Commit Graph

719 Commits

Author SHA1 Message Date
Rintaro Ishizaki
d4db99ce9d [Parse] Remove unnecessary dependencies to Parser.h
C++ swift::Parser is going to be replaced with SwiftParser+ASTGen.
Direct dependencies to it should be removed. Before that, remove
unnecessary '#include "swift/Parse/Parser.h"' to clarify what actually
depends on 'swift::Parser'.

Split 'swift::parseDeclName()' et al. into the dedicated files.
2024-11-02 01:23:59 -07:00
Hamish Knight
81dc7d87ed [Parse] Remove TypeChecker and SIL options parameter from ParserUnit
Providing these is a bit of a layering violation,
the parser shouldn't care about these options (there
does seem to be one current use of `TypeCheckerOpts`
in the parser for designated operator types, but
that's a legacy feature that was never officially
supported).
2024-10-17 14:04:34 +01:00
Doug Gregor
d762dd53f8 Stop parsing into IfConfiDecl nodes in the C++ parser
When parsing #if...#endif regions, parse the active clause directly into
place in the AST without ever producing an IfConfigDecl instance.
2024-09-18 20:51:09 -07:00
Doug Gregor
8febd3fb32 Reimplement ModuleDecl::getSourceFileContainingLocation() using SourceManager
ModuleDecl kept track of all of the source files in the module so that it
could find the source file containing a given location, which relied on
a sorted array all of these source files. SourceManager has its own
similar data structure for a similar query mapping the locations to
buffer IDs.

Replace ModuleDecl's dats structure with a use of the SourceManager's version
with the mapping from buffer IDs to source files.
2024-09-18 07:45:50 -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
Kavon Farvardin
b3d548218b NCGenerics: omit flag in interfaces
Also cleans-up legacy code and tests that are no longer needed.
2024-04-18 21:57:44 -07:00
Ben Barham
9779c18da3 Rename startswith to starts_with
LLVM is presumably moving towards `std::string_view` -
`StringRef::startswith` is deprecated on tip. `SmallString::startswith`
was just renamed there (maybe with some small deprecation inbetween, but
if so, we've missed it).

The `SmallString::startswith` references were moved to
`.str().starts_with()`, rather than adding the `starts_with` on
`stable/20230725` as we only had a few of them. Open to switching that
over if anyone feels strongly though.
2024-03-13 22:25:47 -07:00
John McCall
976f1494f5 [NFC] Introduce DiagRef and use it throughout the parser
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.
2024-03-01 22:09:47 -05:00
Alex Hoppen
a836195e97 Revert "Merge pull request #71238 from ahoppen/ahoppen/source-location-parser-changes"
This reverts commit 12fe866470, reversing
changes made to 956d6d23f2.
2024-02-23 11:09:10 -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
Doug Gregor
81ffafdc6a Merge pull request #70602 from ApolloZhu/macro/expression-as-default-argument
[Macros] Expression macro as caller-side default argument
2024-02-14 16:10:11 -08:00
Steven Wu
3986937e03 [Caching][NFC] Restructure CASOption in swift. NFC
Clean up how CASOptions are kept and passed inside swift to make the
code more readable. Also avoid a copy of CAS configuration in
ClangImporter.
2024-02-11 14:08:09 -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
Alex Hoppen
b3f9e08255 Merge pull request #71237 from ahoppen/ahoppen/attribute-parser-changes
Disallow spaces between `@`, attribute name and `(` in Swift 6
2024-01-31 20:53:34 -08:00
Alex Hoppen
c6e425a559 [Parse] Disallow space between attribute name and '(' in Swift 6 mode
This allows us to resolve disambiguities of whether a parenthesis belong to an argument to the attribute or if it is eg. the start of a tuple.
2024-01-31 18:24:42 -08:00
Alex Hoppen
4a386d40a6 [Parse] Disallow multiline string literals for filename in #sourceLocation and similar locations
This should allow us to eventually simplify parsing of simple string literals in the new parse by not having to handle indentation of multiline string literals.
2024-01-31 16:03:20 -08:00
Rintaro Ishizaki
5862d347e6 [Parse] Remove 'ParseDeclOptions' parameter from 'parseDecl' function
'ParseDeclOptions' can be trivially calculated solely from the current
decl context. To reduce the number of the contextual parameters,
calculate it inside the function.
2023-11-02 16:50:33 -07:00
Kavon Farvardin
c01360d02e [Sema] reimplement ~C as an general inverse constraint 2023-09-20 09:34:06 -07:00
Hamish Knight
6ee44f09b4 Introduce then statements
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.
2023-09-01 14:32:14 +01:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
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.
2023-06-27 09:03:52 -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
Holly Borla
51e1a39a0c [Parser] Reset ASTScopes before performing the IDEInspection second pass.
IDE inspection can delay parsing of particular declarations, so expanding
ASTScopes during the first pass will miss those declarations. Clear any
expanded scopes to force re-expansion during the second pass.
2023-06-11 23:10:43 -07:00
Hamish Knight
4ce49bd4d2 [Parse] Sink registerParseRequestFunctions call into ParserUnit 2023-05-22 14:55:18 +01:00
Hamish Knight
48b58eb338 [AST] Introduce BraceStmt::getSingleActiveElement
Use this to replace
`Parser::shouldReturnSingleExpressionElement`.
This should be NFC.
2023-04-12 14:54:21 +01:00
Alex Hoppen
8a2cd86deb Split IDEInspectionCallbacks into CodeCompletionCallbacks and DoneParsingCallback
Cursor info only cares about the `doneParsing` callback and not about all the `complete` functions that are now defined in `CodeCompletionCallbacks`. To make the design clearer, split `IDEInspectionCallbacks`.

rdar://105120332
2023-03-17 10:31:13 -07:00
Michael Gottesman
25d5fff50b [reference-bindings] Put inout parsing behind a flag harder.
In my earlier commit that attempted to do this I wasn't aggressive enough. In
this commit, I was more aggressive in putting it behind a flag and as a result
we reject all of the patterns in the tests I added into tree.
2023-03-05 13:22:18 -08:00
Michael Gottesman
c97121d3ee [reference-binding] Add support for inout binding parsing/serialization. 2023-03-01 20:48:54 -08:00
zoecarver
048a38194c [cxx-interop] Add back identifier validation; traffic 'isCxxClassTemplateSpec' through 'formDeclName'. 2023-02-21 10:48:45 -08:00
zoecarver
ab15240ebd Remove 'failure' codepath from decl name parsing. 2023-02-20 18:03:35 -08:00
zoecarver
f9e111c21a [cxx-interop] Re-implement template mangling.
Instead of mangling class template specializations with the prefix "__CxxTemplateInst," simply set the decl name as the class templates plus the types that it is specialized on (so `vector<Int>` rather than `__CxxTemplateInstNSt3__16vectorIi...`).

This is mainly to improve diagnostics. As a side effect of this change, if anyone copies the name of a class template specializaiton from an error/warning and uses it in source code, the compiler will error (that class templates aren't available in swift) rather than silently passing only to cause serailization failures down the road.
2023-02-20 17:58:10 -08:00
Doug Gregor
ac4aa41d0f [Macros] Use macro expansion mangling for unique names in macros
Use the name mangling scheme we've devised for macro expansions to
back the implementation of the macro expansion context's
`getUniqueName` operation. This way, we guarantee that the names
provided by macro expansions don't conflict, as well as making them
demangleable so we can determine what introduced the names.
2023-01-31 09:40:48 -08:00
Doug Gregor
b399b92566 [Parser] Remove the notion of a "local context".
The "local context" was only used to prevent parsing of closures in a
non-local context, and also string interpolations because they are
similar-ish to closures. However, this isn't something a parser should
decide, so remove this special-case semantic check from the parser and
eliminate the notion of "local context" entirely.
2022-12-21 15:01:08 -08:00
Doug Gregor
9e61b01ec1 Rework computation of local discriminators for named entities.
Local discriminators for named entities are currently being set by the
parser, so entities not created by the parser (e.g., that come from
synthesized code) don't get local discriminators. Moreover, there is
no checking to ensure that every named local entity gets a local
discriminator, so some entities would incorrectly get a local
discriminator of 0.

Assign local discriminators as part of setting closure discriminators,
in response to a request asking for the local discriminator, so the
parser does not need to track this information, and all local
declarations---including synthesized ones---get local discriminators.
And add checking to make sure that every entity that needs a local
discriminator gets assigned one.

There are a few interesting cases in here:
* There was a potential mangling collision with local property
wrappers because their generated variables weren't getting local
discriminators
* $interpolation variables introduced for string interpolation weren't
getting local discriminators, they were just wrong.
* "Local rename" when dealing with captures like `[x]` was dependent on
the new delcaration of `x` *not* getting a local discriminator. There
are funny cases involving nesting where it would do the wrong thing.
2022-12-21 15:01:07 -08:00
Doug Gregor
402ba1492f Set closure descriminators via a request.
Rather than set closure discriminators in both the parser (for explicit
closures) and then later as part of contextualizing closures (for
autoclosures), do so via a request that sets all of the discriminators
for a given context.
2022-12-19 15:23:45 -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
Alex Hoppen
1395928d45 [IDE] Decrement the global closure discriminator by one before performing the second code completion pass
Otherwise, the closure discriminator will be incremented by one when the closure witht he code completion token is parsed a second time during the second pass, and thus it would receive a different discriminator during the second pass.
2022-12-08 14:39:15 +01:00
Alex Hoppen
44262a3da8 [IDE] Pass SourceFile in doneParsing callback
This will be necessary to make cursor info completion like to inspect the just parsed source file because the callback from parsing the code completion token won’t be called.
2022-12-01 12:11:39 +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
Doug Gregor
0cb2746c49 Keep track of source files created for macro expansions and such.
Introduce a new source file kind to describe source files for macro
expansions, and include the macro expression that they expand. This
establishes a "parent" relationship

Also track every kind of auxiliary source file---whether for macro
expansions or other reasons---that is introduced into a module, adding
an operation that allows us to find the source file that contains a
given source location.
2022-11-01 08:03:26 -07:00
Hamish Knight
48ea933804 Parse an ellipsis T... for type parameter packs
In a generic parameter list, parse an ellipsis
to produce a type parameter pack. This replaces
the previous `@_typeSequence` attribute.
2022-10-14 15:40:12 +01:00
Becca Royal-Gordon
22a54b5176 [NFC] Add parsing helpers for @attr(<identifier>)
Refactors `parseSingleAttrOption()` to create a helper that can parse a single arbitrary `Identifier`. This simplifies the handling of `SwiftNativeObjCRuntimeBaseAttr`, `ObjCRuntimeNameAttr`, and `ProjectedValuePropertyAttr`.
2022-09-30 17:54:49 -07:00
Robert Widmann
e456780ee3 Fixup Yield Syntax Representation 2022-09-30 12:56:00 -07:00
Doug Gregor
b3c5fde118 Parse declaration attributes within #if...#endif blocks.
Introduce support for parsing declaration attributes that occur within
example:

    #if hasAttribute(frozen)
    @frozen
    #endif
    public struct X { ... }

will apply to "frozen" attribute to the struct `X`, but only when the
compiler supports the "frozen" attribute.

Correctly determining whether a particular `#if` block contains
attributes to be associated with the following declaration vs.
starting a new declaration requires arbitrary lookahead. The parser
will ensure that at least one of the branches of the `#if` contains an
attribute, and that none of the branches contains something that does
not fit the attribute grammar, before committing to parsing the `#if`
clause as part of the declaration attributes. This lookahead does
occur at the top level (e.g., in the parsing of top-level declarations
and code), but should only need to scan past the first `#if` line to
the following token in the common case.

Unlike other `#if` when used to wrap statements or declarations, we
make no attempt to record the `#if` not taken anywhere in the AST.
This reflects a change in attitude in the design of the AST, because
we have found that trying to represent this information there (e.g.,
via `IfConfigDecl`) complicates clients while providing little value.
This information is best kept in the syntax tree, only.
2022-07-25 21:31:17 -04:00
Josh Soref
4721852fcb Spelling parse (#42469)
* spelling: appear

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: availability

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: available

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: coerce

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: collection

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: condition

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: conditional

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: delimiter

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: derived

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: diagnostics

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: disambiguation

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: dropped

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: escaped

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: existence

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: expression

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: expressions

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: extended

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: furthermore

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: identifier

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: indentation

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: inspect

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: miscellaneous

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: multiline

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: offset

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: passthrough

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: precede

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: prefix

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: receiver

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: reference

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: registered

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: representing

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: returned

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: sequence

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: should

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: successfully

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: that

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: the

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: trivia

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: unsupported

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: whitespace

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

Co-authored-by: Josh Soref <jsoref@users.noreply.github.com>
2022-04-21 09:31:40 -07:00
Robert Widmann
245321199e [NFC] Remove Legacy Parser-Based Redeclaration Diagnostics 2022-04-14 18:38:51 -07:00
Hamish Knight
f1a799037e [Parse] Introduce /.../ regex literals
Start parsing regex literals with `/.../`
delimiters.

rdar://83253726
2022-04-12 16:03:49 +01:00
Alex Hoppen
bfc68f48e4 [Parser] When recovering from expression parsing don't stop at '{'
When recovering from a parser error in an expression, we resumed parsing at a '{'. I assume this was because we wanted to continue inside e.g. an if-body if parsing the condition failed, but it's actually causing more issue because when parsing e.g.

```swift
expr + has - error +

functionTakesClosure {
}
```

we continue parsing at the `{` of the trailing closure, which is a completely garbage location to continue parsing.

The motivating example for this change was (in a result builder)
```swift
Text("\(island.#^COMPLETE^#)")
takeTrailingClosure {}
```

Here `Text(…)` has an error (because it contains a code completion token) and thus we skip `takeTrailingClosure`, effectively parsing
```swift
Text(….) {}
```

which the type checker wasn’t very happy with and thus refused to provide code completion. With this change, we completely drop `takeTrailingClosure {}`. The type checker is a lot happier with that.
2022-04-07 09:19:22 +02:00
Allan Shortlidge
2a646dc438 Parse: Require a "before: " label in the first item of the list in the @_backDeploy attribute in order to match the pitched syntax for the attribute. Refactor existing comma separated list parsing code to take advantage of part of it in the attribute parsing. 2022-03-18 11:31:34 -07:00
Alex Hoppen
b888dc0e40 [Parser] Don't modify the current token kind when cutting off parsing
Previously, when we reached the maximum nesting level, we changed the current token’s kind to an EOF token. A lot of places in the parser are not set up to expect this token change. The intended workaround was to check whether pushing a structure marker failed (which would change the token kind) and bail out parsing if this happened. This was fragile and caused assertion failures in assert builds.

Instead of changing the current token’s kind, and failing to push the structure marker, let the lexer know that it should cut off lexing, essentially making the input buffer stop at the current position. The parser will continue to consume its current token (`Parser.Tok`) and the next token that’s already lexed in the lexer (`Lexer.NextToken`) before reaching the emulated EOF token. Thus two more tokens are parsed than before, but that shouldn’t make much of a difference.
2021-11-09 12:28:10 +01:00