Commit Graph

1184 Commits

Author SHA1 Message Date
Doug Gregor
8bb5bbedbc Implement an unsafe expression to cover uses of unsafe constructs
Introduce an `unsafe` expression akin to `try` and `await` that notes
that there are unsafe constructs in the expression to the right-hand
side. Extend the effects checker to also check for unsafety along with
throwing and async operations. This will result in diagnostics like
the following:

    10 |   func sum() -> Int {
    11 |     withUnsafeBufferPointer { buffer in
    12 |       let value = buffer[0]
       |                   |     `- note: reference to unsafe subscript 'subscript(_:)'
       |                   |- warning: expression uses unsafe constructs but is not marked with 'unsafe'
       |                   `- note: reference to parameter 'buffer' involves unsafe type 'UnsafeBufferPointer<Int>'
    13 |       tryWithP(X())
    14 |       return fastAdd(buffer.baseAddress, buffer.count)

These will come with a Fix-It that inserts `unsafe` into the proper
place. There's also a warning that appears when `unsafe` doesn't cover
any unsafe code, making it easier to clean up extraneous `unsafe`.

This approach requires that `@unsafe` be present on any declaration
that involves unsafe constructs within its signature. Outside of the
signature, the `unsafe` expression is used to identify unsafe code.
2025-01-10 10:39:14 -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
Rintaro Ishizaki
8e8e4d0193 [Parse/Sema] Move OptionalEvaluationExpr wrapping to PreCheckTarget
This simplify the Parser diagnostics and some type checker logic.
2024-10-11 13:12:48 -07: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
05e8140c6d Provide macro module name in MacroExpansionExpr creation
This properly passes the module name through from attached macros to
the freestanding macro that are used under-the-hood for type checking.
2024-09-16 16:44:17 -07:00
Mateus Rodrigues
b1ba769754 Minor changes for better clarity 2024-07-25 15:30:37 -03:00
Mateus Rodrigues
e0d416cdab Ungate accepted parts of SE439 2024-07-22 09:55:16 -03:00
Xiaodi Wu
e1f537107f Merge branch 'main' into trailing-comma 2024-06-29 16:36:06 -04:00
Ben Barham
d72f5b12c4 Update StringRef::equals references to operator==
`equals` has been deprecated upstream, use `operator==` instead.
2024-06-27 19:14:06 -07:00
Hamish Knight
2fbc8b336f Merge pull request #74559 from hamishknight/pound-if-skip
[Parse] Handle `#if` in brace skipping logic
2024-06-21 15:04:19 +01:00
Tim Kientzle
598e5104ef Merge pull request #74184 from tbkka/tbkka-assertions2
Add `#include "swift/Basic/Assertions.h"` to a lot of source files
2024-06-20 12:13:28 -07:00
Hamish Knight
a85ca1315b [Parse] Unify recovery for invalid tokens following a #if body
Previously we would only diagnose and recover for
invalid tokens following a `#if` body for the decl
and postfix expression case. Sink this logic into
`parseIfConfigRaw`, ensuring that we do this for
all `#if` cases. This requires propagating the
context we're parsing in to customize the
diagnostic.
2024-06-19 21:39:40 +01:00
Holly Borla
8d6434410b [Parser] Hoist up 'try' exprs out from sequence exprs in the parser.
If the left-most sequence expr is a 'try', hoist it up to turn
'(try x) + y' into 'try (x + y)'. This is necessary to do in the
parser because 'try' nodes are represented in the ASTScope tree
to look up catch nodes. The scope tree must be syntactic because
it's constructed before sequence folding happens during preCheckExpr.
Otherwise, catch node lookup would find the incorrect catch node for
'try x + y' at the source location for 'y'.

'try' has restrictions for where it can appear within a sequence
expr. This is still diagnosed in TypeChecker::foldSequence.
2024-06-18 21:31:44 -07:00
Mateus Rodrigues
013997dae7 Implement trailing comma for comma-separated lists 2024-06-18 14:01:38 -03: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
Anthony Latsis
61bdbd2fe3 Move unsupported super use diagnosis form Parse to Sema 2024-04-19 16:57:04 +03:00
Doug Gregor
533a744623 Parse suppressed-conformance constraints in expressions and validate them
Ensure that we're properly parsing suppressed-conformance constraints
in expression contents and in metatypes. This allows types like `any
~Copyable` in expression context as well as types like `any
~Copyable.Type`.

While we're here, ensure that existentials that involve
suppressed-conformance constraints are spelled with `any`.

Fixes rdar://123728228.
2024-04-01 14:32:40 -07:00
Sophia Poirier
95abb73e1a Merge pull request #72175 from sophiapoirier/explicitly-nonisolated-closure
[Concurrency] explicit nonisolated specification for closures
2024-03-14 17:17:00 -07:00
Sophia Poirier
5ce7be7e75 [Concurrency] explicit nonisolated specification for closures 2024-03-14 12:24:13 -07:00
Rintaro Ishizaki
58e70e8535 Merge pull request #72103 from rintaro/astgen-stringliteral
[ASTGen] Generate interpolated string literal
2024-03-13 10:08:15 +09:00
Rintaro Ishizaki
e5592c7984 [ASTGen] Generate interpolated string literal 2024-03-06 10:32:00 -08:00
Rintaro Ishizaki
cbae07e64e [Parse] Clean up Interpolated string literal parsing 2024-03-04 14:38:24 -08: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
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
Hamish Knight
9b64990d24 [AST] Remove the "single expression body" bit
Remove this bit from function decls and closures.
Instead, for closures, infer it from the presence
of a single return or single expression AST node
in the body, which ought to be equivalent, and
automatically takes result builders into
consideration. We can also completely drop this
query from AbstractFunctionDecl, replacing it
instead with a bit on ReturnStmt.
2024-01-30 14:08:54 +00:00
Hamish Knight
f4a6b95d24 Move single-expr return transform from Parse to Sema
Rather than doing the transform in the parser, and
then potentially undoing it in Sema, move the
entire transform into Sema. This also lets us
unify the logic between function decls and
closures, and allows ASTGen to benefit from it.
2024-01-30 14:08:53 +00:00
Hamish Knight
3a8e31d7f6 Merge pull request #71094 from hamishknight/return-tweaks
A couple of ReturnStmt tweaks
2024-01-24 10:07:27 +00:00
Hamish Knight
c97d80b1c3 [AST] NFC: Add convenience constructors for ReturnStmt
Add `ReturnStmt::createParsed` and `createImplict`.
2024-01-23 19:30:18 +00:00
Alex Hoppen
c8424c1b7a [CodeComplete] Remove code for call pattern heuristics
These options weren’t used anymore, so we can remove them.
2024-01-22 19:57:12 -08:00
Alex Hoppen
695e69e09e [CodeComplete] Suggest single argument labels if code completion is invoked at start of function call with exiting parameters
This removes the distinction between argument completions and postfix expr paren completions, which was meaningless since solver-based completion.

It then determines whether to suggest the entire function call pattern (with all argument labels) or only a single argument based on whether there are any existing arguments in the call.

For this to work properly, we need to improve parser recovery a little bit so that it parsers arguments after the code completion token properly.

This should make call pattern heuristics obsolete.

rdar://84809503
2024-01-22 12:21:04 -08:00
Anthony Latsis
d7b52e96c4 Move unqualified init diagnosis from Parse to Sema 2023-12-25 21:17:20 +03:00
Rintaro Ishizaki
0c111ace0a [ASTGen] Implement SequenceExpr generation 2023-12-04 06:50:31 -08:00
Rintaro Ishizaki
fb08a92f48 [ASTGen] Infrastructure to implment ASTGen Incrementally
* 'ASTGenVisitor' has a reference to a legacy C++ Parser configured for
  ASTGen.
* If 'ASTGenVisitor' encounters a AST node that hasn't been migrated,
  call parse(Decl|Stmt|Expr|Type) to parse the position using the legacy
  parser.
* The legacy parser calls ASTGen's
  'swift_ASTGen_build(Decl|Stmt|Expr|Type)' for each ASTNode "parsing"
  (unless the call is not directly from the ASTGen.)

rdar://117151886
2023-11-12 21:43:08 -08:00
Hamish Knight
33f94bc874 Introduce do expressions 2023-10-06 11:17:48 +01:00
Doug Gregor
ef642098f2 [Typed throws] Parsing and AST representation for typed errors
Parse typed throw specifiers as `throws(X)` in every place where there
are effects specified, and record the resulting thrown error type in
the AST except the type system. This includes:
* `FunctionTypeRepr`, for the parsed representation of types
* `AbstractFunctionDecl`, for various function-like declarations
* `ClosureExpr`, for closures
* `ArrowExpr`, for parsing of types within expression context

This also introduces some serialization logic for the thrown error
type of function-like declarations, along with an API to extract the
thrown interface type from one of those declarations, although right
now it will either be `Error` or empty.
2023-09-29 10:51:51 -07:00
Doug Gregor
06bcd0641f Fix handling of anonymous closure arguments within macro expansions
We were incorrectly emitting a nonsensical error.

Fixes rdar://114340542.
2023-09-12 15:57:03 -07:00
Alex Hoppen
acc6c10344 Merge pull request #68075 from ahoppen/ahoppen/labeled-trailing-closure-solver-based
[CodeCompletion] Migrate labeled trailing closure completions to solver-based
2023-09-06 13:10:56 -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
Alex Hoppen
a1bfb510e1 [CodeCompletion] Migrate labeled trailing closure completions to solver-based
rdar://113472967
2023-08-24 15:41:36 -07:00
Rintaro Ishizaki
ababa1e461 [Parse] Accept 'self' after 'each'
Also move 'repeat', 'each', and 'any' expression parsing to
'parseExprSequenceElement'

rdar://107450487
2023-07-10 15:37:00 -07:00
Alex Hoppen
00eaed3af9 [CodeCompletion] Migrate postfix expr completion to solver-based 2023-07-07 19:51:01 +02:00
Doug Gregor
6fca08acf7 [Macros] Cope with local types and opaque result types in macros and expansions
Address a few related issues that affect local types and opaque result types within macros:
* Don't add local types or opaque types encountered while parsing the
arguments of a freestanding macro to the global list. When we do add
them, make sure we're adding them to the outermost source file so
they'll get seen later. This avoids trying to generate code for these
types, because they aren't supposed to be part of the program. Note
that a similar problem remains for arguments to attached macros, which
will need to be addressed with a more significant refactoring.
* When determining whether opaque types should be substituted within a
resilience domain, check the outermost source files rather than the exact
source file, otherwise we will end up with a mismatch in
argument-passing conventions.
* When delaying the type checking of functions that occur as part of a
macro expansion, make sure we record them in the outermost Swift source
file. Otherwise, we won't come back to them.

There is a common theme here of using AST state on the source file in
a manner that isn't ideal, and starts to break down with macros. In
these cases, we're relying on side effects from earlier phases
(parsing and type checking) to inform later phases, rather than
properly expressing the dependencies through requests.

Fixes rdar://110674997&110713264.
2023-07-03 15:09:54 -07:00
Erik Eckstein
6b1697eb06 use new llvm::Optional APIs to fix deprecation warnings 2023-06-28 14:28:38 +02: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
Hamish Knight
8caf9997c9 Merge pull request #66718 from hamishknight/getting-out-of-a-bind 2023-06-19 12:49:49 +01:00
Hamish Knight
6fffd96a18 [Parse] Avoid creating binding patterns in a couple more positions
If we have an identifier followed by either `[` or
a generic argument list, avoid turning it into a
binding pattern, as that would be invalid. This
is similar to the existing rule we have where a
following `(` prevents a binding pattern from
being formed.

This allows patterns such as `let E<Int>.foo(x)` and
`let (y[0], x)` to compile, where `x` is treated
as a binding, but no other identifier is.

rdar://108738034
2023-06-16 21:37:47 +01:00
Pavel Yaskevich
9d342f1dd0 Merge pull request #66681 from xedin/enable-inits-on-props-with-init-accessors
[Sema/SILGen] InitAccessors: Synthesize default arguments for init accessor properties
2023-06-16 11:24:35 -07:00
Pavel Yaskevich
8b1c9c9be8 [Parse] InitAccessors: Parse initializer exprs associated with computed properties that have init accessor
Initialization expressions are not allowed on computed properties
but if a property has `init` accessor it should be allowed because
it could be used by a memberwise initializer.
2023-06-15 11:38:06 -07:00
Alex Hoppen
fbbbd0d08a [Macros] Allow keywords after # in freestanding macro expansions
Allow keywords after `#` in freestanding macro expansions

There is no reason why we shouldn’t allow keywords here.

I also thought about allowing keywords after `@` but things become tricky here for two reasons:
- In the parser, we parse a type after the `@`, which could start with a keyword itself (e.g. `any`). If we want to keep the parser logic to parse a type after `@` (which I think we should), then it becomes unclear what `@any T` should parse as.
- We allow a space between `@` and the type name. This makes it very hard for recovery to tell whether `@ struct` refers to an attribute with name `struct` or if the user forgot to write the attribute name after `@`.

Since almost all keywords are lowercase and attached member macros are usually spelled with an uppercase name, there are a lot fewer chances for clashes here, so I don’t think it’s worth allowing keywords after `@`.

https://github.com/apple/swift/issues/66444
rdar://110472060
2023-06-14 22:02:37 -07:00