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.
Now that ASTGen should be able to generate most Swift code. Let's
remove "legacy parser" call-in, and remove the unhealthy cyclic
dependency between lib/Parse and ASTGen.
Previously we would only diagnose and recover for
invalid tokens following a `#if` body for the decl
and postfix expression case. Sink this logic into
`parseIfConfigRaw`, ensuring that we do this for
all `#if` cases. This requires propagating the
context we're parsing in to customize the
diagnostic.
If the left-most sequence expr is a 'try', hoist it up to turn
'(try x) + y' into 'try (x + y)'. This is necessary to do in the
parser because 'try' nodes are represented in the ASTScope tree
to look up catch nodes. The scope tree must be syntactic because
it's constructed before sequence folding happens during preCheckExpr.
Otherwise, catch node lookup would find the incorrect catch node for
'try x + y' at the source location for 'y'.
'try' has restrictions for where it can appear within a sequence
expr. This is still diagnosed in TypeChecker::foldSequence.
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)
Ensure that we're properly parsing suppressed-conformance constraints
in expression contents and in metatypes. This allows types like `any
~Copyable` in expression context as well as types like `any
~Copyable.Type`.
While we're here, ensure that existentials that involve
suppressed-conformance constraints are spelled with `any`.
Fixes rdar://123728228.
The goal is to have a lightweight way to pass an unapplied
diagnostic to general routines. Constructing a Diagnostic
is quite expensive as something we're potentially doing in
hot paths, as opposed to just when we're actually emitting
the diagnostic. This design allows the expense to be delayed
until we need it.
I've also optimized the Diagnostic constructor to avoid
copying arguments unnecessarily; this is a relatively small
expense, since arguments are POD, but there's really no good
reason not to do it.
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.
Rather than doing the transform in the parser, and
then potentially undoing it in Sema, move the
entire transform into Sema. This also lets us
unify the logic between function decls and
closures, and allows ASTGen to benefit from it.
This removes the distinction between argument completions and postfix expr paren completions, which was meaningless since solver-based completion.
It then determines whether to suggest the entire function call pattern (with all argument labels) or only a single argument based on whether there are any existing arguments in the call.
For this to work properly, we need to improve parser recovery a little bit so that it parsers arguments after the code completion token properly.
This should make call pattern heuristics obsolete.
rdar://84809503
* 'ASTGenVisitor' has a reference to a legacy C++ Parser configured for
ASTGen.
* If 'ASTGenVisitor' encounters a AST node that hasn't been migrated,
call parse(Decl|Stmt|Expr|Type) to parse the position using the legacy
parser.
* The legacy parser calls ASTGen's
'swift_ASTGen_build(Decl|Stmt|Expr|Type)' for each ASTNode "parsing"
(unless the call is not directly from the ASTGen.)
rdar://117151886
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.
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.
Address a few related issues that affect local types and opaque result types within macros:
* Don't add local types or opaque types encountered while parsing the
arguments of a freestanding macro to the global list. When we do add
them, make sure we're adding them to the outermost source file so
they'll get seen later. This avoids trying to generate code for these
types, because they aren't supposed to be part of the program. Note
that a similar problem remains for arguments to attached macros, which
will need to be addressed with a more significant refactoring.
* When determining whether opaque types should be substituted within a
resilience domain, check the outermost source files rather than the exact
source file, otherwise we will end up with a mismatch in
argument-passing conventions.
* When delaying the type checking of functions that occur as part of a
macro expansion, make sure we record them in the outermost Swift source
file. Otherwise, we won't come back to them.
There is a common theme here of using AST state on the source file in
a manner that isn't ideal, and starts to break down with macros. In
these cases, we're relying on side effects from earlier phases
(parsing and type checking) to inform later phases, rather than
properly expressing the dependencies through requests.
Fixes rdar://110674997&110713264.
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".
I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
If we have an identifier followed by either `[` or
a generic argument list, avoid turning it into a
binding pattern, as that would be invalid. This
is similar to the existing rule we have where a
following `(` prevents a binding pattern from
being formed.
This allows patterns such as `let E<Int>.foo(x)` and
`let (y[0], x)` to compile, where `x` is treated
as a binding, but no other identifier is.
rdar://108738034
Initialization expressions are not allowed on computed properties
but if a property has `init` accessor it should be allowed because
it could be used by a memberwise initializer.
Allow keywords after `#` in freestanding macro expansions
There is no reason why we shouldn’t allow keywords here.
I also thought about allowing keywords after `@` but things become tricky here for two reasons:
- In the parser, we parse a type after the `@`, which could start with a keyword itself (e.g. `any`). If we want to keep the parser logic to parse a type after `@` (which I think we should), then it becomes unclear what `@any T` should parse as.
- We allow a space between `@` and the type name. This makes it very hard for recovery to tell whether `@ struct` refers to an attribute with name `struct` or if the user forgot to write the attribute name after `@`.
Since almost all keywords are lowercase and attached member macros are usually spelled with an uppercase name, there are a lot fewer chances for clashes here, so I don’t think it’s worth allowing keywords after `@`.
https://github.com/apple/swift/issues/66444
rdar://110472060