Commit Graph

89 Commits

Author SHA1 Message Date
Rintaro Ishizaki
00985697c6 [Parse] Return 'const' pointer from AvailabilityMacroArgumentsRequest
Because it shouldn't be modified.
2025-02-05 11:36:08 -08:00
Rintaro Ishizaki
df2ada37df [ASTGen] Generate AvailableAttr
* Move `AvailabilitySpec` handling logic to AST, so they can be shared
  between libParse and ASTGen
* Requestify '-define-availability' arguments parsing and parse them
  with 'SwiftParser' according to the 'ParserASTGen' feature flag
* Implement 'AvailableAttr' generation in ASTGen
2025-02-04 23:40:01 -08:00
Rintaro Ishizaki
71ca3e129a [ASTGen] Use syntax tree based interface hash 2024-12-12 09:51:09 -08:00
Rintaro Ishizaki
6d7b3d69d1 [ASTGen] Generate several attributes
* NonisolatedAttr
* SpecializeAttr
* UnavailableFromAsyncAttr
* DocumentationAttr
* StorageRestrictionsAttr
2024-12-05 15:12:00 -08:00
Rintaro Ishizaki
e153164677 [ASTGen] Handle '#sourceLocation' directives
Use `ExportedSourceFile.sourceLocationConverter.lineTable.virtualFiles`
to populate the information in `swift::SourceManger` and
`swift::SourceFile` when "parsing" with ASTGen
2024-11-21 08:23:08 -08:00
Doug Gregor
c5de02f60e Merge pull request #77628 from DougGregor/clang-importer-parse-request
[Clang importer] Use ParseSourceFileRequest for parsing swift_attr attributes
2024-11-16 01:12:27 -08:00
Doug Gregor
24a12ebc34 Renable GeneratedSourceInfo::Attribute to GeneratedSourceInfo::AttributeFromClang 2024-11-15 09:02:49 -08:00
Doug Gregor
f8f14b4ab6 [Clang importer] Use ParseSourceFileRequest for parsing swift_attr attributes
The Clang importer was directly calling into the parser to parse the
attribute (or modifier) within swift_attr. Aside from being gross, this
isn't possible with ASTGen.

Instead, teach ParseSourceFileRequest to deal with modifiers in the
same way that the Clang importer was hardcoding, and have the Clang
importer pull the attributes/modifiers off of the "missing"
declaration introduced by the request.

One benefit of this approach is that we're only parsing each
swift_attr source buffer once, then cloning the attributes each time
it's used, so we should be doing less work overall.

Fixes rdar://139119159.
2024-11-15 09:02:47 -08:00
Rintaro Ishizaki
1fc00ae248 [ASTGen] Remove LegacyParser ping-pong mechanism
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.
2024-11-14 22:46:43 -08:00
Doug Gregor
11ed132614 [Clang importer + macros] Handle name lookup and type checking for expanded macros
Introduce a number of fixes to allow us to fully use declarations that
are produced by applying a peer macro to an imported declarations.
These changes include:
* Ensuring that we have the right set of imports in the source file
containing the macro expansion, because it depends only on the module
it comes from
* Ensuring that name lookup looks in that file even when the
DeclContext hierarchy doesn't contain the source file (because it's
based on the Clang module structure)

Expand testing to be sure that we're getting the right calls,
diagnostics, and generated IR symbols.
2024-11-13 21:21:56 -08:00
Doug Gregor
989c73d014 Ensure that buffers containing Clang swift_attr attributes are parsed as attributes
Previously, they were being parsed as top-level code, which would cause
errors because there are no definitions. Introduce a new
GeneratedSourceInfo kind to mark the purpose of these buffers so the
parser can handle them appropriately.
2024-11-13 21:19:37 -08:00
Doug Gregor
64e08d7e47 Merge pull request #77436 from DougGregor/parse-expression-macro-buffer-as-expression 2024-11-06 20:25:49 -08:00
Doug Gregor
78b89b201c Parse expression macro expansion buffers as expressions
This started out as a crash, where an expression macro could not be
defined in terms of one of the builtin macros (e.g., `#line`), because
we were expecting a macro expansion expression but didn't get one.
Easy fix.

However, this uncovered a second bug, which is that we couldn't handle
an expression macro expansino to `#line`. This is because we were
parsing the macro expansion buffer as "top level items", which treats
`#line` at the start of a line as a deprecated alias of
`#sourceLocation`. Switch over to parsing a single expression in these
contexts, and fix up an issue where `#isolation` didn't even have that
expression.

Fixes rdar://139372780.
2024-11-06 15:55:38 -08:00
Rintaro Ishizaki
e566a746c8 [ASTGen] Support macro expanded buffer
* Make ExportedSourceFile hold any Syntax as the root node
* Move `ExportedSourceFileRequest::evaluate()` to `ParseRequests.cpp`
* Pass  the decl context and `GeneatedSourceFileInfo::Kind` to
  `swift_ASTGen_parseSourceFile()` to customize the parsing
* Make `ExportedSourceFile` to hold an arbitrary Syntax node
* Move round-trip checking into `ExportedSourceFileRequest::evaluate()`
* Split `parseSourceFileViaASTGen` completely from C++ parsing logic
  (in `ParseSourceFileRequest::evaluate()`)
* Remove 'ParserDiagnostics' experimental feature: Now that we have
  ParserASTGen mode which includes the swift-syntax parser diagnostics.
2024-11-05 11:00:33 -08:00
Slava Pestov
9d85221ae5 Parse: Save and restore InFreestandingMacroArgument when delayed parsing
Closures appearing in freestanding macro arguments don't have
discriminators assigned, since we don't actually emit them.

Similarly we skip recording opaque return types that appear in macro
arguments, since they don't get emitted.

However this logic didn't take delayed parsing into account, which must
save and restore the InFreestandingMacroArgument bit correctly.

As a result, if the freestanding macro argument contained a closure
which contained a local function with a declaration that has an
opaque return type, we would crash in serialization from attempting
to mangle an opaque return type nested inside of a closure without a
discriminator.

Fixes rdar://135445004
2024-10-24 17:19:50 -04: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
Ben Barham
f292ec9784 Use the new template deduction guides rather than makeArrayRef
LLVM has removed `make*ArrayRef`, migrate all references to their
constructor equivalent.
2024-02-23 20:04:51 -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
Apollo Zhu
b09a22a9a0 Somewhat working
Test shadowed variable of same type

Fully type check caller side macro expansion

Skip macro default arg caller side expr at decl primary

Test macro expand more complex expressions

Set synthesized expression as implicit

Add test case for with argument, not compiling currently

Test with swiftinterface

Always use the string representation of the default argument

Now works across module boundary

Check works for multiple files

Make default argument expression work in single file

Use expected-error

Disallow expression macro as default argument

Using as a sub expression in default argument still allowed as expression macros behave the same as built-in magic literals
2024-02-06 15:02:11 -08:00
Doug Gregor
dd80cf79e6 [Macros] Parse body macro expansion as a single brace statement
Now that the macro expansion machinery is wrapping the contents of a
body macro in curly braces, parse it as a single brace statement. This
has the advantage of giving us real locations for `{` and `}` rather
than synthesizing them, and simplifies the implementation of macro
body expansion somewhat.
2023-12-05 13:55:50 -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
Doug Gregor
b53026d8d4 [Macros] Macro-metaprogram macro roles
Introduce X-macros for the various macro roles, and use them to
macro-metaprogram a lot of boilerplate involved with introducing new
macro roles.
2023-11-13 22:37:54 -08:00
Allan Shortlidge
1d8fc104c3 AST/SILGen: Requestify function body skipping.
Function bodies are skipped during typechecking when one of the
-experimental-skip-*-function-bodies flags is passed to the frontend. This was
implemented by setting the "body kind" of an `AbstractFunctionDecl` during decl
checking in `TypeCheckDeclPrimary`. This approach had a couple of issues:

- It is incompatible with skipping function bodies during lazy typechecking,
  since the skipping is only evaluated during a phase of eager typechecking.
- It prevents skipped function bodies from being parsed on-demand ("skipped" is
  a state that is distinct from "parsed", when they ought to be orthogonal).
  This needlessly prevented complete module interfaces from being emitted with
  -experimental-skip-all-function-bodies.

Storing the skipped status of a function separately from body kind and
requestifying the determination of whether to skip a function solves these
problems.

Resolves rdar://116020403
2023-09-28 19:18:35 -07:00
Holly Borla
725374e0d8 [Macros] Implement attached extension macros. 2023-06-27 21:22:12 -07:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
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.
2023-06-27 09:03:52 -07:00
Richard Wei
833338f9ce [Macros] Top-level freestanding macros (#63553)
Allow freestanding macros to be used at top-level.
- Parse top-level `#…` as `MacroExpansionDecl` when we are not in scripting mode.
- Add macro expansion decls to the source lookup cache with name-driven lazy expansion. Not supporting arbitrary name yet.
- Experimental support for script mode and brace-level declaration macro expansions: When type-checking a `MacroExpansionExpr`, assign it a substitute `MacroExpansionDecl` if the macro reference resolves to a declaration macro. This doesn’t work quite fully yet and will be enabled in a future fix.
2023-03-06 07:15:20 -08:00
Doug Gregor
fb2a35ac43 [Parser] Add obviously-missing break. 2023-02-27 15:57:39 -08:00
Holly Borla
a3caacd309 [Macros] Initial implementation of conformance macros. 2023-02-23 20:43:11 -08:00
Holly Borla
f4b2b60446 [Macros] Enable global peer macros.
Global peer macro expansions are not injected into the AST. Instead, they
are visited as "auxiliary declarations" when needed, such as in the decl
checker and during SILGen. This is the same mechanism used for local property
wrappers and local lazy variables.
2023-02-14 16:24:25 -08:00
Holly Borla
f04f512184 [Macros] Add a new macro role for attached peer macros. 2023-02-10 14:38:22 -08:00
Holly Borla
e6d7ea53ed [Parser] Use proper ParseDeclOptions when parsing the result of a member macro
expansion.
2023-01-27 22:37:22 -08:00
Holly Borla
f6f57a8099 [Macros] Rename "synthesized member macros" to "member macros". 2023-01-26 21:52:36 -08:00
Holly Borla
8b9be30783 [Macros] Add a new macro role for synthesized member macros. 2023-01-22 21:19:21 -08:00
Holly Borla
ffa47556f5 [Parser] Parse top-level attribute lists for member attribute macro
expansion.
2023-01-15 10:11:00 -08:00
Holly Borla
1b74d6cfcc [SourceManager] Distinguish between the various macro roles in
GeneratedSourceInfo::Kind.
2023-01-15 10:11:00 -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
0407610162 [Macros] Don't parse the macro expansion buffer twice.
Each macro expansion buffer was getting parsed twice: once by
ParseSourceFileRequest (which is used by unqualified name lookup) and
once to parse the expression when type-checking the expanded macro.
This meant that the same code had two ASTs. Hilarity ensures.

Stop directly invoking the parser on macro-expanded code. Instead, go
through ParseSourceFileRequest *as is always the right way*, and dig
out the expression we want.
2023-01-02 21:22:04 -08:00
Doug Gregor
1a3c6d721f [ASTGen] Handle new parser validation in ASTGen.
Replace the use of the "consistency check" vended by swift-syntax with
an ASTGen-implemented operation that emits diagnostics from the new parser
via the normal diagnostic engine. This eliminates our last dependency
on SwiftCompilerSupport, so stop linking it.
2022-12-15 21:24:44 -08:00
Doug Gregor
7dd6af759d [New parser] Move round-trip checking logic into ASTGen
This removes one bit of code dependency on SwiftCompilerSupport, which
we want to eliminate.
2022-12-15 07:13:38 -08:00
Alex Hoppen
fe2ae72ad2 [IDE] Rename CodeCompletion to IDEInspection in cases where the code path no longer exclusively applies to code completion
The code completio infrastructure is also being used for cursor info now, so it should no longer be called code completion.

rdar://103251187
2022-12-13 11:41:05 +01:00
Robert Widmann
530d937879 Remove SyntaxContext and Parser Affordances 2022-11-16 13:24:21 -08: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
Richard Wei
4ce1ebb120 [Macros] Support user-defined macros as compiler plugins (#61734)
Allow user-defined macros to be loaded from dynamic libraries and evaluated.

- Introduce a _CompilerPluginSupport module installed into the toolchain. Its `_CompilerPlugin` protocol acts as a stable interface between the compiler and user-defined macros.
- Introduce a `-load-plugin-library <path>` attribute which allows users to specify dynamic libraries to be loaded into the compiler.

A macro library must declare a public top-level computed property `public var allMacros: [Any.Type]` and be compiled to a dynamic library. The compiler will call the getter of this property to obtain and register all macros.

Known issues:
- We current do not have a way to strip out unnecessary symbols from the plugin dylib, i.e. produce a plugin library that does not contain SwiftSyntax symbols that will collide with the compiler itself.
- `MacroExpansionExpr`'s type is hard-coded as `(Int, String)`. It should instead be specified by the macro via protocol requirements such as `signature` and `genericSignature`. We need more protocol requirements in `_CompilerPlugin` to handle this.
- `dlopen` is not secure and is only for prototyping use here.

Friend PR: apple/swift-syntax#1022
2022-10-31 14:03:25 -07:00
Robert Widmann
fc2e10a5ff Bridge Parser Diagnostics into the C++ Diagnostic Engine
Add a hook so the Swift parser can emit diagnostics that go
through the normal diagnostics engine.
2022-10-18 21:39:06 -07:00
Doug Gregor
f53294f4fa Use a normal error when the new parser's consistency checking fails 2022-10-05 22:47:14 -07:00
Doug Gregor
dfcbb83494 [New Parser] Don't perform round-trip testing with structural overflows.
If we had a structural overflow, don't perform round-trip testing. The
new parser currently fails, and will need to deal with the problem in
a more appropriate manner than the existing one, which cuts off lexing entirely.
2022-09-24 12:13:47 -07:00
Doug Gregor
70a13ef147 Adopt new SwiftCompilerSupport header and enumerator names. 2022-09-18 17:00:45 -07:00
Robert Widmann
930ded7c0c Ignore SIL Files in Swift Syntax Parser Validation
Validating these files creates a load of false positive error cases
since the new Swift parser doesn't handle SIL. Disable validating
these files.
2022-09-14 00:56:23 -07:00
Doug Gregor
7902c6ecc1 Add an experimental feature to do validation of the Swift Swift parser. 2022-09-08 13:28:26 -07:00