Rather than fixing-up in the parser, adjust the ASTScope logic such
that a `try` element in a SequenceExpr is considered as covering all
elements to the right of it. Cases where this isn't true are invalid,
and will be diagnosed during sequence folding. e.g:
```
0 * try foo() + bar()
_ = try foo() ~~~ bar() // Assuming `~~~` has lower precedence than `=`
```
This ensures we correctly handle `try` in assignment sequences, and
allows ASTGen to get the behavior for free.
rdar://132872235
Update the logic to correctly handle replacement ranges, and re-enable
the assertion. For now, carve out an exception for attributes on
extensions, I'll try and tackle those in a follow-up.
Sema now type-checks the alternate ABI-providing decls inside of @abi attributes.
Making this work—particularly, making redeclaration checking work—required making name lookup aware of ABI decls. Name lookup now evaluates both API-providing and ABI-providing declarations. In most cases, it will filter ABI-only decls out unless a specific flag is passed, in which case it will filter API-only decls out instead. Calls that simply retrieve a list of declarations, like `IterableDeclContext::getMembers()` and friends, typically only return API-providing decls; you have to access the ABI-providing ones through those.
As part of that work, I have also added some basic compiler interfaces for working with the API-providing and ABI-providing variants. `ABIRole` encodes whether a declaration provides only API, only ABI, or both, and `ABIRoleInfo` combines that with a pointer to the counterpart providing the other role (for a declaration that provides both, that’ll just be a pointer to `this`).
Decl checking of behavior specific to @abi will come in a future commit.
Note that this probably doesn’t properly exercise some of the new code (ASTScope::lookupEnclosingABIAttributeScope(), for instance); I expect that to happen only once we can rename types using an @abi attribute, since that will create distinguishable behavior differences when resolving TypeReprs in other @abi attributes.
The "buffer ID" in a SourceFile, which is used to find the source file's
contents in the SourceManager, has always been optional. However, the
effectively every SourceFile actually does have a buffer ID, and the
vast majority of accesses to this information dereference the optional
without checking.
Update the handful of call sites that provided `nullopt` as the buffer
ID to provide a proper buffer instead. These were mostly unit tests
and testing programs, with a few places that passed a never-empty
optional through to the SourceFile constructor.
Then, remove optionality from the representation and accessors. It is
now the case that every SourceFile has a buffer ID, simplying a bunch
of code.
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)
Both `try?` and `try!` are catch nodes, because they catch an error
thrown in their subexpression and handle it. Introduce an ASTScope for
all `try/try?/try1` expressions so we can find them, and model them as
catch nodes.
Fixes rdar://119216455.
The ASTScope class hierarchy rooted at ASTScopeImpl is relying entirely
on overridden virtual functions and, in some cases, string comparisons
on the class name, to provide customization for the various classes.
Introduce proper LLVM dynamic casting support to this class hierarchy,
eliminating the string comparisons and the manually-specified
implementations of `getClassName` (which is now used only for printing).
We've been meaning to do this for years, but today I got angry enough.
ASTScope assertions that a new child node inserted into its parent list
is after all other child nodes in the source, which included some bespoke
code for dealing with macro expansions. Replace this bespoke code with
uses of the newer SourceManager operations that check ordering of
source locations in a manner that respects macro expansions.
Function body macros allow one to introduce a function body for a
particular function, either providing a body for a function that
doesn't have one, or wholesale replacing the body of a function that
was written with a new one.
so that it can represent the scope for any custom attribute and its arguments.
This commit is NFC, but CustomAttributeScope is now applicable to attached macros.
Teach ASTScope to create child nodes for each of the arguments of a
macro expansion declaration, so that we can perform name lookup into
them. Otherwise, we cannot have nontrivial closures in arguments to a
macro expansion declaration.
Fixes rdar://107388151.
Macro expansion buffers, along with other generated source buffers,
need more precise "original source ranges" that can be had with the
token-based `SourceRange`. Switch over to `CharSourceRange` and provide
more thoughtfully-determined original source ranges.
Once an accessor macro has produced accessors, parse them and wire them
into the AST so the rest of the compiler will see them. First
end-to-end test case!
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`
The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.
rdar://102362022
In the Swift grammar, the top-level of a source file is a mix of three
different kinds of "items": declarations, statements, and expressions.
However, the existing parser forces all of these into declarations at
parse time, wrapping statements and expressions in TopLevelCodeDecls,
so the primary API for getting the top-level entities in source files
is based on getting declarations.
Start generalizing the representation by storing ASTNode instances at
the top level, rather than declaration pointers, updating many (but
not all!) uses of this API. The walk over declarations is a (cached)
filter to pick out all of the declarations. Existing parsed files are
unaffected (the parser still creates top-level code declarations), but
the new "macro expansion" source file kind skips creating top-level
code declarations so we get the pure parse tree. Additionally, some
generalized clients (like ASTScope lookup) will now look at the list
of items, so they'll be able to walk into statements and expressions
without the intervening TopLevelCodeDecl.
Over time, I'd like to phase out `getTopLevelDecls()` entirely,
relying on the new `getTopLevelItems()` for parsed content. We can
introduce TopLevelCodeDecls more lazily for semantic walks.
Semantically, the capture list binding behavior doesn't require the scope
to be an explicit closure, and forming new ClosureExprs during type-checking
is difficult because they have to have preassigned discriminators, unlike
AutoClosureExprs which get discriminators introduced by Sema itself. Allowing
CaptureListExpr to hold an AutoClosureExpr makes it easier to synthesize
CaptureListExprs during type checking, to represent expressions with closure
semantics that evaluate some parts of the expression eagerly in the surrounding
context.
When LLDB wraps a user-defined expression in the REPL, it takes something like this
```
<expr>
```
and turns it into (very very abstractly)
```
var result
do {
result = <expr>
}
print(result)
```
In the process, it creates an implicit pattern binding and an implicit do block. Of these, only the implicit do is considered by ASTScope lookup to be relevant. This presents a problem when <expr> is or contains a closure, as the parameters of that closure are defined within a scope that will never be expanded. Thus,
```
> [42].map { x in x } // <- cannot find 'x' in scope
```
This patch provides the Swift half of the fix wherein we privilege pattern bindings created by the debugger and look through them to the underlying user expression when performing ASTScope expansion.
rdar://78256873
The top-level scope for a conditional clause with a pattern is now
ConditionalClausePatternUseScope, which introduces the pattern's
bindings.
Since the patterns are not visible in their own initializer, a new
ConditionalClauseInitializerScope is used for the initializer.
While it is nested inside of the ConditionalClausePatternUseScope,
it's lookup parent skips one level, giving us the desired behavior.
The source range needs to contain any attributes on the subscript
declaration, since those might create child scopes (@_specialize,
property wrappers, etc).
Today, the reported source range of a GuardStmtScope is just that of
the statement itself, ending after the 'else' block. Similarly, a
PatternEntryDeclScope ends immediately after the initializer
expression.
Since these scopes introduce names until the end of the parent
BraceStmt (meaning they change the insertion point), we were
relying on the addition of child scopes to extend the source
range.
While we still need the hack for extending source ranges to deal
with string interpolation, at least in the other cases we can
get rid of it.
Note that this fixes a bug where a GuardStmtScope would end
before an inactive '#if' block if the inactive '#if' block was
the last element of a BraceStmt.
Let's use a ClosureParametersScope for all closures, even those
without an 'in' keyword. This eliminates the need for the
ClosureBodyScope and WholeClosureScope.
Also, let's move the lookup of capture list bindings from
CaptureParametersScope to CaptureListScope. This eliminates the
need for CaptureParametersScope to store a reference to the
capture list, which allows us to remove the AbstractClosureScope
base class entirely.
In a code snippet like the following,
static func ==(a: Foo, b: Foo) -> Bool {
switch (a, b) {
case (.x(let aa), .x(let bb)) where condition(aa, bb),
(.y(let aa), .y(let bb)) where condition(aa, bb):
return aa == bb
default:
return false
}
}
The CaseStmt defines two patterns, both of which bind
'aa' and 'bb'. The first 'aa'/'bb' are in scope inside the
first 'where' clause, and the second 'aa'/'bb' are in scope
inside the second 'where' clause.
Furthermore, the parser creates a "fake" VarDecl for
'aa' and 'bb' to represent the phi node merging the two
values along the two control flow paths; these are in scope
inside the body.
Model this situation by introducing a new CaseLabelItemScope
for the 'where' clauses, and a CaseStmtBodyScope for the
body.
* Re-create `ASTScope` for each completion
* Add generic params and where clause scope even without missing body
* Use `getOriginalBodySourceRange()` for `AbstractFunctionBodyScope`
* Source range translations for replaced ranges when finding scopes
* Bypass source range checks when the completion happens in the replaced
range
* Be lenient with ASTScope / DeclContext mismatch in code completion
Like switch cases, a catch clause may now include a comma-
separated list of patterns. The body will be executed if any
one of those patterns is matched.
This patch replaces `CatchStmt` with `CaseStmt` as the children
of `DoCatchStmt` in the AST. This necessitates a number of changes
throughout the compiler, including:
- Parser & libsyntax support for the new syntax and AST structure
- Typechecking of multi-pattern catches, including those which
contain bindings.
- SILGen support
- Code completion updates
- Profiler updates
- Name lookup changes
`@differentiable` attributes may contain `where` clauses referencing generic
parameters from some generic context, just like `@_specialize` attributes.
Without special ASTScope support for `@differentiable` attributes,
ASTScopeLookup.cpp logic tries to resolve the generic parameter `DeclName`s in
`where` clauses based on source location alone
(`ASTScopeImpl::findChildContaining`) and fails.
The fix is to add a special `DifferentiableAttributeScope`, mimicking
`SpecializeAttributeScope`. Every `@differentiable` attribute has its own scope,
derived from the declaration on which it is declared. Unlike `@_specialize`,
`@differentiable` may also be declared on `AbstractStorageDecl` declarations
(subscripts and variables).
Upstreams https://github.com/apple/swift/pull/27451.
Progress towards TF-828: upstream `@differentiable` attribute type-checking.
This commit introduces a request to type-check a
default argument expression and splits
`getDefaultValue` into 2 accessors:
- `getStructuralDefaultExpr` which retrieves the
potentially un-type-checked default argument
expression.
- `getTypeCheckedDefaultExpr` which retrieves a
fully type-checked default argument expression.
In addition, this commit adds `hasDefaultExpr`,
which allows checking for a default expr without
kicking off a request.