Commit Graph

937 Commits

Author SHA1 Message Date
Slava Pestov
0211fd7025 AST: Make absence of discriminator into a fatal error
... even in noassert builds. This is always a miscompile and should
be prevented.
2024-06-11 09:01:39 -04:00
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Cal Stephens
3315cab336 Merge branch 'main' into cal--fix-70089 2024-03-18 16:44:09 -07:00
Holly Borla
78384d596d [Concurrency] Add ExtractFunctionIsolationExpr to represent the isolation
of a dynamically isolated function value in the AST.
2024-03-13 19:55:15 -07:00
Cal Stephens
f21aee7baa Improve quality of 'capture self explicitly to enable implicit self in this closure' and 'variable other than self captured here under the name self does not enable implicit self' diagnostics 2024-03-12 10:45:17 -07:00
Cal Stephens
94dcf9bc70 Fix edge cases related to nested autoclosures, invalid weak self unwrapping 2024-03-11 07:42:44 -07:00
Anthony Latsis
5b7a8b6705 [NFC] AST: Rename MemberTypeReprQualifiedIdentTypeRepr 2024-03-02 14:59:37 +03:00
Anthony Latsis
7e7f6d8d61 [NFC] AST: Construct SimpleIdentTypeRepr & GenericIdentTypeRepr through IdentTypeRepr 2024-03-02 08:28:47 +03:00
Anthony Latsis
68746a0579 [NFC] AST: Rename IdentTypeReprUnqualifiedIdentTypeRepr 2024-03-02 08:28:47 +03:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Anthony Latsis
8bea09d2ad [NFC] AST: Refactor for recursive MemberTypeRepr representation 2024-02-09 17:23:38 +03:00
Anthony Latsis
d6fd424560 [NFC] MemberTypeRepr: getBaseComponent()getRoot() 2024-02-09 17:22:05 +03:00
Hamish Knight
d73e394ea7 Allow implicit last expression results for if/switch expressions
Allow implicitly treating the last expression of
the branch as the result, behind the experimental
feature `ImplicitLastExprResults`.
2024-02-07 18:14:22 +00:00
Hamish Knight
16cfca4186 [ASTWalker] NFC: Rename SkipChildren -> SkipNode
This better describes what the action currently
does, and allows us to re-introduce `SkipChildren`
with the correct behavior.
2024-02-05 15:27:25 +00:00
Pavel Yaskevich
4debaf2c5d [AST] Introduce a new conversion expression - ActorIsolationErasure
To be used in situations when a global actor isolation is stripped
from a function type in argument positions and could be extended in
the future to cover more if needed.
2024-02-01 13:28:25 -08:00
Slava Pestov
80205ecf9c Merge pull request #71241 from slavapestov/ncgenerics-fixes
Non-copyable generics fixes
2024-02-01 07:18:29 -05:00
Slava Pestov
4a46717325 Distributed: Fixes for non-copyable generics 2024-01-31 21:55:52 -05:00
Hamish Knight
0a4c029cfc [AST] Introduce UnreachableExpr
This models the conversion from an uninhabited
value to any type, and allows us to get rid of
a couple of places where we'd attempt to drop
the return statement instead.
2024-01-30 14:08:54 +00:00
Hamish Knight
9b64990d24 [AST] Remove the "single expression body" bit
Remove this bit from function decls and closures.
Instead, for closures, infer it from the presence
of a single return or single expression AST node
in the body, which ought to be equivalent, and
automatically takes result builders into
consideration. We can also completely drop this
query from AbstractFunctionDecl, replacing it
instead with a bit on ReturnStmt.
2024-01-30 14:08:54 +00:00
Michael Gottesman
4768d017b8 [ast] Hide CapturedValue(OpaqueValueExpr *) so that it only can be used by TypeLowering.
The reason why I am doing this is before this commit despite the fact that
CapturedValue was only used by TypeLowering, this constructor was exposed to the
entire rest of the compiler. This made it so that other code (like the
AbstractClosureExpr::getIsolationCrossing() that I added in the previous series
of commits) would have to handle that API even though there was nothing to
handle just in case someone added something in the future.

Rather than create such a burden on the rest of the compiler, in this commit, we
instead hide said constructor and make it only accessible from
TypeLowering. This creates a barrier from new uses appearing in AST and make it
reasonable for code in the AST that will never see things from TypeLowering
(like the ACE API I mentioned above) just assert on that case without needing to
worry about additional uses cropping in easily by mistake.
2024-01-26 13:13:03 -08:00
Michael Gottesman
7c79a24a1f [region-isolation] Values that are captured by an actor isolated closures are transferred to that closure.
This commit makes it so that we treat values captured by an actor isolated
closure as being transferred to that closure. I also introduced a new diagnostic
for these warnings that puts the main warning on the capture point of the value
so the user is able to see the actual capture that causes the transfer to occur:

```swift
  nonisolated func testLocal2() async {
    let l = NonSendableKlass()

    // This is not safe since we use l later.
    self.assumeIsolated { isolatedSelf in
      isolatedSelf.ns = l
    }

    useValue(l) // expected-note {{access here could race}}
  }
```

```
test.swift:74:14: warning: main actor-isolated closure captures value of non-Sendable type 'NonSendableKlass' from nonisolated context; later accesses to value could race
    useValue(x) // expected-warning {{main actor-isolated closure captures value of non-Sendable type 'NonSendableKlass' from nonisolated context; later accesses to value could race}}
             ^
test.swift:76:12: note: access here could race
  useValue(x) // expected-note {{access here could race}}
           ^
```

One thing to keep in mind is that if we have a function argument being captured
in this way, we still emit the "call site passes `self`" error. I am going to
begin cleaning that up in the next commit in this PR so that we emit a better
error here. But it makes sense to split these into two separate commits since
they are doing different things.

rdar://121345525
2024-01-25 20:40:56 -08:00
Hamish Knight
246f09a1e1 [AST] Improve FailStmt source location computation
Avoid forming invalid source ranges when
`ReturnLoc` is invalid. Also introduce a utility
to make this kind of range computation easier,
and use it in a couple of other cases.
2024-01-23 19:30:32 +00:00
Hamish Knight
c97d80b1c3 [AST] NFC: Add convenience constructors for ReturnStmt
Add `ReturnStmt::createParsed` and `createImplict`.
2024-01-23 19:30:18 +00:00
Slava Pestov
42053105de AST: Add Evaluator::getInnermostSourceLoc() 2024-01-20 17:44:12 -05:00
Hamish Knight
c7ac0aa110 [Sema] Avoid forming nested do expressions in if/switch bindings
In asserts builds this hits an assert that the
feature isn't enabled, and in no-asserts builds
this incorrectly allows `do` expressions to be
used with the feature disabled. Note this only
affects their use when nested in an `if`/`switch`
that is used in a binding, we correctly handled
the other cases.

rdar://121193678
2024-01-18 16:18:49 +00:00
Doug Gregor
255009dddb Implement #isolation macro to produce the isolation of the current context
Introduce a new expression macro that produces an value of type
`(any AnyActor)?` that describes the current actor isolation. This
isolation will be `nil` in non-isolated code, and refer to either the
actor instance of shared global actor in other cases.

This is currently behind the experimental feature flag
OptionalIsolatedParameters.
2024-01-16 14:25:51 -08:00
Doug Gregor
b31133e67d Ensure that freestanding macros get consistent discriminators
Due to the duality between the expression and declaration forms of
freestanding macros, we could end up assigning two different discriminators
to what is effectively the same freestanding macro expansion. Across
different source files, this could lead to inconsistent discriminators in
different translation units. Unify the storage of the discriminator to
avoid this issue.

Fixes rdar://116259748
2024-01-11 08:18:28 -08:00
Holly Borla
76ae065c29 [Concurrency] Suppress Sendable argument diagnostics for values that come
from `nonisolated(unsafe)` declarations.
2024-01-03 12:32:11 -08:00
Doug Gregor
e1be9c312b Eliminate the DeclContext from ExplicitCaughtTypeRequest
Correctly determining the DeclContext needed for an
ExplicitCaughtTypeRequest is tricky for a number of callers, and
mistakes here can easily lead to redundant computation of the caught
type, redundant diagnostics, etc.

Instead, put a `DeclContext` into `DoCatchStmt`, because that's the
only catch node that needs a `DeclContext` but does not have one.
2023-12-13 11:42:56 -08:00
Doug Gregor
25faa002a4 Merge pull request #70397 from DougGregor/cleanup-caught-error-type
[Typed throws] Cleanups for the caught error type computation
2023-12-12 23:13:00 -08:00
Doug Gregor
010a41243e Fix minor regressions from refactoring of caught error types 2023-12-12 15:39:56 -08:00
Doug Gregor
91df336a4d [Typed throws] Unify ThrownTypeRequest and DoCatchExplicitThrownTypeRequest
These two requests are effectively doing the same thing to two
different cases within CatchNode. Unify the requests into a single
request, ExplicitCaughtTypeRequest, which operates on a CatchNode.

This also moves the logic for closures with explicitly-specified throws
clauses into the same request, taking it out of the constraint system.
2023-12-12 00:06:17 -08:00
Zhiyu Zhu/朱智语
5767e8f6d1 [Macros] Support module-qualified attached macro lookup (#69457)
Allow attached macro expansion syntax to have a module qualifier, `@Foo.Bar`.

rdar: //108621205
2023-12-08 15:57:51 -08:00
Pavel Yaskevich
c9a8355c26 [AST] Add a way to retrieve key path and its root/value types from KeyPathExpr 2023-11-28 13:02:17 -08:00
Doug Gregor
5ad39c84e0 [Typed throws] Record thrown error types and conversions in the AST
For any operation that can throw an error, such as calls, property
accesses, and non-exhaustive do..catch statements, record the thrown
error type along with the conversion from that thrown error to the
error type expected in context, as appropriate. This will prevent
later stages from having to re-compute the conversion sequences.
2023-10-24 12:40:22 -07:00
Doug Gregor
a14f280104 Merge pull request #69087 from DougGregor/typed-throws-conformances 2023-10-10 21:16:44 -07:00
Doug Gregor
7d7c726efe [Typed throws] Teach associated type inference to infer from thrown errors
When comparing a requirement that uses typed throws and uses an
associated type for the thrown error type against a potential witness,
infer the associated type from the thrown error of the
witness---whether explicitly specified, untyped throws (`any Error`),
or non-throwing (`Never`).
2023-10-09 21:21:21 -07:00
Hamish Knight
33f94bc874 Introduce do expressions 2023-10-06 11:17:48 +01:00
Holly Borla
3cb9bb89bc [Concurrency] Serialize default argument isolation. 2023-10-04 13:12:11 -07:00
Holly Borla
95a7107872 [Concurrency] Allow default arguments to require actor isolation.
Type checking a default argument expression will compute the required
actor isolation for evaluating that argument value synchronously. Actor
isolation checking is deferred to the caller; it is an error to use a
default argument from across isolation domains.

Currently gated behind -enable-experimental-feature IsolatedDefaultArguments.
2023-10-04 13:12:11 -07:00
Doug Gregor
b6b999abd4 [Typed throws] Basic SIL lowering and SIL generation for typed throws
Lower the thrown error type into the SIL function type. This requires
very little code because the thrown error type was already modeled as
a SILResultInfo, which carries type information. Note that this
lowering does not yet account for error types that need to passed
indirectly, but we will need to do so for (e.g.) using resilient error
types.

Teach a few places in SIL generation not to assume that thrown types
are always the existential error type, which primarily comes down to
ensuring that rethrow epilogues have the thrown type of the
corresponding function or closure.

Teach throw emission to implicitly box concrete thrown errors in the
error existential when needed to satisfy the throw destination. This
is a temporary solution that helps translate typed throws into untyped
throws, but it should be replaced by a better modeling within the AST
of the points at which thrown errors are converted.
2023-09-29 10:51:55 -07:00
Doug Gregor
ef642098f2 [Typed throws] Parsing and AST representation for typed errors
Parse typed throw specifiers as `throws(X)` in every place where there
are effects specified, and record the resulting thrown error type in
the AST except the type system. This includes:
* `FunctionTypeRepr`, for the parsed representation of types
* `AbstractFunctionDecl`, for various function-like declarations
* `ClosureExpr`, for closures
* `ArrowExpr`, for parsing of types within expression context

This also introduces some serialization logic for the thrown error
type of function-like declarations, along with an API to extract the
thrown interface type from one of those declarations, although right
now it will either be `Error` or empty.
2023-09-29 10:51:51 -07:00
Holly Borla
549b45250f [Concurrency] Remove ClosureActorIsolation. 2023-09-16 12:22:38 -07:00
Holly Borla
97f1e617fd [Concurrency] Replace ClosureActorIsolation with ActorIsolation throughout
the isolation query APIs.
2023-09-16 12:21:36 -07:00
Holly Borla
54f5fef20e [Concurrency] Store ActorIsolation in AbstractClosureExpr instead of
ClosureActorIsolation.
2023-09-16 12:20:53 -07:00
Holly Borla
4b23564711 [Concurrency] Rename AbstractClosureExpr::getActorIsolation to
getClosureActorIsolation.

This is preparation for changing AbstractClosureExpr to store
ActorIsolation instead of ClosureActorIsolation, and convert to
ClosureActorIsolation when needed to allow incrementally updating
callers. This change is NFC.
2023-09-16 12:20:53 -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
Holly Borla
a6d078b820 [Concurrency] Use the 'nonisolated' terminology instead of 'independent'.
This commit is NFC; it's mostly renames.
2023-09-08 13:28:55 -07:00
Hamish Knight
6ee44f09b4 Introduce then statements
These allow multi-statement `if`/`switch` expression
branches that can produce a value at the end by
saying `then <expr>`. This is gated behind
`-enable-experimental-feature ThenStatements`
pending evolution discussion.
2023-09-01 14:32:14 +01:00
Hamish Knight
c04281c1ef [Sema] Allow implicit nodes to wrap if/switch expressions
Previously we would only look through a handful of
AST node types when determining if an if/switch
expression is in a valid position. However this
doesn't handle cases where we synthesize code
around an if/switch expression, such as
`init(erasing:)` calls. As such, relax the logic
such that it can look through any implicit
expression.

rdar://113435870
2023-08-30 12:57:29 +01:00