Commit Graph

92 Commits

Author SHA1 Message Date
Hamish Knight
2e1c37f1ab [ASTScope] Allow try in unfolded sequence to cover following elements
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
2025-04-02 12:46:21 +01:00
Hamish Knight
6d89ed3d73 [ASTScope] Use PrettyStackTraceString to print verification errors
Use the same approach as `ModuleFileSharedCore::fatal`, ensuring the
verification error ends up in the crash log.
2025-03-28 17:00:35 +00:00
Hamish Knight
1980f7235f [ASTScope] Re-enable checkSourceRangeBeforeAddingChild
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.
2025-03-27 11:31:24 +00:00
Becca Royal-Gordon
08e2a4ddae Type check ABI decls
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.
2024-12-19 15:49:34 -08:00
Doug Gregor
49aa0e966f Ensure that SourceFiles always have a backing buffer in the SourceManager
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.
2024-09-16 21:46:42 -07: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
Doug Gregor
49b05cec84 [Typed throws] Make try? and try! into catch nodes
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.
2023-12-06 15:00:58 -08:00
Doug Gregor
1e20686d12 [ASTScope] Introduce isa/cast/dyn_cast support to ASTScope hierarchy
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.
2023-12-06 09:43:21 -08:00
Doug Gregor
79e31a87b3 Re-implement ASTScope's child-insertion assertions
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.
2023-11-30 10:54:42 -08:00
Doug Gregor
36a2dcd927 Implement function body macros
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.
2023-11-27 17:04:55 -08:00
Holly Borla
abcdc6c60f [ASTScope] Rename and generalize AttachedPropertyWrapperScope to CustomAttributeScope
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.
2023-06-11 23:09:47 -07:00
Doug Gregor
82de47c494 [Macros] Fix name lookup in macro expansion declaration arguments.
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.
2023-03-30 00:10:20 -07:00
Doug Gregor
40b332189f [Macros] Fix name lookup of macro parameters in the definition.
This enables macros to be defined in terms of other macros.
2023-03-29 16:32:31 -07:00
Doug Gregor
7ea0e3f096 Switch GeneratedSourceInfo ranges over to CharSourceRange.
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.
2023-02-11 11:23:26 -08:00
Doug Gregor
8c3bd021c5 [Macros] Parse accessors produced my an accessor macro.
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!
2023-01-13 13:17:17 -08:00
Doug Gregor
b29fcb4e58 [Macros] Parse macro declarations fully, and treat them as normal declarations 2022-11-28 18:32:43 -08:00
Erik Eckstein
ab1b343dad use new llvm::Optional API
`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
2022-11-21 19:44:24 +01:00
Doug Gregor
0f9a70601a Parse and record top-level "items" rather than always forcing declarations.
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.
2022-11-01 08:04:15 -07:00
Joe Groff
a35dc481ee AST: Allow CaptureListExpr to hold any AbstractClosureExpr.
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.
2022-09-23 08:35:18 -07:00
Doug Gregor
55067ba028 Support named opaque result types for properties.
Add lookup scopes for the generic parameters of a named opaque result
type and clean up the code that finds the opaque substitutions.
2022-01-04 21:14:39 -08:00
Rintaro Ishizaki
7c92a8e555 [SourceKit] Add a request to generate object files in SourceKit
Add 'request.compile'
2021-12-21 14:35:38 -08:00
Robert Widmann
d52b33d409 Special-case Pattern Binding Decls Created by LLDB
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
2021-06-01 22:25:17 -07:00
Anthony Latsis
39649161d0 Gardening: See to some missing newline warnings 2021-02-12 17:00:47 +03:00
Slava Pestov
b720c04f4b ASTScope: Simplify a couple of getSourceRangeOfThisASTNode() methods 2020-10-08 16:08:10 -04:00
Slava Pestov
14620a34db ASTScope: Remove source range sorting 2020-10-07 23:28:29 -04:00
Slava Pestov
996100cfd1 ASTScope: Remove old SourceRange machinery 2020-10-07 12:33:58 -04:00
Slava Pestov
771fd6e9d1 ASTScope: Redo assertions to look at CharSourceRanges 2020-10-07 12:33:58 -04:00
Slava Pestov
4252659a04 ASTScope: Add a getCharSourceRangeOfScope() method to ASTScopeImpl 2020-10-07 12:33:30 -04:00
Slava Pestov
dac68ca047 ASTScope: Fix TopLevelCodeScope source range
Top-level code can contain guard statements which introduce
bindings until the end of the parent scope, so plumb that
through.
2020-10-07 12:33:29 -04:00
Slava Pestov
2e67c135fd ASTScope: Rework ConditionalClauseScopes
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.
2020-10-07 12:33:29 -04:00
Slava Pestov
66873b94c9 ASTScope: Fix SubscriptDeclScope source range
The source range needs to contain any attributes on the subscript
declaration, since those might create child scopes (@_specialize,
property wrappers, etc).
2020-10-07 12:33:29 -04:00
Slava Pestov
824ecdd0aa ASTScope: Fix AttachedPropertyWrapperScope source range
The source range needs to contain the argument expression.
2020-10-07 12:33:29 -04:00
Slava Pestov
4f1ab9d8e5 ASTScope: Directly calculate end location of GuardStmtScope and PatternEntryDeclScope
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.
2020-10-02 23:49:59 -04:00
Slava Pestov
445d747622 AST: Move GenericParamList and friends to GenericParamList.{h,cpp} 2020-09-29 19:51:03 -04:00
Slava Pestov
32957259e8 ASTScope: Remove VarDeclScope 2020-09-23 13:09:01 -04:00
Slava Pestov
87593fc0be ASTScope: Fold AbstractFunctionBodyScope into FunctionBodyScope 2020-09-23 13:09:00 -04:00
Slava Pestov
76802dd635 ASTScope: FunctionBodyScope should not be nested inside ParameterListScope 2020-09-22 13:42:47 -04:00
Slava Pestov
85ae227465 ASTScope: Remove hacks for PatternBindingDecls with invalid source ranges 2020-09-22 02:06:32 -04:00
Slava Pestov
3801d16d6f ASTScope: Simplify representation of closures
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.
2020-09-17 14:46:47 -04:00
Slava Pestov
df1b631722 ASTScope: Fix source range of ClosureParametersScope
The parameters are visible inside the source range that begins
with the 'in' keyword and ends with the closure's closing brace.
2020-09-16 20:07:58 -04:00
Slava Pestov
d260fbb9b1 ASTScope: More accurate modeling of 'case' statements
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.
2020-09-16 00:21:13 -04:00
Slava Pestov
713b57becb Frontend: Remove -lazy-astscopes flag 2020-09-05 01:16:21 -04:00
Rintaro Ishizaki
513fed7d8c [CodeCompletion] Enable ASTScope in code completion
* 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
2020-08-12 16:36:09 -07:00
Owen Voorhees
45bc578ae5 [SourceManager] Rename line and column APIs for clarity 2020-05-21 12:54:07 -05:00
Owen Voorhees
43e2d107e1 [SE-0276] Implement multi-pattern catch clauses
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
2020-04-04 09:28:26 -07:00
Dan Zheng
6c29939f59 [AutoDiff upstream] Add @differentiable ASTScope support. (#29171)
`@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.
2020-01-13 17:48:44 -08:00
Robert Widmann
96b3b9f0f4 [NFC] Hide SourceFile::Decls
In preparation for installing some stable paths infrastructure here,
hide access to the array of top-level decls.
2020-01-03 14:14:00 -08:00
Hamish Knight
01d5c00f9b [Sema] Requestify default arg 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.
2019-11-11 13:49:06 -08:00
David Ungar
f162a84e01 Factoring 2019-11-02 20:44:03 -07:00
David Ungar
37afa7cf98 Merge pull request #27435 from davidungar/A-9-29-recursion-assert
[ASTScopes] Use RequestEvaluator for ASTScope expansion to detect recursion
2019-10-10 19:42:22 -07:00