Commit Graph

1185 Commits

Author SHA1 Message Date
Alejandro Alonso
15c32e117b Directly store GTPD in TypeValueExpr 2025-02-25 14:11:55 -08:00
Rintaro Ishizaki
0ced6e06b4 [ASTGen] Generate CaptureListExpr
Move the capture list entry construction logic to
CaptureListEntry::createParsed() so that ASTGen can use it.
2025-02-16 05:22:46 -08:00
Yuta Saito
3745dd1463 Merge pull request #79340 from kateinoigakukun/pr-3e00aa82837cda0d107594c8b38a7446d55c768b 2025-02-14 05:39:54 +09:00
Rintaro Ishizaki
563ddc47e2 [AST] Eliminate 'SYNTAX_KIND' from MagicIdentifierKinds.def
Nothing is using it.
2025-02-12 23:19:34 -08:00
Yuta Saito
c0478705e6 [AST] Explicitly cast uint64_t to size_t for 32-bit platforms
There are a few places in the AST where we use `uint64_t` as
`ArrayRef`'s size type. Even though of these `uint64_t` size fields are
actually defined as bitfields with a maximum value of 32, but
unfortunately it's not taken into account and clang complains about
the implicit cast.

The same attempt was made in 073905b573,
but several new places were added since then.
2025-02-13 00:23:45 +00:00
Allan Shortlidge
87308e37f1 AST: Avoid creating duplicate AvailabilityScopes under SequenceExprs.
Since availability scopes may be built at arbitrary times, the builder may
encounter ASTs where SequenceExprs still exist and have not been folded, or it
may encounter folded SequenceExprs that have not been removed from the AST.

To avoid a double visit, track whether a SequenceExpr is folded and then
customize how ASTVisitor handles folded sequences.

Resolves rdar://142824799 and https://github.com/swiftlang/swift/issues/78567.
2025-01-17 10:21:22 -08:00
Doug Gregor
8bb5bbedbc Implement an unsafe expression to cover uses of unsafe constructs
Introduce an `unsafe` expression akin to `try` and `await` that notes
that there are unsafe constructs in the expression to the right-hand
side. Extend the effects checker to also check for unsafety along with
throwing and async operations. This will result in diagnostics like
the following:

    10 |   func sum() -> Int {
    11 |     withUnsafeBufferPointer { buffer in
    12 |       let value = buffer[0]
       |                   |     `- note: reference to unsafe subscript 'subscript(_:)'
       |                   |- warning: expression uses unsafe constructs but is not marked with 'unsafe'
       |                   `- note: reference to parameter 'buffer' involves unsafe type 'UnsafeBufferPointer<Int>'
    13 |       tryWithP(X())
    14 |       return fastAdd(buffer.baseAddress, buffer.count)

These will come with a Fix-It that inserts `unsafe` into the proper
place. There's also a warning that appears when `unsafe` doesn't cover
any unsafe code, making it easier to clean up extraneous `unsafe`.

This approach requires that `@unsafe` be present on any declaration
that involves unsafe constructs within its signature. Outside of the
signature, the `unsafe` expression is used to identify unsafe code.
2025-01-10 10:39:14 -08:00
Slava Pestov
2d17294d73 Merge pull request #78301 from slavapestov/remove-one-way-constraints
Sema: Remove ConstraintKind::OneWayBindParam and ConstraintKind::OneWayEqual
2025-01-05 10:38:14 -05:00
Allan Shortlidge
d0f63a0753 AST: Split Availability.h into multiple headers.
Put AvailabilityRange into its own header with very few dependencies so that it
can be included freely in other headers that need to use it as a complete type.

NFC.
2025-01-03 18:36:04 -08:00
Slava Pestov
74f8960bd8 Sema: Remove OneWayExpr and Builtin.one_way 2024-12-21 00:42:13 -08:00
Pavel Yaskevich
1a5f00b205 [AST] Add a new implicit conversion to model unsafe casts
`UnsafeCastExpr` - A special kind of conversion that performs an unsafe
bitcast from one type to the other.

Note that this is an unsafe operation and type-checker is allowed to
use this only in a limited number of cases like: `any Sendable` -> `Any`
conversions in some positions, covariant conversions of function and
function result types.
2024-12-11 11:40:28 -08:00
Hamish Knight
c4efa0d5f0 [AST] Factor out Expr::getNameLoc
There are a bunch of AST nodes that can have
associated DeclNameLocs, make sure we cover them
all. I don't think this makes a difference for
`unwrapPropertyWrapperParameterTypes` since the
extra cases should be invalid, but for cursor info
it ensures we handle UnresolvedMemberExprs.
2024-12-05 15:55:19 +00:00
Hamish Knight
d7d77e9e4b [CS] Correctly set compound bit for UnresolvedMemberExprs
Now that IUOs are supported for compound function
references, we can properly set the compound bit
here.

This is a source breaking change since this used
to be legal:

```swift
struct S {
  static func foo(x: Int) -> Self { .init() }
}
let _: S = .foo(x:)(x: 0)
```

However I somewhat doubt anyone is intentionally
writing code like that.
2024-12-04 11:14:48 +00:00
Hamish Knight
73fb36f371 [AST] Split out "is compound" bit on FunctionRefInfo
FunctionRefKind was originally designed to represent
the handling needed for argument labels on function
references, in which the unapplied and compound cases
are effectively the same. However it has since been
adopted in a bunch of other places where the
spelling of the function reference is entirely
orthogonal to the application level.

Split out the application level from the
"is compound" bit. Should be NFC. I've left some
FIXMEs for non-NFC changes that I'll address in a
follow-up.
2024-12-02 14:11:33 +00:00
Hamish Knight
a4d51419ba [AST] NFC: Rename FunctionRefKind -> FunctionRefInfo 2024-12-02 14:11:32 +00:00
Michael Gottesman
c3d445831b [region-isolation] Fix an off by one error when mapping AST capture indices to SIL level parameter indices.
This problem comes up with the following example:

```swift
class A {
    var description = ""
}

class B {
    let a = A()

    func b() {
        let asdf = ""
        Task { @MainActor in
            a.description = asdf // Sending 'asdf' risks causing data races
        }
    }
}
```

The specific issue is that the closure we generate actually includes an
implicit(any) parameter at the SIL level which occurs after the callee operand
but before the captures. This caused the captured variable index from the AST
and the one we compute from the partial_apply to differ by 1. So we need to
subtract 1 in such a case. That is why we used to print 'asdf' instead of 'a'
above.

DISCUSSION: This shows an interesting difference between SIL applied arg indices
and AST indices. SIL applied arg indices would include the implicit(any)
parameter since it is a parameter in the SIL function type. In contrast, this
doesn't show up in the formal AST parameters or captures. To make it easier to
reason about this, I added a new API to ApplySite called
ApplySite::getASTAppliedArgIndex and added large comments to
getASTAppliedArgIndex and getAppliedArgIndex that explains the issue.

rdar://136593706
https://github.com/swiftlang/swift/issues/76648
2024-10-30 18:32:45 -07:00
Hamish Knight
9d4a78678a [Sema] Add logic to diagnose regex feature availability
Add the necessary compiler-side logic to allow
the regex parsing library to hand back a set of
features for a regex literal, which can then be
diagnosed by ExprAvailabilityWalker if the
availability context isn't sufficient. No tests
as this only adds the necessary infrastructure,
we don't yet hand back the features from the regex
parsing library.
2024-10-28 17:09:47 +00:00
Hamish Knight
7c3f965578 Merge pull request #76979 from hamishknight/regex-request
Requestify regex pattern parsing
2024-10-12 19:19:09 +01:00
Hamish Knight
6a435960b7 Requestify regex pattern parsing
Instead of doing the pattern parsing in both the
C++ parser and ASTGen, factor out the parsing into
a request that returns the pattern to emit, regex
type, and version. This can then be lazily run
during type-checking.
2024-10-11 19:25:58 +01:00
Anthony Latsis
41adfec8da [NFC] AST, Sema: Move TypeChecker::findReturnStatements into AnyFunctionRef
Also rename it to `getExplicitReturnStmts` for clarity and have it
take a `SmallVector` out parameter instead as a small optimization and
to discourage use of this new method as an alternative to
`AnyFunctionRef::bodyHasExplicitReturnStmt`.
2024-10-11 03:57:43 +03:00
Anthony Latsis
c7ea672463 [NFC] AST, Sema: Internalize BraceHasReturnRequest evaluation in AnyFunctionRef method 2024-10-11 03:44:43 +03:00
Doug Gregor
05e8140c6d Provide macro module name in MacroExpansionExpr creation
This properly passes the module name through from attached macros to
the freestanding macro that are used under-the-hood for type checking.
2024-09-16 16:44:17 -07:00
Hamish Knight
ee0e408a8c [Sema] Remove separate closure type-checking logic
`participatesInInference` is now always true for
a non-empty body, remove it along with the separate
type-checking logic such that empty bodies are
type-checked together with the context.
2024-09-08 16:17:11 +01:00
Alejandro Alonso
0df42e9841 Lower UDRE to TypeValue if it references a value generic 2024-09-04 15:13:29 -07:00
Alejandro Alonso
75c2cbf593 Implement value generics
Some requirement machine work

Rename requirement to Value

Rename more things to Value

Fix integer checking for requirement

some docs and parser changes

Minor fixes
2024-09-04 15:13:25 -07:00
Pavel Yaskevich
a4d9b3b5b2 [AST] Add a bit to closure expr to indiciate whether it requires dynamic isolation checking
This is an important information for closures because the compiler
might need to emit dynamic actor isolation checks in some circumstances
(i.e. when a closure is isolated and passed to a not fully concurrency
checked API).
2024-08-22 09:57:06 -07:00
Slava Pestov
9d163c4139 Convert GlobalActorAttributeRequest to use split caching 2024-07-06 23:35:59 -04:00
Michael Gottesman
5e27999b09 [sending] Rename Sema level APIs from isSendingParameter -> isPassedToSendingParameter.
This came up while I was talking with @xedin. This name makes
it really clear what we are trying to communicate to the author.
2024-06-21 02:24:03 -07:00
Michael Gottesman
3f39bdc1ed [sending] closure literals that are passed as sending parameters are now inferred to be nonisolated.
Consider the following piece of code and what the isolation is of the closure
literal passed to doSomething():

```swift
func doSomething(_ f: sending () -> ()) { ... }

@MyCustomActor
func foo() async {
  doSomething {
    // What is the isolation here?
  }
}
```

In this case, the isolation of the closure is @MyCustomActor. This is because
non-Sendable closures are by default isolated to their current context (in this
case @MyCustomActor since foo is @MyCustomActor isolated). This is a problem
since

1. Our closure is a synchronous function that does not have the ability to hop
to MyCustomActor to run said code. This could result in a concurrency hole
caused by running the closure in doSomething() without hopping to
MyCustomActor's executor.

2. In Region Based Isolation, a closure that is actor isolated cannot be sent,
so we would immediately hit a region isolation error.

To fix this issue, by default, if a closure literal is passed as a sending
parameter, we make its isolation nonisolated. This ensures that it is
disconnected and can be transferred safely.

In the case of an async closure literal, we follow the same semantics, but we
add an additional wrinkle: we keep support of inheritActorIsolation. If one
marks an async closure literal with inheritActorIsolation, we allow for it to be
passed as a sendable parameter since it is actually Sendable under the hood.
2024-06-21 02:24:03 -07:00
Cal Stephens
b525b9c7da Merge tag 'swift-DEVELOPMENT-SNAPSHOT-2024-05-01-a' of github.com:apple/swift into cal--fix-70089
Tag build swift-DEVELOPMENT-SNAPSHOT-2024-05-01-a
2024-05-04 12:19:16 -07:00
Slava Pestov
e342a38b87 Sema: Convert TypeChecker::computeCaptures() into two requests
We now compute captures of functions and default arguments
lazily, instead of as a side effect of primary file checking.

Captures of closures are computed as part of the enclosing
context, not lazily, because the type checking of a single
closure body is not lazy.

This fixes a specific issue with the `-experimental-skip-*` flags,
where functions declared after a top-level `guard` statement are
considered to have local captures, but nothing was forcing these
captures to be computed.

Fixes rdar://problem/125981663.
2024-04-20 22:16:25 -04:00
Slava Pestov
55ff73f205 AST: Stronger assertions around CaptureInfo 2024-04-19 17:59:58 -04:00
Cal Stephens
3315cab336 Merge branch 'main' into cal--fix-70089 2024-03-18 16:44:09 -07:00
Holly Borla
d9aa8697ab [Concurrency] Teach the constraint system about .isolation on dynamically
isolated function values.
2024-03-13 22:23:31 -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
Rintaro Ishizaki
58e70e8535 Merge pull request #72103 from rintaro/astgen-stringliteral
[ASTGen] Generate interpolated string literal
2024-03-13 10:08:15 +09:00
Cal Stephens
94dcf9bc70 Fix edge cases related to nested autoclosures, invalid weak self unwrapping 2024-03-11 07:42:44 -07:00
cui fliter
127077b3aa chore: fix some comments
Signed-off-by: cui fliter <imcusg@gmail.com>
2024-03-05 17:23:22 +08:00
Rintaro Ishizaki
cbae07e64e [Parse] Clean up Interpolated string literal parsing 2024-03-04 14:38:24 -08: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
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
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
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
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
fd97268393 Merge pull request #70983 from hamishknight/another-cleanup
[AST] Remove SerializedLocalDeclContext
2024-01-22 18:49:42 +00:00
Slava Pestov
42053105de AST: Add Evaluator::getInnermostSourceLoc() 2024-01-20 17:44:12 -05:00
Hamish Knight
3f4b45b012 [AST] Remove SerializedLocalDeclContext
It's not clear that its worth keeping this as a
base class for SerializedAbstractClosure and
SerializedTopLevelCodeDecl, most clients are
interested in the concrete kinds, not only whether
the context is serialized.
2024-01-18 12:03:52 +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