Commit Graph

62 Commits

Author SHA1 Message Date
Hamish Knight
3c67271869 [AST] Handle a few more cases in getStartLoc()
Handle PatternBindingDecls with missing var locations, which can
happen for loop iterator vars, and FuncDecls with missing name and
func locations, which can happen for `defer`. Also while here make
sure we set the source location of a parser-produced ErrorExpr.
2025-05-14 11:15:42 +01:00
Doug Gregor
ed6dccf12c Diagnose captured of non-sendable metatypes crossing isolation boundaries
Keep track of all of the type parameters and archetypes that are captured
by a local function or closure. Use that information to diagnose cases
where a non-Sendable metatype crosses an isolation boundary.
2025-02-13 17:07:09 -08:00
Michael Gottesman
791d07d379 Revert "Test fixes"
This reverts commit 9c328a81d1.
2025-02-06 14:04:28 -08:00
Tony Allevato
c5f0200680 Merge pull request #79059 from allevato/json-ast-followups
[ASTDumper] Some followups from the initial JSON PR and macro dumping improvements.
2025-02-04 01:13:46 -05:00
Michael Gottesman
9c328a81d1 Test fixes 2025-02-03 13:35:08 -08:00
Tony Allevato
5fe10ce86a ASTDumper: Label "interface type" -> "interface_type". 2025-01-29 13:55:00 -05:00
Sophia Poirier
5ce7be7e75 [Concurrency] explicit nonisolated specification for closures 2024-03-14 12:24:13 -07:00
Becca Royal-Gordon
8770c7f826 Rework ASTDumper (#68438)
This PR refactors the ASTDumper to make it more structured, less mistake-prone, and more amenable to future changes. For example:

```cpp
  // Before:
  void visitUnresolvedDotExpr(UnresolvedDotExpr *E) {
    printCommon(E, "unresolved_dot_expr")
      << " field '" << E->getName() << "'";
    PrintWithColorRAII(OS, ExprModifierColor)
      << " function_ref=" << getFunctionRefKindStr(E->getFunctionRefKind());
    if (E->getBase()) {
      OS << '\n';
      printRec(E->getBase());
    }
    PrintWithColorRAII(OS, ParenthesisColor) << ')';
  }

  // After:
  void visitUnresolvedDotExpr(UnresolvedDotExpr *E, StringRef label) {
    printCommon(E, "unresolved_dot_expr", label);

    printFieldQuoted(E->getName(), "field");
    printField(E->getFunctionRefKind(), "function_ref", ExprModifierColor);

    if (E->getBase()) {
      printRec(E->getBase());
    }

    printFoot();
  }
```

* Values are printed through calls to base class methods, rather than direct access to the underlying `raw_ostream`.
    * These methods tend to reduce the chances of bugs like missing/extra spaces or newlines, too much/too little indentation, etc.
    * More values are quoted, and unprintable/non-ASCII characters in quoted values are escaped before printing.
* Infrastructure to label child nodes now exists.
    * Some weird breaks from the normal "style", like `PatternBindingDecl`'s original and processed initializers, have been brought into line.
* Some types that previously used ad-hoc dumping functions, like conformances and substitution maps, are now structured similarly to the dumper classes.
* I've fixed the odd dumping bug along the way. For example, distributed actors were only marked `actor`, not `distributed actor`.

This PR doesn't change the overall style of AST dumps; they're still pseudo-S-expressions. But the logic that implements this style is now isolated into a relatively small base class, making it feasible to introduce e.g. JSON dumping in the future.
2023-09-11 23:56:38 -07:00
Abdul Ajetunmobi
f8c737b1ec SR-13976: Improve compiler error message: "partial application of ‘mutating’ method is not allowed” 2021-10-06 19:59:09 +01:00
Robert Widmann
c64427fb6c Construct AutoClosureExpr With Deeper Parent Contexts
AutoClosureExprs created by the constraint system used to be constructed
with the decl context of the constraint system itself. This meant that
autoclosures in expressions nested in closures would initially be
parented onto any enclosing functions rather than the deepest closure
context. When we ran capture analysis and lookup from inside of the body
of these nascent values, we would fail to find declarations brought into
scope by those parent closures. This is especially relevant when
pre-typechecked code is involved since captures for those declarations
will be forced before their bodies have been recontextualized. See
issue #34230 for why we need to force things so early.

The attached test case demonstrates both bugs: The former a bogus lookup
through the parent context that would incorrectly reject this otherwise
well-formed code. The latter is a crash in SILGen when the capture
computation would fail to note $0.

Use the decl context of the solution application target, which is always
going to be the deepest user-written closure expression available to us,
and therefore the deepest scope that can introduce capturable variables.

rdar://79248469
2021-07-06 10:55:10 -07:00
Slava Pestov
1904960829 Sema: Fix a couple of problems with capture analysis and TopLevelCodeDecls
A TopLevelCodeDecl is a local context and any declarations inside
of one must be treated as captures. Furthermore, all the
TopLevelCodeDecl children of a source file are peers, and can
see each other's bindings, so don't perform an exact match on the
DeclContext.

Part of <rdar://problem/23051362> / <https://bugs.swift.org/browse/SR-3528>.
2019-12-19 23:46:01 -05:00
Slava Pestov
0ade7b70d9 AST: Type::subst() preserves TypeAliasType sugar
Fixes <rdar://problem/45313760>.
2019-09-24 17:42:15 -04:00
David Ungar
f64033a2d2 Manual rebase with master 2019-08-06 22:13:20 -07:00
Slava Pestov
1a82712499 Sema: Remove incorrect and incomplete forward capture analysis
Sema does not have enough information to diagnose these problems correctly.

Also, there was an unimplemented case in the analysis; if a closure did not
yet have computed captures, we'd add it to the ForwardCapturedFuncs list,
but nothing ever looked at that list.
2019-06-27 20:59:10 -04:00
David Ungar
663760e3b7 ASTOOScope ontology 2019-05-28 10:48:22 -07:00
Vinicius Vendramini
39d3963131 Fix broken tests
- Many tests got broken because of two things:
  - AST dump now outputs to stdout, but many tests expected stderr. This was a straightforward fix.
  - Many tests call swift with specific parameters; specifically, many call `swift frontend` directly. This makes them go through the compiler in unexpected ways, and specifically it makes them not have primary files, which breaks the new AST dump implementation. This commit adds the old implementation as a fallback for those cases, except it dumps to `stdout` to maintain some consistence.

Finally, the `/test/Driver/filelists.swift` failed for unknown reasons. It seems its output now had some lines out of order, and fixing the order made the test pass. However, as the reasons why it failed are unknown, this fix might not have been a good idea. Corrections are welcome.
2018-11-14 13:38:01 -02:00
Davide Italiano
4fed893d74 [AST] Preserve sugar for generic typealiases.
<rdar://problem/43110802>
2018-09-17 15:34:37 -07:00
Mark Lacey
78d83e5703 Use %target-typecheck-verify-swift where possible. 2018-07-26 23:13:43 -07:00
Brent Royal-Gordon
70f788ed7f Merge pull request #17656 from brentdax/thats-what-a-diagnostics-all-about
[Sema] Improve error for inout on conversion
2018-07-11 16:19:34 -07:00
Brent Royal-Gordon
7545b1945f [Sema] Improve error for inout on conversion
The diagnostic when a user attempts to pass an argument requiring an implicit conversion (e.g. declared as a subclass, type conforming to protocol, etc.) to an inout parameter seems to be confusing for users—see e.g. SR-8155, SR-8148. This change replaces it with a more specific diagnostic which clearly suggests a solution. It also includes a fix-it suggesting the user change the type of the original variable if it’s a local with a simple type signature.
2018-07-10 12:31:36 -07:00
John McCall
9bee3cac5a Generalize storage implementations to support generalized accessors.
The storage kind has been replaced with three separate "impl kinds",
one for each of the basic access kinds (read, write, and read/write).
This makes it far easier to mix-and-match implementations of different
accessors, as well as subtleties like implementing both a setter
and an independent read/write operation.

AccessStrategy has become a bit more explicit about how exactly the
access should be implemented.  For example, the accessor-based kinds
now carry the exact accessor intended to be used.  Also, I've shifted
responsibilities slightly between AccessStrategy and AccessSemantics
so that AccessSemantics::Ordinary can be used except in the sorts of
semantic-bypasses that accessor synthesis wants.  This requires
knowing the correct DC of the access when computing the access strategy;
the upshot is that SILGenFunction now needs a DC.

Accessor synthesis has been reworked so that only the declarations are
built immediately; body synthesis can be safely delayed out of the main
decl-checking path.  This caused a large number of ramifications,
especially for lazy properties, and greatly inflated the size of this
patch.  That is... really regrettable.  The impetus for changing this
was necessity: I needed to rework accessor synthesis to end its reliance
on distinctions like Stored vs. StoredWithTrivialAccessors, and those
fixes were exposing serious re-entrancy problems, and fixing that... well.
Breaking the fixes apart at this point would be a serious endeavor.
2018-06-30 05:19:03 -04:00
Brent Royal-Gordon
fb79b8f44e Indicate which closures are escaping in AST dumps 2018-06-10 14:03:01 -07:00
Mark Rowe
62eb12b652 Include source ranges for decls in the AST dump. 2018-05-17 10:50:19 -07:00
Ben Langmuir
f20586b3d8 Revert "Include source ranges for statements, declarations, and parameter lists in the AST dump" 2018-05-17 09:53:05 -07:00
Mark Rowe
28af6959b8 Include source ranges for decls in the AST dump. 2018-05-09 11:15:35 -07:00
Doug Gregor
e82e7ee908 [Type checker] Use BoundNameAliasType for all typealiases.
Rather than relying on the NameAliasType we get by default for references
to non-generic typealiases, use BoundNameAliasType consistently to handle
references to typealiases that are formed by the type checker.
2018-03-25 21:35:16 -07:00
Joe Groff
43f841e585 Sema: Don't raise bogus escape diagnostics about captures in closures with errors. 2017-02-26 08:27:19 -08:00
Brian Gesiak
ff7f01c7e5 [AST] Missing space when printing generic params
Using `-dump-parse` on `func foo<T>(bar: T) {}` results in:

```
(source_file
  (func_decl "foo(bar:)"<T>
    (parameter_list
      (parameter "bar" apiName=bar))
    (brace_stmt)))
```

Notice there is no space between "foo(bar:)" and <T>.

Add a space to correct the formatting error.
2017-01-04 15:58:02 -05:00
Slava Pestov
2c6b9f71b6 AST: Change TypeAliasDecls to store an interface type as their underlying type
- TypeAliasDecl::getAliasType() is gone. Now, getDeclaredInterfaceType()
  always returns the NameAliasType.

- NameAliasTypes now always desugar to the underlying type as an
  interface type.

- The NameAliasType of a generic type alias no longer desugars to an
  UnboundGenericType; call TypeAliasDecl::getUnboundGenericType() if you
  want that.

- The "lazy mapTypeOutOfContext()" hack for deserialized TypeAliasDecls
  is gone.

- The process of constructing a synthesized TypeAliasDecl is much simpler
  now; instead of calling computeType(), setInterfaceType() and then
  setting the recursive properties in the right order, just call
  setUnderlyingType(), passing it either an interface type or a
  contextual type.

  In particular, many places weren't setting the recursive properties,
  such as the ClangImporter and deserialization. This meant that queries
  such as hasArchetype() or hasTypeParameter() would return incorrect
  results on NameAliasTypes, which caused various subtle problems.

- Finally, add some more tests for generic typealiases, most of which
  fail because they're still pretty broken.
2016-12-15 22:46:15 -08:00
Slava Pestov
c4dbf91676 AST Dumper: Don't canonicalize interface types 2016-12-01 13:00:19 -08:00
Slava Pestov
09980dd3c1 AST: getType() => getInterfaceType() 2016-11-29 03:05:26 -07:00
David Farler
b7d17b25ba Rename -parse flag to -typecheck
A parse-only option is needed for parse performance tracking and the
current option also includes semantic analysis.
2016-11-28 10:50:55 -08:00
Slava Pestov
a1eef126ba AST: Don't print "aka <<desugared type>>" for generic function types
This was causing us to emit diagnostics talking about τ_m_n, which is
not helpful.

Now that generic function types print sanely, print them in a few
places where we were previously printing PolymorphicFunctionTypes.
2016-09-15 21:47:57 -07:00
Doug Gregor
4c45885ffd [Name lookup] Diagnose attempts to reference not-yet-declared local variables.
Until the point where ASTScope-based unqualified name lookup is the
default, unqualified name lookup can still find names declared *after*
the source location. The 'hasType' check no longer makes sense, so actually
check the source location of the entity we found.
2016-09-15 10:21:30 -07:00
Dmitri Gribenko
d175b3b66d Migrate FileCheck to %FileCheck in tests 2016-08-10 23:52:02 -07:00
Jordan Rose
f42158b12e Revert "[Sema] ban multi-arguments to tuple coercion" (#3922)
It breaks cases where there really is a single unlabeled argument of tuple type, like this:

  let pairs = [(1, "A"), (2, "B")]
  print(pairs.map { $0.0 })
2016-08-01 19:22:19 -07:00
Daniel Duan
c9b73dacc2 [Sema] ban multi-arguments to tuple coercion
Implements part of SE-0110. Single argument in closures will not be accepted if
there exists explicit type with a number of arguments that's not 1.

```swift
let f: (Int, Int) -> Void = { x in } // this is now an error
```

Note there's a second part of SE-0110 which could be considered additive,
which says one must add an extra pair of parens to specify a single arugment
type that is a tuple:

```swift
let g ((Int, Int)) -> Void = { y in } // y should have type (Int, Int)
```

This patch does not implement that part.
2016-07-31 16:22:57 -07:00
Slava Pestov
f8f6d61d19 Fixes for typealiases involving generics (#3811)
* Serialization: Another fix for generic typealiases

Fixes <https://bugs.swift.org/browse/SR-1889>.

* Sema: Fix FindCapturedVars to look through typealiases

Fixes <https://bugs.swift.org/browse/SR-1781>.
2016-07-27 21:35:37 -07:00
Jordan Rose
ebdee21464 Handle top-level vars' and closure params' access specially.
Parameters are normally given 'private' access, because they can only
be referred to within the body of the owning function. However,
single-expression closures allow a parameter to appear in a constraint
system in the containing context. Mark closure parameters as
'fileprivate' instead.

Similarly, 'private' at the top level is normally equivalent to
'fileprivate', but not for a decl that appears within top-level
imperative code, which has a TopLevelCodeDecl context. This currently
only happens for bindings in a top-level 'guard' statement; mark
these variables and constants as 'fileprivate' as well.

More progress on SE-0025 ('private' and 'fileprivate').
2016-07-25 20:20:58 -07:00
Slava Pestov
c870052520 Sema: Give capture analysis ability to sniff out uses of dynamic 'Self'
This also adds some tests for the existing generic parameter
capture logic, which was only tested as part of SILGen tests
until now.

Also, move capture analysis into a new TypeCheckCaptures.cpp file.
2016-06-27 18:37:52 -07:00
Trent Nadeau
0cc851568a Updated tests to use @discardableResult and _ = . 2016-05-11 22:53:38 -04:00
Manav Gabhawala
7928140f79 [SE-0046] Implements consistent function parameter labels by discarding extraneous parameter names and adding _ where necessary 2016-04-06 20:21:58 -04:00
Daniel Duan
780b58a9a5 [Parser] update tests for 'inout' syntax adjustment 2016-02-26 01:33:22 -08:00
David Farler
3f635d04c7 Reinstante var bindings in refutable patterns, except function parameters.
This reverts commits: b96e06da44,
                      8f2fbdc93a,
                      93b6962478,
                      64024118f4,
                      a759ca9141,
                      3434f9642b,
                      9f33429891,
                      47c043e8a6.

This commit leaves 'var' on function parameters as a warning to be
merged into Swift 2.2. For Swift 3, this will be an error, to be
converted in a follow-up.
2016-01-29 15:27:08 -08:00
Chris Willmore
983a674e0c Make use of curried function declaration syntax an error.
<rdar://problem/23111018>
2016-01-20 21:57:38 -08:00
Chris Willmore
30af42fda9 Add warning that curried function decl syntax is going away.
<rdar://problem/23111018>
2015-11-02 15:45:11 -08:00
David Farler
3434f9642b Disallow 'var' pattern bindings in if, while, and guard statements
Make the following patterns illegal:

  if var x = ... {
    ...
  }

  guard var x = ... else {
    ...
  }

  while var x = ... {
    ...
  }

And provide a replacement fixit 'var' -> 'let'.

rdar://problem/23172698

Swift SVN r32855
2015-10-24 01:46:30 +00:00
Jordan Rose
64100010dd Allow capturing from another TopLevelCodeDecl.
Otherwise, we'll fail to capture "locals" declared in top-level guard
statements. This led to an assertion failure in SILGen.

Depends on previous commit.

rdar://problem/21997265

Swift SVN r30812
2015-07-30 19:47:58 +00:00
Chris Lattner
0e20f24b95 fix <rdar://problem/18734297> Reject access to local variables from local types
init()'s implicitly evaluate the initial values for properties, and we aren't modeling
that correctly in the AST.  This prevented the closure checker from noticing these 
accesses, leading to SILGen crashing later.  In the absence of proper AST modeling of
this, add special case handling for them.



Swift SVN r29508
2015-06-19 06:15:19 +00:00
Slava Pestov
7319a97ab4 Sema: Rewrite witness method calls as ApplyExpr + DeclRefExpr
Special-casing these as MemberRefExprs created an asymmetry
where unbound archetype instance methods (<T : P> T.f) could
not be represented. Treating class and protocol methods
uniformly also eliminates a handful of special cases around
MemberRefExpr.

SILGen's RValue and call emission peepholes now have to know
about DeclRefExprs that point to protocol methods.

Finally, generalize the diagnostic for partially applied
mutating methods to any partially applied function with an
inout parameter, since this is not supported.

Fixes <rdar://problem/20564672>.

Swift SVN r29298
2015-06-04 15:57:58 +00:00