Commit Graph

144 Commits

Author SHA1 Message Date
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
Doug Gregor
0ec13f9a90 Build compiler and runtimes without Swift
Remove dependency on macros from compiler and stdlib build when
bootstrapping the compiler without Swift available.
2025-03-06 13:32:52 -08:00
Saleem Abdulrasool
42af06051d lib: simplify some pragma usage
When suppressing a warning for a single line, prefer to use `suppress`
to avoid the push/pop dance.
2025-01-21 09:15:07 -08:00
Rintaro Ishizaki
660a2ea39a Merge pull request #78335 from rintaro/revert-revert-77140-swift-lexical-lookup-validation
Reapply "[SwiftLexicalLookup] New unqualified lookup implementation validation"
2025-01-06 09:12:45 -08:00
Rintaro Ishizaki
a0d7068162 Revert "Merge pull request #78280 from swiftlang/revert-77140-swift-lexical-lookup-validation"
This reverts commit ae88aaca8f, reversing
changes made to b0123bca14.
2024-12-20 16:37:36 -08: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
Ben Barham
e06d0b9357 Revert "[SwiftLexicalLookup] New unqualified lookup implementation validation" 2024-12-18 15:04:16 -08:00
Jakub Florek
2cc00889bd Switch to integer division inaddPaddingUpTo. Rename magic constants in LoggingASTScopeDeclConsumer. Format BridgedConsumedLookupResult. 2024-10-23 12:27:15 +02:00
Jakub Florek
1d94844322 Add SwiftLexicalLookup validation. 2024-10-20 12:12:22 +02: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
ab90d09f7b [ASTScope] Eliminate getDeclAttributeIfAny().
We only used this in one place, and then immediately filtered down
to a `CustomAttr`. Just use `dyn_cast` in the obvious way and remove
this function.
2023-12-06 13:26:34 -08:00
Doug Gregor
742323c1b1 [ASTScope] Eliminate getClosureIfClosureScope
... it's just a `dyn_cast` now.
2023-12-06 13:19:10 -08:00
Doug Gregor
5c2171ca18 [ASTScope] Eliminate ASTScopeImpl::getCatchNodeBody() and centralize
The implementation of "lookup the catch node" is scattered throughout
various `ASTScopeImpl` subclasses. Remove that, and instead centralize
the code to find the innermost catch scope.
2023-12-06 13:14:52 -08:00
Doug Gregor
64c953f8f0 [ASTScope] Customize getClassName() for GenericTypeOrExtensionScope
The subclasses of `GenericTypeOrExtensionScope` are customized by a `Portion`
mix-in class that effectively makes each into several different scope
nodes: one for the "whole decl", one for the where clause, one for the
body. Re-introduce the customized `getClassName()` operation so we get
the nicer debugging dumps.
2023-12-06 12:12:34 -08:00
Doug Gregor
a2aed2af7b [ASTScope] Replace six virtual functions + overrides with switches
Replace a number of virtual query functions like `getDeclIfAny`, which had
to be overridden at various points in the hierarchy, with simpler
implementations based on the scope kind and `dyn_cast`.
Macro-metaprogram whether each scope node is associated with a
particular declaration/statement/expression/attribute so these
implementations can be efficiently macro-metaprogrammed.
2023-12-06 10:24:11 -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
3dd4df2351 [Typed throws] Location based lookup for the thrown error type
Introduce a new API to find the AST node that catches or rethrows an
error thrown from the given source location. Use it to determine the
thrown error type to use for type checking a `throw` statement, which
begins as `any Error` within a `do..catch` and is later refined.
2023-10-15 22:59:48 -07:00
Holly Borla
393b4ceb95 [NameLookup] Move macro-related name lookup operations into the namelookup
namespace.

This moves the `isInMacroArgument` predicate and `lookupMacros` into `namelookup`.
ASTScope still encapsulates the scope tree and contains the operation to lookup
the enclosing macro scope, which then invokes a callback to determine whether a
potential macro scope is indeed a macro, because answering this question requires
name lookup.
2023-06-11 23:10:43 -07:00
Holly Borla
cd79cf97d6 [ASTScope] Add APIs for determining whether a given source location is inside
a macro argument.
2023-06-11 23:09:47 -07: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
b29fcb4e58 [Macros] Parse macro declarations fully, and treat them as normal declarations 2022-11-28 18:32:43 -08:00
Doug Gregor
b129d7ec60 [Macros] Teach name lookup in macro expansions to look in expansion context
Teach ASTScope how to reason about macro expansions. When we create an
ASTScope for a source file that represents a macro expansion, its
parent scope node is the macro expansion itself. When performing
unqualified lookup (of any form), find the starting source file based
on the location, not on the source file provided---this ensures that
we start lookups within the macro expansion (for example).

The effect of this is to enable macro expansions to work in nested
contexts, where they refer to names in the scope in which the macro is
expanded.

This is decidedly unhiegenic, but it fits with our syntactic model.
2022-11-01 08:04:16 -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
Anthony Latsis
39649161d0 Gardening: See to some missing newline warnings 2021-02-12 17:00:47 +03:00
Slava Pestov
996100cfd1 ASTScope: Remove old SourceRange machinery 2020-10-07 12:33:58 -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
f8fb071f0f ASTScope: Remove ASTScopeImpl::getDeclContext() 2020-09-25 02:40:13 -04:00
Slava Pestov
bbd79a2db2 ASTScope: unqualifiedLookup() entry point does not need the name
If we're searching for a declaration with a given name, the name
should be entirely encapsulated inside the DeclConsumer.

Otherwise, there might not be a specific name at all, if we're
performing code completion for example (once LookupVisibleDecls
starts to use ASTScope, anyway).
2020-09-25 02:40:13 -04:00
Slava Pestov
32957259e8 ASTScope: Remove VarDeclScope 2020-09-23 13:09:01 -04:00
Slava Pestov
fd53040932 ASTScope: Refactor DeclAttribute scopes
DifferentiableAttr, SpecializeAttr and CustomAttr create scopes
because lookups can be performed from inside them. Previously
we would sort DifferentiableAttr and SpecializeAttr by source
order, but we consider that a declaration may also have more
than one _kind_ of attribute requiring special handling.

The case where this comes up is properties that have both a
DifferentiableAttr and CustomAttr. This fixes test failures in
AutoDiff tests with subsequent commits in this PR.
2020-09-23 13:09:00 -04:00
Slava Pestov
b7bd4fb8b3 ASTScope: Remove 'history' vector 2020-09-22 13:42:48 -04:00
Robert Widmann
d93c6d8b12 Remove Cascading Computations from ASTScope 2020-09-21 10:42:33 -06:00
Slava Pestov
9b851bf8cb ASTScope: Collapse PureFunctionBodyScope and MethodBodyScope
This centralizes some invariants around the 'self' parameter.
While all ConstructorDecls and DestructorDecls have a 'self',
even if they're invalid because they're not nested inside a type,
we don't want to consider this as the base 'self' for lookups.

Eg, consider this invalid code:

class C {
  func f() {
    init() {
      x
    }
  }
}

The base for the lookup should be f.self, not f.init.self.
2020-09-18 15:05:48 -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
09bb3c0d30 ASTScope: Don't need to pass in a DeclContext
This was used to validate against the old lookup code, but should no
longer be needed.
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
Doug Gregor
827ec9d28e [ASTScope] Use ASTScope to find fallthrough source/dest cases.
Rather than depending on the tracking of state in switch cases to
remember the case statements that are the source and destination for a
`fallthrough` statement, compute them using ASTScope to find the
nearest enclosing case (the source) and then find the next case in the
same `switch` statement (the destination).
2020-08-02 10:29:42 -07:00
Doug Gregor
0d90adf1b5 [ASTScope] Implement lookup for visible labeled statements.
Use the scope map to implement lookup for the labeled statements that
are visible from a given source location, which is a lexical property
that is currently handled with stateful tracking in the type checker.

For now, merely assert that the results of this approach are identical
to the state tracked in the statement type checker.
2020-07-30 23:55:10 -07:00
Doug Gregor
6c959af579 [ASTScope] Model "do" statements in the scope map 2020-07-30 22:18:27 -07:00
Robert Widmann
fb8fdd9644 Replace resolveCustomAttrType with a Request 2020-06-10 19:31:41 -07: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
Brent Royal-Gordon
da88512eda [NFC] Take DeclNameRef in UnqualifiedLookup and lookupQualified() 2019-12-11 00:55:17 -08:00
Robert Widmann
56b6e53dae Remove raw references to PatternBindingEntry APIs
Switch most callers to explicit indices.  The exceptions lie in things that needs to manipulate the parsed output directly including the Parser and components of the ASTScope.  These are included as friend class exceptions.
2019-10-17 13:31:14 -07:00
David Ungar
c25de6af75 Merge pull request #27221 from davidungar/A-9-17-astscope-off
[NFC, NameLookup, ASTScope] Bug fix for eager scope tree construction & better failure messages
2019-09-22 19:10:58 -07:00
David Ungar
e59196cb62 Remove too-restrictive assertion 2019-09-22 17:59:40 -07:00
David Ungar
10583f89c6 Ensure that reexpansion does not lose scopes. 2019-09-22 17:59:40 -07:00
David Ungar
c808eb5a27 Don't try to expand ASTSourceFileScope when eagerly building. 2019-09-22 17:59:40 -07:00