Commit Graph

53 Commits

Author SHA1 Message Date
Hamish Knight
f524691cdf [IDE] Avoid inferring container type for implicit expressions
For e.g implicit `buildExpression` calls, we have a location that
matches the argument, but we don't want to consider the result
builder type as the container type.
2025-02-28 21:00:12 +00:00
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
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
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
Alex Hoppen
a38e7cce49 [SourceKit] Mark overridable declarations as dynamic
We only set `isDynamic` to `true` if we were inside an expression. Also set `isDynamic` when we are performing cursor info at an overridable declaration. This allows jump-to-definition to jump to declarations that override the one that we performed cursor info on.

rdar://128300752
2024-06-01 22:59:38 -07:00
Alex Hoppen
ef3e1c1d4f [SourceKit] Allow generation of cursor info for declarations from solutions that haven’t aren’t applied to the AST ye
This has two benefits:
1. We can now report ambiguous variable types
2. We are more robust in the generation of results for declarations inside closures. If the closure has an error, we won’t apply the solution to the AST and thus any cursor info that tried to get types out of the AST would fail.

rdar://123845208
2024-03-20 14:52:39 +01: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
Simon Barinka
9342e78e3e [SourceKit] Fix support for interpolated strings 2023-08-08 23:36:16 +02:00
Simon Barinka
e32a20a55c [SourceKit] Report init info instead of the type decl info
Addresses PR review comments.
2023-08-01 12:51:39 +02:00
Simon Barinka
fcd084f9dd [SourceKit] Report cursor info information for literals
Adds literals support for the CursorInfo request.
Previously CursorInfo just returned error for literals.
Implements issue #57725
2023-07-30 14:22:08 +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
Ben Barham
daa80bba4b [CursorInfo] Handle @ and # position
Allow clients to send the position of @ or #, rather than just the name.

Resolves rdar://106368511.
2023-03-07 18:00:15 -08:00
Doug Gregor
7a1c558899 Add more missing ASTWalker macro behavior entries 2023-02-28 19:13:02 -08:00
Doug Gregor
200f2340d9 [Macros] Be deliberate about walking macro arguments vs. expansions
Provide ASTWalker with a customization point to specify whether to
check macro arguments (which are type checked but never emitted), the
macro expansion (which is the result of applying the macro and is
actually emitted into the source), or both. Provide answers for the
~115 different ASTWalker visitors throughout the code base.

Fixes rdar://104042945, which concerns checking of effects in
macro arguments---which we shouldn't do.
2023-02-28 17:48:23 -08:00
Ben Barham
0c3f538822 [AST] Allow ignoring macro expansions
Various requests expect to be walking over the current source file.
While we could add checks to all these to skip decls outside of the
current buffer, it's a little nicer to handle this during the walk
instead.

Allow ignoring nodes that are from macro expansions and add that flag to
the various walks that expect it.

Also add a new `getOriginalAttrs` that filters out attributes in
generated source.
2023-02-16 18:04:56 -08:00
Alex Hoppen
ee26b4b299 [SourceKit] Pass ResolvedCursorInfo as shared pointer instead of by value
This allows us to model the `ResolvedCursorInfo` types as a proper type hierarchy instead of having to store all values in the base `ResolvedCursorInfo` type.

rdar://102853071
2023-02-14 22:40:45 +01:00
Doug Gregor
96380624db [SourceKit] Implement macro expansion for (some) attached macros.
Extend the macro-expansion refactoring to work with member and
member-attribute attached macros. These expansions can return several
different changes, e.g., adding new members, sprinkling member
attributes around, and so on.
2023-02-11 11:23:28 -08:00
Ben Barham
4cc7167b60 [Index] Handle shorthand if let/closure captures in local rename
Update rename to pull the outermost-declaration so that references are correctly found.

Rather than keeping suppressed locations in the current parent, keep
them for the whole index. Local rename starts the lookup from the
innermost context it can, which could be a closure. In that case there
is no parent decl on the stack and thus no where to store the locations
to suppress. We could have a specific store for this case, but there
shouldn't be that many of these and they're relatively cheap to store
anyway.

Resolves rdar://104568539.
2023-01-24 11:10:38 -08:00
Alex Hoppen
652686034c [IDE] Split ResolvedCursorInfo into subclasses
This way, each kind of `ResolvedCursorInfo` can define its own set of properties and it’s obvious which properties are used for which kind. Also switch to getters and setters because that makes it easier to search for usages of properties by looking at the call hierarchy of the getter / setter.
2022-12-01 12:11:39 +01: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
Ben Barham
5c9487286e [CursorInfo] References should not include shadowed declarations
Cursor info on a reference to a decl that shadows other decls should not
include those decls in the secondary symbols. They should only be
added on the decl itself, if that particular location is *also* the
reference to the shadowed decl (eg. in a shorthand if let or closure
capture).

Resolves rdar://96305891.
2022-07-01 13:17:54 -07:00
Ben Barham
8889daedce [SourceKit] Add whether a property is dynamic
Properties can also be specified in a protocol/overridden by subclasses,
so they should also be classed as "dynamic" in these cases.

Removed receiver USRs when *not* dynamic, since it's not used for
anything in that case and should be equivalent to the container anyway.

Resolves rdar://92882348.
2022-05-13 15:13:49 -07:00
Alex Hoppen
2b364930fc [CursorInfo] Report values shadowed using shorthand syntax as secondary results
When a variable is re-declared using shorthand syntax (`[foo]` closure capture or `if let foo {`), the user doesn’t perceive this as a new variable declaration. Thus, we should return the original declaration as a secondary result.

rdar://91311033
rdar://75455650
2022-05-11 08:05:26 +02:00
Saleem Abdulrasool
910fbee14e gardening: make c++98-compat-extra-semi an error
This cleans up 90 instances of this warning and reduces the build spew
when building on Linux.  This helps identify actual issues when
building which can get lost in the stream of warning messages.  It also
helps restore the ability to build the compiler with gcc.
2021-11-27 11:40:17 -08:00
Ben Barham
f6db91e3f9 [SourceKit] Ignore references without a location
A keypath using dynamic member lookup results in various `KeyPathExpr`
that have components with no location. Ignore these and any other
references that have a missing location.

Resolves rdar://85237365
2021-11-10 14:52:46 +10:00
Hamish Knight
8d92241ca9 [Refactoring] Support async for function extraction
Adapt the `ThrowingEntityAnalyzer` to pick up any
`await` keywords and add an `async` to the extracted
function if necessary along with an `await` for its
call.

rdar://72199949
2021-05-26 12:40:35 +01:00
Hamish Knight
3752965d8b [IDE] Don't walk into closures in ThrowingEntityAnalyzer
We don't want to consider any `try` exprs here.
2021-05-26 12:40:35 +01:00
Ben Barham
299df93a7f Merge pull request #36807 from bnbarham/use-original-locs
Replace uses of presumed locations where they do not make sense
2021-04-13 08:48:23 +10:00
Ben Barham
20f45ec284 Replace uses of presumed locations where they do not make sense
Various uses of `getPresumedLineAndColumnForLoc` were likely added when
that function was the very misleading name `getLineAndColumn`. Change
these to use `getLineAndColumnForBuffer` instead where appropriate, ie.
we want the underlying file rather than the location to display to the
user.

There were also some cases where the buffer identifier had been swapped
to use the display name instead, under the assumption that the presumed
location was needed. Updated those as well.

SingleRawComment: Lines are only used when merging comments, where the
original location is fine to use.

Index: Doesn't store the file set in #sourceLocation, so using the
presumed line would end up pointing to a location that makes no sense.

Editor functionality: Formatting and refactoring are on the current
file. Using the presumed location would result in incorrect
replacements.
2021-04-10 09:49:31 +10:00
Alex Hoppen
16baf61601 [RangeInfo] Acknowledge that SemaAnnotator walks the tree in source order *excluding* attributes
`SemaAnnotator` walks the tree in source order with respect to the source ranges *excluding* attributes, but `RangeResolver` considers attributes part of their declaration. Thus they disagree on what “walking in source order means”. `SemaAnnotator` will visit the attributes *before* the decl they are on, while `RangeResolver` as currently implemented expects them *as part of* the decl they are on.

Thus, for the purpose of `RangeResolver`, we need to assume that nodes are visited in arbitrary order and we might encounter enclosing nodes after their children.

Thus, when we find a new node, remove all nodes that it encloses from `ContainedASTNodes`.

Fixes rdar://64140713 [SR-12958]
2021-03-31 13:32:02 +02:00
Ben Barham
19f23130d0 [SourceKit/CursorInfo] Mark dynamic calls
Adds two new fields to the cursor info response:
  1. is_dynamic: whether a call is dynamic
  2. receivers: receivers of the call (USRs)

Users of the CursorInfo request can use "is_dynamic" to decide whether
to lookup overrides or not, and then the "receivers" as the starting
point of the lookup.

Resolves rdar://75385900
2021-03-20 13:57:01 +10:00
Ben Barham
b889b0777d [IDE] Refactor some call related functions out of Index.cpp
The cursor info request also needs to output whether a call is "dynamic"
or not, move the functions related to this out of Index.cpp and into
IDE/Utils.cpp.

Also cleanup the `TrailingExpr` handling in `CursorInfoResolver` - it
only needs the first expression.
2021-03-20 13:57:01 +10:00
Ben Barham
ab55c19b44 [IDE] Propagate the Stmt visit failure while walking TopLevelCodeDecls
`visitTopLevelCodeDecl` ignored the `Stmt` visit returning a nullptr.
This caused the `walkToDeclPost` to run for the `TopLevelCodeDecl` and
thus an imbalance in the `RangeResolver` pre and posts (since none of
the children would have their `walkTo*Post` called).

This was originally incorrectly fixed while assuming that the
`walkTo*Post` are called regardless of whether the children were visited
or not. Those changes have been reverted - fixing an imbalance in
`ExtDecls` in `SemaAnnotator`.

Added a test case for the `ExtDecls` imbalance which can occur while an
extension is being added.

Resolves rdar://74820040
2021-03-06 11:45:11 +10:00
Ben Barham
33bc38cdb8 [IDE] SourceEntityWalker should walk all explicit declarations
`SourceEntityWalker` had an unbalanced `walkToDeclPre` and
`walkToDeclPost`, ie. `walkToDeclPost` could be called even though
`walkToDeclPre` was not. Specifically, this would occur for both
`OperatorDecl` and `PrecedenceGroupDecl` declarations.

These could both be added to the `if` in `walkToDeclPost`, but this
seems fairly errorprone in general - especially as new decls are added.
Indeed, there's already declarations that are being skipped because they
aren't explicitly tested for in `walkToDeclPre`, ie.
`PatternBindingDecl`.

Instead of skipping if not explcitly handled, only skip running the
`SEWalker` walk methods if the declaration is implicit (and not a
constructor decl, see TODO). This should probably also always visit
children, with various decls changed to become implicit (eg.
TopLevelCodeDecl), but we can do that later - breaks too many tests for
now.

This change exposed a few parameter declarations that were missing their
implicit flag, as well as unbalanced walk methods in `RangeResolver`.
2021-02-11 10:34:07 +10:00
Anthony Latsis
9fd1aa5d59 [NFC] Pre- increment and decrement where possible 2020-06-01 15:39:29 +03:00
Owen Voorhees
45bc578ae5 [SourceManager] Rename line and column APIs for clarity 2020-05-21 12:54:07 -05:00
Anthony Latsis
74252028ca AST: Rename getFullName -> getName on ValueDecl & MissingMemberDecl 2020-04-23 05:16:55 +03:00
Robert Widmann
987cd55f50 [NFC] Drop llvm::Expected from Evaluation Points
A request is intended to be a pure function of its inputs. That function could, in theory, fail. In practice, there were basically no requests taking advantage of this ability - the few that were using it to explicitly detect cycles can just return reasonable defaults instead of forwarding the error on up the stack.

This is because cycles are checked by *the Evaluator*, and are unwound by the Evaluator.

Therefore, restore the idea that the evaluate functions are themselves pure, but keep the idea that *evaluation* of those requests may fail. This model enables the best of both worlds: we not only keep the evaluator flexible enough to handle future use cases like cancellation and diagnostic invalidation, but also request-based dependencies using the values computed at the evaluation points. These aforementioned use cases would use the llvm::Expected interface and the regular evaluation-point interface respectively.
2020-03-26 23:08:02 -07:00
Nathan Hawes
1218613e27 [IDE] Fix CursorInfo crash on arg label when the called 'function' is actually a module decl. 2019-11-07 13:49:27 -08:00
Anthony Latsis
6325915b4b NFC: Solidify and tidy up the BraceStmt interface 2019-10-30 16:43:59 +03:00
Robert Widmann
087e2f2746 [Evaluator Ergonomics] Add location information options to the requests 2019-09-06 11:16:17 -07:00
Robert Widmann
7a51cfcb87 [Evaluator Ergonomics] Add Request Signatures
Also add their caching kinds.  This information will be used to remove
the need to define classes at all.
2019-09-05 13:15:02 -07:00
Robert Widmann
a19a70e5c9 Switch all request infrastructure to SWIFT_REQUEST
Formally define the Zones in the TypeID header.  This is not its final
resting place.
2019-08-27 17:38:14 -07:00
Michael Gottesman
241142978a [gardening] Remove never read assignment.
Found with the static analyzer.
2019-08-08 12:32:11 -07:00
Xi Ge
1cb746b47c IDE+Evaluator: refactor resolveProtocolName to using the request evaluator, NFC 2019-07-22 15:35:14 -07:00
Xi Ge
77ba3a21b4 IDE+Evaluator: refactor the implementation of two type checker utilities to evaluator requests. NFC
IDE functionality needs some internal type checking logics, e.g. checking
whether an extension is applicable to a concrete type. We used to directly
expose an header from sema called IDETypeChecking.h so that IDE functionalities
could invoke these APIs. The goal of the commit and following commits is to
expose evaluator requests instead of directly exposing function entry points from
sema so that we could later move IDETypeChecking.h to libIDE and implement these functions
by internally evaluating these requests.
2019-07-22 12:49:36 -07:00
Xi Ge
4d57590fa9 IDE+Evaluator: refactor the implementation of two common IDE utilities to the evaluator model
These APIs are 'canDeclProvideDefaultImplementationFor' and 'collectAllOverriddenDecls'.
2019-07-19 11:14:21 -07:00