Commit Graph

591 Commits

Author SHA1 Message Date
Suyash Srijan
90d96881bb [Typechecker] Do not check tuple labels for a function call
It's okay to have two function parameters with the same external label, as long as the internal labels are different. If not, we already emit a diagnostic for it, so no need to check
2019-05-17 00:13:42 +01:00
Suyash Srijan
935128cd3b Merge branch 'master' into fix/duplicate-tuple-labels 2019-05-15 22:38:52 +01:00
Suyash Srijan
a332eb6b4d [Typechecker] Don't add empty identifiers to the set 2019-05-15 02:26:04 +01:00
Suyash Srijan
71fee96093 [Typechecker] Ban tuples with duplicate labels 2019-05-14 19:43:46 +01:00
Slava Pestov
b103fed866 Sema: Remove old diagnostics for misplaced InOutExpr 2019-05-07 23:10:49 -04:00
Joe Groff
22793b4567 Fixes for opaque return types on local functions.
- In Sema, don't traverse nested declarations while deducing the opaque return type. This would
  cause returns inside nested functions to clobber the return type of the outer function.
- In IRGen, walk the list of opaque return types we keep in the SourceFile already for type
  reconstruction, instead of trying to visit them ad-hoc as part of walking the AST, since
  IRGen doesn't normally walk the bodies of function decls directly.

Fixes rdar://problem/50459091
2019-05-03 16:53:21 -07:00
Pavel Yaskevich
caad4a817b [MiscDiagnostics] Run opaque return checker only if all of the return expressions are correct 2019-04-29 18:42:28 -07:00
Suyash Srijan
a58db50b4f [Diagnostics] Update diagnostics for T! to Any (#23617)
Add a tailored diagnostic for the case where implicitly unwrapped optional is coerced to `Any`
2019-04-18 15:23:52 -07:00
Joe Groff
0fcc7cdac0 Check the underlying type of get-only computed properties with opaque return types. 2019-04-17 14:46:22 -07:00
Joe Groff
f008019bda Sema: Infer the underlying type for opaque return types from function bodies. 2019-04-17 14:43:32 -07:00
Brent Royal-Gordon
7a41c3874b Permit subscripting types without using .self 2019-04-10 23:17:04 -07:00
Slava Pestov
d82b88cd82 Merge pull request #23907 from slavapestov/noescape-parameter-call-restriction
Re-implement "no-escape parameter call restriction" as SIL pass
2019-04-09 19:38:31 -04:00
Slava Pestov
3f58eb745b Merge pull request #23878 from slavapestov/reimplement-escaping-diagnostics
Reimplement escaping diagnostics
2019-04-09 16:40:04 -04:00
Slava Pestov
6a34ed0120 Sema: Remove NPCR diagnostics 2019-04-09 16:35:25 -04:00
Slava Pestov
e214156abf Sema: Remove escaping capture diagnostics
I'm about to replace all of this with a SIL pass.
2019-04-09 15:02:14 -04:00
John McCall
4f4d64b93e Various improvements to the variable-is-never-mutated diagnostic.
The main fixes here are:
- we weren't looking through open-existentials in the l-value
- we weren't handling mutating gets correctly unless CSApply wrapped
  the base in an InOutExpr, which seems to be multifile-sensitive
- we were missing diagnostics in some cases involving subscripts

A better fix would be to re-introduce LValueAccessKind, but I wanted
a workable short-term fix that I could try to get into 5.1.

Fixes rdar://49482742, which is specific to the lazy-getter problem.
2019-04-08 18:43:24 -04:00
Michael Gottesman
564b4fc11a [silgenpattern] Fix some stack-use-after-free errors caused by iterating over an Optional<ArrayRef<T>>.
Specifically the bad pattern was:

```
   for (auto *vd : *caseStmt->getCaseBodyVariables()) { ... }
```

The problem is that the optional is not lifetime extended over the for loop. To
work around this, I changed the API of CaseStmt's getCaseBodyVariable methods to
never return the inner Optional<MutableArrayRef<T>>. Now we have the following 3
methods (ignoring const differences):

1. CaseStmt::hasCaseBodyVariables().

2. CaseStmt::getCaseBodyVariables(). Asserts if the case body variable array was
   never specified.

3. CaseStmt::getCaseBodyVariablesOrEmptyArray(). Returns either the case body
   variables array or an empty array if we were never given any case body
   variable array.

This should prevent anyone else in the future from hitting this type of bug.

radar://49609717
2019-04-04 13:34:36 -07:00
Michael Gottesman
7b0d8455ca [ast][silgen] Wire up the case body var decls and use them in SILGenPattern emission to fix the evil fallthrough bug.
rdar://47467128
2019-04-03 23:51:06 -07:00
Michael Gottesman
ed94b13d3f [ast] Add a helper method for checking if a pattern contains a var decl and adopt it. 2019-04-03 13:38:03 -07:00
Slava Pestov
1caf2c7544 Sema: Fix code completion crash when a ParamDecl hasn't had its type set yet
We set the type of ParamDecls when applying solutions in the normal path, but
sometimes code completion will type check an expression inside a closure without
checking the outer expression. In this case, we may have inferred a type for
the ParamDecl, but we don't write it back.

Instead, just look at the DeclRefExpr's type.

Fixes <rdar://problem/42098113>.
2019-04-02 00:25:24 -04:00
Slava Pestov
88e41231cc Sema: Skip non-single-expression closure bodies in MiscDiagnostics
This is a defensive move to avoid duplicated work and guard against crashes
when a multi-expression closure body or TapExpr has not been type checked yet.

Fixes <rdar://problem/48852402>.
2019-04-02 00:25:24 -04:00
Slava Pestov
1467f554f5 AST: Remove ArgumentShuffleExpr 2019-03-31 01:36:19 -04:00
Slava Pestov
e212d4567f Sema: Collect varargs into an ArrayExpr and use DefaultArgumentExpr
Instead of building ArgumentShuffleExprs, lets just build a TupleExpr,
with explicit representation of collected varargs and default
arguments.

This isn't quite as elegant as it should be, because when re-typechecking,
SanitizeExpr needs to restore the 'old' parameter list by stripping out
the nodes inserted by type checking. However that hackery is all isolated
in one place and will go away soon.

Note that there's a minor change the generated SIL. Caller default
arguments (#file, #line, etc) are no longer delayed and are instead
evaluated in their usual argument position. I don't believe this actually
results in an observable change in behavior, but if it turns out to be
a problem, we can pretty easily change it back to the old behavior with a
bit of extra work.
2019-03-31 01:36:19 -04:00
Slava Pestov
e2c9c52c93 AST/Sema/SILGen: Implement tuple conversions
TupleShuffleExpr could not express the full range of tuple conversions that
were accepted by the constraint solver; in particular, while it could re-order
elements or introduce and eliminate labels, it could not convert the tuple
element types to their supertypes.

This was the source of the annoying "cannot express tuple conversion"
diagnostic.

Replace TupleShuffleExpr with DestructureTupleExpr, which evaluates a
source expression of tuple type and binds its elements to OpaqueValueExprs.

The DestructureTupleExpr's result expression can then produce an arbitrary
value written in terms of these OpaqueValueExprs, as long as each
OpaqueValueExpr is used exactly once.

This is sufficient to express conversions such as (Int, Float) => (Int?, Any),
as well as the various cases that were already supported, such as
(x: Int, y: Float) => (y: Float, x: Int).

https://bugs.swift.org/browse/SR-2672, rdar://problem/12340004
2019-03-27 18:12:05 -04:00
Slava Pestov
1864f6f679 AST: Introduce ClassDecl::isSuperclassOf() 2019-03-26 18:42:59 -04:00
Michael Gottesman
0680ce1bab Merge pull request #23448 from nathawes/fix-case-var-for-relatedidents-cursorinfo-and-rename
[sourcekitd] Improve CursorInfo, RelatedIdents, and local rename to better handle VarDecls involved in case fallthroughs
2019-03-21 15:52:59 -07:00
Slava Pestov
d470e9df4d AST: Split off ArgumentShuffleExpr from TupleShuffleExpr
Right now we use TupleShuffleExpr for two completely different things:

- Tuple conversions, where elements can be re-ordered and labels can be
  introduced/eliminated
- Complex argument lists, involving default arguments or varargs

The first case does not allow default arguments or varargs, and the
second case does not allow re-ordering or introduction/elimination
of labels. Furthermore, the first case has a representation limitation
that prevents us from expressing tuple conversions that change the
type of tuple elements.

For all these reasons, it is better if we use two separate Expr kinds
for these purposes. For now, just make an identical copy of
TupleShuffleExpr and call it ArgumentShuffleExpr. In CSApply, use
ArgumentShuffleExpr when forming the arguments to a call, and keep
using TupleShuffleExpr for tuple conversions. Each usage of
TupleShuffleExpr has been audited to see if it should instead look at
ArgumentShuffleExpr.

In sequent commits I plan on redesigning TupleShuffleExpr to correctly
represent all tuple conversions without any unnecessary baggage.

Longer term, we actually want to change the representation of CallExpr
to directly store an argument list; then instead of a single child
expression that must be a ParenExpr, TupleExpr or ArgumentShuffleExpr,
all CallExprs will have a uniform representation and ArgumentShuffleExpr
will go away altogether. This should reduce memory usage and radically
simplify parts of SILGen.
2019-03-21 02:18:41 -04:00
Nathan Hawes
9291201e32 [sourcekitd][Refactoring] Fix renaming of var decls in fallthrough case statements
We weren't renaming all occurrences of 'x' in the cases like the below:

  case .first(let x), .second(let x):
    print("foo \(x)")
    fallthrough
  case .third(let x):
    print("bar \(x)")

We would previously only rename occurrences within the case statement the query
was made in (ignoring fallthroughs) and for cases with multiple patterns (as in
the first case above) we would only rename the occurrence in the first pattern.
2019-03-20 14:38:08 -07:00
Michael Gottesman
b1a7b488fd [sema] Wire up VarDecl parent pointers for case stmt related Var Decls
This is in preparation for fixing issues around SILGenPattern fallthrough
emission and bad rename/edit all in scope of case stmt var decls. Specifically,
I am going to ensure that we can get from any VarDecl in the following to any
other VarDecl:

switch x {
case .a(let v1, let v2), .b(let v1, let v2):
  ...
  fallthrough
case .c(let v1, let v2), .d(let v1, let v2):
  ...
}

This will be done by:

1. Pointing the var decls in .d at the corresponding var decls in .c.
2. Pointing the var decls in .c at the corresponding var decls in .b.
3. Pointing the var decls in .b at the corresponding var decls in .a.
4. Pointing the var decls in .a at the case stmt. Recognizing that we are asking
for the next VarDecl, but have a case stmt, we check if we have a fallthrough
case stmt. If so, follow down the fallthrough case stmts until you find a
fallthrough case stmt that doesn't fallthrough itself and then return the
corresponding var decl in the last case label item in that var decl (in the
above .d).

In a subsequent commit I am going to add case body var decls. The only change as
a result of that is that I will insert them into the VarDecl double linked list
after the last case var decl of each case stmt.
2019-03-18 14:13:10 -07:00
Rintaro Ishizaki
ce30a72e2a [Sema] Add defensive guard for implicit use of self in closure check
Add assetion along with defensive guard to avoid crashing in release
build. Hopefully, sourcekitd Stress Tester find a reproducer for the
crash.

rdar://problem/47895109
2019-02-25 17:08:02 -08:00
Slava Pestov
12fa026f99 Sema: Use AbstractStorageDecl::getValueInterfaceType() in a couple of spots 2019-02-07 23:46:31 -05:00
Jordan Rose
aabcabfdf3 Merge pull request #21983 from KingOfBrian/bugfix/SR-964-As-Member-master
[Sema] Report unused newValue when getter is accessed in custom setter
2019-02-04 14:46:33 -08:00
Slava Pestov
69f2aba2ff Merge pull request #22158 from pschuh/s-2
NilLiteralExpr now is lowered directly into SIL.
2019-01-28 15:40:10 -05:00
Parker Schuh
6ca70c6720 NilLiteralExpr now is lowered directly into SIL.
Instead of constructing calls to
ExpressibleByNilLiteral.init(nilLiteral: ()) in CSApply.cpp, just
annotate NilLiteralExpr with the selected construtor and do the actual
construction during SILGen.

For context, StringLiteralExpr already behaves this way.
2019-01-28 10:00:52 -08:00
Pavel Yaskevich
6134533580 [MiscDiagnostics] Remove obsolete invalid partial application diagnostics
Diagnostics for cases like these has been moved to new diagnostic framework.
2019-01-25 14:18:19 -08:00
Ding Ye
421d6b065a [Sema] Improve diagnostics for variable_never_mutated in case of for-each loop's binding.
The diagnostics for `variable_never_mutated` always suggests
changing `var` to `let`, which is misleading in case of
for-each loops where explicitly immutable context applies.
This patch adds some variety to the message to make it appropriate.

Resolves: SR-9732
2019-01-24 16:54:57 +11:00
Brian King
3c6fc86c5a Check for getter by member reference 2019-01-18 09:49:23 -05:00
Parker Schuh
f5859ff46e Rename NameAliasType to TypeAliasType. 2019-01-09 16:47:13 -08:00
Slava Pestov
8cfe7377e3 Sema: Ban single-element tuple expressions
Fixes <rdar://problem/30384023>, <rdar://problem/41474370>,
and <https://bugs.swift.org/browse/SR-8109>.
2018-12-15 00:07:04 -05:00
Slava Pestov
6c012b2aec AST: Remove some unnecessary LazyResolver * parameters from ASTContext methods 2018-12-07 20:39:27 -05:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
Brent Royal-Gordon
9bd1a26089 Implementation for SE-0228: Fix ExpressibleByStringInterpolation (#20214)
* [CodeCompletion] Restrict ancestor search to brace

This change allows ExprParentFinder to restrict certain searches for parents to just AST nodes within the nearest surrounding BraceStmt. In the string interpolation rework, BraceStmts can appear in new places in the AST; this keeps code completion from looking at irrelevant context.

NFC in this commit, but keeps code completion from crashing once TapExpr is introduced.

* Remove test relying on ExpressibleByStringInterpolation being deprecated

Since soon enough, it won’t be anymore.

* [AST] Introduce TapExpr

TapExpr allows a block of code to to be inserted between two expressions, accessing and potentially mutating the result of its subexpression before giving it to its parent expression. It’s roughly equivalent to this function:

  func _tap<T>(_ value: T, do body: (inout T) throws -> Void) rethrows -> T {
    var copy = value
    try body(&copy)
    return copy
  }

Except that it doesn’t use a closure, so no variables are captured and no call frame is (even notionally) added.

This commit does not include tests because nothing in it actually uses TapExpr yet. It will be used by string interpolation.

* SE-0228: Fix ExpressibleByStringInterpolation

This is the bulk of the implementation of the string interpolation rework. It includes a redesigned AST node, new parsing logic, new constraints and post-typechecking code generation, and new standard library types and members.

* [Sema] Rip out typeCheckExpressionShallow()

With new string interpolation in place, it is no longer used by anything in the compiler.

* [Sema] Diagnose invalid StringInterpolationProtocols

StringInterpolationProtocol informally requires conforming types to provide at least one method with the base name “appendInterpolation” with no (or a discardable) return value and visibility at least as broad as the conforming type’s. This change diagnoses an error when a conforming type does not have a method that meets those criteria.

* [Stdlib] Fix map(String.init) source break

Some users, including some in the source compatibility suite, accidentally used init(stringInterpolationSegment:) by writing code like `map(String.init)`. Now that these intializers have been removed, the remaining initializers often end up tying during overload resolution. This change adds several overloads of `String.init(describing:)` which will break these ties in cases where the compiler previously selected `String.init(stringInterpolationSegment:)`.

* [Sema] Make callWitness() take non-mutable arrays

It doesn’t actually need to mutate them.

* [Stdlib] Improve floating-point interpolation performance

This change avoids constructing a String when interpolating a Float, Double, or Float80. Instead, we write the characters to a fixed-size buffer and then append them directly to the string’s storage.

This seems to improve performance for all three types, but especially for Double and Float80, which cannot always fit into a small string when stringified.

* [NameLookup] Improve MemberLookupTable invalidation

In rare cases usually involving generated code, an overload added by an extension in the middle of a file would not be visible below it if the type had lazy members and the same base name had already been referenced above the extension. This change essentially dirties a type’s member lookup table whenever an extension is added to it, ensuring the entries in it will be updated.

This change also includes some debugging improvements for NameLookup.

* [SILOptimizer] XFAIL dead object removal failure

The DeadObjectRemoval pass in SILOptimizer does not currently remove reworked string interpolations as well as the old design because their effects cannot be described by @_effects(readonly). That causes a test failure on Linux. This change temporarily silences that test. The SILOptimizer issue has been filed as SR-9008.

* Confess string interpolation’s source stability sins

* [Parser] Parse empty interpolations

Previously, the parser had an odd asymmetry which caused the same function to accept foo(), but reject “\()”. This change fixes the issue.

Already tested by test/Parse/try.swift, which uses this construct in one of its throwing interpolation tests.

* [Sema] Fix batch-mode-only lazy var bug

The temporary variable used by string interpolation needs to be recontextualized when it’s inserted into a synthesized getter. Fixes a compilation failure in Alamofire.

I’ll probably follow up on this bug a bit more after merging.
2018-11-02 19:16:03 -07:00
mzp
eff1b9eb63 use bool(...) to produce bool value 2018-09-11 10:57:22 +09:00
mzp
4d072543fb add space to fit with coding-style 2018-09-11 10:57:22 +09:00
mzp
f5ed8981b6 [Sema] Warn for a function value in string interpolation
Resolves https://bugs.swift.org/browse/SR-8464
2018-09-11 08:09:42 +09:00
Jordan Rose
5dace224a0 Merge pull request #18623 from dingobye/sr8453
[Sema] Warn for redundant access-level modifiers on setters or used in an extension.
2018-09-05 17:44:26 -07:00
Slava Pestov
45b2fe249e Sema: Remove some uses of TypeBase::getUnlabeledType() 2018-08-28 22:36:02 -07:00
John McCall
b80618fc80 Replace materializeForSet with the modify coroutine.
Most of this patch is just removing special cases for materializeForSet
or other fairly mechanical replacements.  Unfortunately, the rest is
still a fairly big change, and not one that can be easily split apart
because of the quite reasonable reliance on metaprogramming throughout
the compiler.  And, of course, there are a bunch of test updates that
have to be sync'ed with the actual change to code-generation.

This is SR-7134.
2018-08-27 03:24:43 -04:00
Jordan Rose
537954fb93 [AST] Rename several DeclContext methods to be clearer and shorter (#18798)
- getAsDeclOrDeclExtensionContext -> getAsDecl

This is basically the same as a dyn_cast, so it should use a 'getAs'
name like TypeBase does.

- getAsNominalTypeOrNominalTypeExtensionContext -> getSelfNominalTypeDecl
- getAsClassOrClassExtensionContext -> getSelfClassDecl
- getAsEnumOrEnumExtensionContext -> getSelfEnumDecl
- getAsStructOrStructExtensionContext -> getSelfStructDecl
- getAsProtocolOrProtocolExtensionContext -> getSelfProtocolDecl
- getAsTypeOrTypeExtensionContext -> getSelfTypeDecl (private)

These do /not/ return some form of 'this'; instead, they get the
extended types when 'this' is an extension. They started off life with
'is' names, which makes sense, but changed to this at some point.  The
names I went with match up with getSelfInterfaceType and
getSelfTypeInContext, even though strictly speaking they're closer to
what getDeclaredInterfaceType does. But it didn't seem right to claim
that an extension "declares" the ClassDecl here.

- getAsProtocolExtensionContext -> getExtendedProtocolDecl

Like the above, this didn't return the ExtensionDecl; it returned its
extended type.

This entire commit is a mechanical change: find-and-replace, followed
by manual reformatted but no code changes.
2018-08-17 14:05:24 -07:00
Slava Pestov
f2ae23a2ab AST: Remove TupleType::getElementForScalarInit()
This is a legacy holdover from when tuple types had default
arguments, and also the constraint solver's matching of function
types pre-SE-0110.

Well, move the last live usage to CSDiag, where it can die a slow
painful death over time. The other usages were not doing anything.
2018-08-11 22:26:44 -07:00