Commit Graph

169 Commits

Author SHA1 Message Date
Tristan Labelle
fb8c4182d3 Avoid memory mapping source files opened by SourceKit. 2023-11-01 11:33:33 -04:00
Alex Hoppen
22d34d9b14 Merge pull request #58978 from ahoppen/pr/no-deadlock-cancellation-bigger-change
[SoruceKit] Audit SwiftASTManager to prevent deadlocks
2023-06-26 13:11:08 +02:00
Ben Barham
1d7c534228 Merge pull request #66839 from bnbarham/reuse-cursor-ast
[CursorInfo] Re-use already built ASTs ahead of currently building ones
2023-06-23 09:05:47 -07:00
Alex Hoppen
453f6cdeee [SoruceKit] Audit SwiftASTManager to prevent deadlocks
- Ensure that no callbacks are called when either of these mutexes are held:
  - `SwiftASTConsumer::CancellationRequestCallbackAndIsCancelledMtx`
  - `ASTBuildOperation::DependencyStampsMtx`
    - Exception: We allow calls to `getBuferStamp` because that doesn’t claim any locks)
    - No change was necessary here
  - `ASTBuildOperation::ConsumersAndResultMtx`
  - `ASTBuildOperation::CacheMtx`
    - No change was necessary here
  - `ASTBuildOperation::ScheduledConsumersMtx`
    - Make sure we always inform the consumers asynchronously, even if the operation was already cancelled when the consumer got enqueued by introducing `ConsumerNotificationQueue`
- Ensure that all callbacks to `SwiftASTConsumer` (i.e. `requestCancellation` and `handlePrimaryAST`, `failed`, `cancelled`) are performed asyncronously from a queue to avoid deadlocks

rdar://110357502
2023-06-23 16:55:49 +02:00
Ben Barham
037ddc92ee [CursorInfo] Re-use already built ASTs ahead of currently building ones
Resolves rdar://110344363.
2023-06-22 14:12:48 -07:00
Alex Hoppen
35661f2ab6 [SourceKit] Inform consumers about cancellation from a background queue
This fixes a deadlock that could occur when a cursor info request is cancelled while another one is inside the cancellation callback. The schematic deadlock backtrace is

```
sourcekitd::cancelRequest
SourceKit::RequestTracker::cancel -> holds RequestTracker.RequestsMtx
anonymous func in SourceKit::SwiftASTManager::processASTAsync
SourceKit::SwiftASTConsumer::requestCancellation
anonymous func in ASTBuildOperation::addConsumer -> tries to get ASTBuildOperation.ConsumersAndResultMtx

resolveCursor
SourceKit::SwiftASTManager::processASTAsync
SourceKit::SwiftASTConsumer::requestCancellation
anonymous func in ASTBuildOperation::addConsumer
[probably inlined] ASTBuildOperation::requestConsumerCancellation -> holds ASTBuildOperation.ConsumersAndResultMtx
resolveCursor::CursorInfoConsumer::cancelled
anonymous func in SourceKit::SwiftLangSupport::getCursorInfo
anonymous func in handleRequestCursorInfo
reportCursorInfo
anonymous func in sourcekitd::handleRequest -> tries to get RequestTracker.RequestsMtx
```

rdar://110357502
2023-06-22 21:31:42 +02:00
Ben Barham
01086bc8b5 Merge pull request #65688 from bnbarham/swap-cursor-info-order
[CursorInfo] Prefer AST based results over solver based
2023-05-05 16:54:25 -07:00
Ben Barham
5beeca7cf1 [CursorInfo] Prefer AST based results over solver based
Solver based results are fast within a function, where the `ASTContext`
can be re-used. But it is significantly slower than the AST based
results when outside of a function. Instead of using solver based as the
primary results, only use them as a fallback for when AST based fails.

Resolves rdar://108930110.
2023-05-04 20:53:38 -07:00
Hamish Knight
62b021030f [SourceKit] Include generated macro buffers in diagnostic responses
Introduce a new key `generated_buffers`, which
stores an array of generated buffers. These
include the buffer text, as well as its original
location and any parent buffers.

While here, also fix rdar://107281079 such that
only apply the filename fallback logic to the
pretty-printed Decl case. We ought to remove this
fallback once the editor can handle it though.

rdar://107281079
rdar://107952288
2023-05-02 16:21:44 +01:00
Rintaro Ishizaki
a551c01d6a [Macros] Track plugin dependencies
* Factor out ASTContext plugin loading to newly introduced 'PluginLoader'
* Insert 'DependencyTracker' to 'PluginLoader'
* Add dependencies right before loading the plugins

rdar://104938481
2023-04-25 10:50:32 -07:00
Rintaro Ishizaki
a4d1fc6abe [SourceKit] Use a single PluginRegistry in multiple ASTContexts
Make a single 'PluginRegistry' and share it between SwiftASTManager,
IDEInspectionInstance, and CompileInstance. And inject the plugin
registry to ASTContext right after 'CompilerInstance.setup()'

That way, all sema-capable ASTContext in SourceKit share a single
PluginRegistry.
2023-03-27 14:59:08 -07:00
Alex Hoppen
a8dd6819b5 [IDE] Implement completion-like cursor info for ValueDecls
This brings up the ability to compute cursor info results using the completion-like type checking paradigm, which an reuse ASTContexts and doesn’t need to type check the entire file.

For now, the new implementation only supports cursor info on `ValueDecl`s (not on references) because they were easiest to implement. More cursor info kinds are coming soon.

At the moment, we only run the new implementation in a verification mode: It is only invoked in assert toolchains and when run, we check that the results are equivalent to the old implementation. Once more cursor info kinds are implemented and if the SourceKit stress tester doesn’t find any verification issues, we can enable the new implementation, falling back to the old implementation if the new one didn’t produce any results.
2022-12-08 14:39:14 +01:00
Alex Hoppen
9f6bc90d6d [SourceKit] Accept a file system in SwiftASTManager::getMemoryBuffer 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
Allan Shortlidge
d663c11df7 IDE: Move compiler invocation utils to break cycle with Frontend.
Move compiler invocation utilities up into the IDETool library which is designed to be dependent on the Frontend and FrontendTool libraries.
2022-10-29 17:51:53 -07:00
Josh Soref
436484c8c8 Gardening: Fix spelling mistakes in */SourceKit
* about
* and
* answering
* because
* before
* cancellation
* clear
* comment
* complete
* corresponding
* cursor
* custom
* dependencies
* doesn't
* expression
* extension
* immediately
* implementation
* implicit
* innovation
* intentionally
* occasionally
* oldest
* parameter
* property
* response
* reuseastcontext
* snapshot
* sourcekit_swift_runtime_link_flags
* synchronously
* target
* that
* unlabeled
* usefulness
* work

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>
2022-09-21 02:03:25 -04:00
Alex Hoppen
e22e443596 [SourceKit] Re-enable cancellation of non-completion requests
This enables the ability to cancel requests, which aren’t code completion requests, again.

Previous crashes in SILGen are prevented by disabling cancellation during the SIL stages. Instead, we add dedicated cancellation checkpoints before and after SIL.

rdar://98390926
2022-08-16 16:02:23 +02:00
Alex Hoppen
025e919b84 Merge pull request #42258 from ahoppen/pr/no-deadlock-cancellation
[SourceKit] Resolve a nondeterministic deadlock in SourceKit while cancelling
2022-05-19 09:27:27 +02:00
Alex Hoppen
727d3fec86 Merge pull request #58852 from ahoppen/pr/ubuntu-22-failure
[SourceKit] Pass the main swift executable path when constructing a compiler invocation
2022-05-14 08:36:35 +02:00
Alex Hoppen
1525f6b982 [SourceKit] Pass the main swift executable path when constructing a compiler invocation
#58786 (rdar://93030932) was failing because the `swift-frontend` invocations passed a `swiftExecutablePath` to `Invocation.parseArgs`. This caused the `ClangImporter` instance to point to a `clang` binary next to the `swift-frontend` executable while SourceKit used PATH to find `clang`. The clang executable next to `swift-frontend` doesn’t actually exist because `clang` lives in `llvm-linux-aarch64/bin` and `swift-frontend` lives in `swift-linux-aarch64/bin`.
So some checks for a minimum clang verison failed for the normal build (because the executable doesn’t actually exists) while they pass during the SourceKit build (which used `clang` from `PATH`). This in turn caused the `outline-atomics` to be enabled to the SourceKit clang compiler arguments but not the clang compiler arguments for a normal build and thus resulted in two separate module cache directories (which includes the enabled features in the module directory hash).

To fix this issue, also set the swift executable path for compiler invocations created from SourceKit.

Fixes #58786 (rdar://93030932)
2022-05-13 09:05:38 +02:00
Alex Hoppen
351770c2c3 [SourceKit] Guard DependencyStamps with a lock
We might run into situations where `matchesSourceState` reads `DependencyStamps` while they are being written in `buildASTUnit`, causing a crash.

Guard `DependencyStamps` by a mutex to avoid this problem. We don’t need to provide any ordering guarantees about whether `DependencyStamps` have been computed in are accessed because we already assume that the dependencies shouldn't change (much) in the time between an `ASTBuildOperation` is created and until it produced an AST.

rdar://92748564
2022-05-05 10:49:32 +02:00
Alex Hoppen
0124407300 [SourceKit] If setting up the compiler instance failed with an error, don't override it with a generic error message 2022-04-22 15:08:56 +02:00
Alex Hoppen
d7eada412f [SourceKit] Resolve a nondeterministic deadlock in SourceKit while cancelling
This fixes a race-conditioned deadlock which could occur while cancelling SourceKit AST build request

We have one thread that claimed `CancellationRequestCallbackMtx` in `SwiftASTConsumer::requestCancellation` and wants to claim `ConsumersAndResultMtx` in `ASTBuildOperation::requestConsumerCancellation`

Another thread claimed `ConsumersAndResultMtx` in `ASTBuildOperation::schedule` and now wants to claim `CancellationRequestCallbackMtx` in `SwiftASTConsumer::removeCancellationRequestCallback`.

In both cases we could actually release one lock before claiming the other.

Fixes rdar://90870793
2022-04-08 10:44:16 +02:00
Ben Barham
7cd4937290 [SourceKit] Disable cancellation of in-flight non-completion requests
We need to run SILGen for diagnostics (to actually get all diagnostics).
All non-completion requests share an AST and thus they too run SILGen.
Any lazy typechecking run in SILGen assumes that it succeeds.

Cancellation can cause typechecking to fail here though, since we simply
check the flag and error if it's set. This unfortunately has the ability
to cause any any number of crashes since various invariants in SILGen
are then broken.

Disable cancellation of in-flight non-completion requests for now until
we have a proper fix in place.

Resolves rdar://91251017.
2022-04-04 13:13:33 -07:00
Ben Barham
15ada41a5a [SourceKit] Make sure to use overlays when reading files
Two paths missed setting up overlays:
  - `CompletionInstance` when checking files from dependencies
  - `SwiftASTManager` when reading in files that it would later replace
    all inputs with

(1) would cause the AST context not to be re-used, even though nothing
had changed. (2) caused all non-completion functionality to fail for any
symbols within files only specified by the overlay.

Resolves rdar://85508213.
2022-03-24 15:30:02 -07:00
Alex Hoppen
4fc9d015de Merge pull request #40107 from ahoppen/pr/load-stdlib-in-setup
[Frontend] Load standard libarary in CompilerInstance::setup
2021-12-14 13:45:23 +01:00
Alex Hoppen
f5b6103ef7 [SourceKit] Fix a crash that occurred when a document without an associated source file is reopened
When opening a file for the first time, we don’t store a snapshot for it. This could cause a crash when trying to consult its snapshot to see whether an AST can be reused for cursor info.
2021-12-13 16:43:32 +01:00
Alex Hoppen
22f67e89a6 [SourceKit] Explicitly specify frontend action type when creating compiler invocation
Explicitly specify the frontend action to make sure we aren’t loading thes stdlib if the performed action is syntactic only.
2021-12-13 15:32:08 +01:00
Alex Hoppen
63c31033fc [Frontend] Load standard libarary in CompilerInstance::setup
Instead of checking that the stdlib can be loaded in a variety of places, check it when setting up the compiler instance. This required a couple more checks to avoid loading the stdlib in cases where it’s not needed.

To be able to differentiate stdlib loading failures from other setup errors, make `CompilerInstance::setup` return an error message on failure via an inout parameter. Consume that error on the call side, replacing a previous, more generic error message, adding error handling where appropriate or ignoring the error message, depending on the context.
2021-12-13 15:32:08 +01:00
Alex Hoppen
c90c7a2975 [SourceKit] Enqueue SwiftASTConsumers async on a queue
Enqueuing `SwiftASTConsumer`s might be expensive because `getBuildOperationForConsumer` consults the file system. Since all results from the AST build are processed asynchronously anyway, there’s no need to perform the enqueuing  synchronously.

rdar://86289703
2021-12-10 09:11:02 +01:00
Alex Hoppen
4aa911023a Merge pull request #40339 from ahoppen/pr/improve-sourcekit-stamp-handling
[SourceKit] Improvements to stamp handling in SwiftASTManager
2021-12-09 23:53:59 +01:00
Alex Hoppen
e17faa5bcf [SourceKit] Improve memory cost function of ASTBuildOperation 2021-12-08 15:17:13 +01:00
Alex Hoppen
3adb9c2823 [SourceKit] Make FileContent non ref-counted
We never need to have two copies of the same `FileContent` object, so we don’t need a copy constructor and can thus pass it on the stack again, instead of storing it on the heap.
2021-12-08 15:17:13 +01:00
Alex Hoppen
dcbedc65fd [SourceKit] Remove some dupliate computation of realpaths 2021-12-08 15:17:13 +01:00
Alex Hoppen
5f4b1a0b27 [SourceKit] Don't store Stamps in ASTBuildOperation
FileContents already contains the stamps.
2021-12-08 15:17:13 +01:00
Alex Hoppen
a8bfd4fe44 [SourceKit] Store FileContents in ASTBuildOperation instead of snapshots 2021-12-08 15:17:13 +01:00
Alex Hoppen
de25265de0 [SourceKit] Remove ability to specify fixed snapshots to use when building an AST
The feature was never used and just complicated the implementation.
2021-12-08 15:17:13 +01:00
Alex Hoppen
9042536323 [SourceKit] Move the cancellation flag from TypeCheckerOptions to ASTContext
We need to modify the pointer pointing to the cancellation flag when reusing an ASTContext for code completion. This is not possible by the previous design because `TypeCheckerOptions` was `const`. Moving the cancellation flag to `ASTContext` will also allow other stages of the compiler to honor a cancellation request.
2021-12-02 12:57:34 +01:00
Alex Hoppen
772485def3 [SourceKit] Add a request tracker that manages cancellaiton
Previously, `SwiftASTManager` and `SlowRequestSimulator` maintained their own list of in-progress cancellation tokens. With code completion cancellation coming up, there would need to be yet another place to track in-progress requests, so let’s centralize it.

While at it, also support cancelling requests before they are scheduled, eliminating the need for a `sleep` in a test case.

The current implementaiton leaks tiny amounts of memory if a request is cancelled after if finishes. I think this is fine because it is a pretty nieche case and the leaked memory is pretty small (a `std::map` entry pointing to a `std::function` + `bool`). Alternatively, we could require the client to always dispose of the cancellation token manually.
2021-11-10 22:11:02 +01:00
Alex Hoppen
7d5ee83a61 [SourceKit] Allow explicit cancellation of requests with a cancellation token
The key changes here are
- To keep track of cancellation tokens for all `ScheduledConsumer`s in `SwiftASTManager`
- Generate unique request handles for all incoming requests (`create_request_handle `), use these request handles as cancellation tokens and return them from the `sourcekitd_send_request` methods
- Implement cancellation with `sourcekitd_cancel_request` as the entry point and `SwiftASTManager::cancelASTConsumer` as the termination point

Everything else is just plumbing the cancellation token through the various abstraction layers.

rdar://83391505
2021-09-30 11:45:24 +02:00
Alex Hoppen
7a80034e35 [SourceKit] Support cancellation of requests while an AST is being built
This commit refactors the way ASTs are being built in SourceKit and how `SwiftASTConsumer`s are served by the built ASTs. `SwiftASTManager.h` should give an overview of the new design.

This commit does not change the cancellation paradigm in SourceKit (yet). That is, subsequent requests with the same `OncePerASTToken` still cancel previous requests with the same token. But while previously, we were only able to cancel requests that haven’t started an AST build yet, we can now also cancel the AST build of the to-be-cancelled requests.

With this change in place, we can start looking into explicit cancellation of requests or other cancellation paradigms.
2021-09-23 11:53:45 +02:00
Ben Barham
73d9f5b843 [SourceKit] Remove OptimizeForIDE global configuration
Have SourceKit return locations for symbols outside of the current
module as well. Callsites of location and comment information should
explicitly disable retrieving serialized information where performance
is a concern.

Resolves rdar://75582627
2021-05-01 11:37:23 +10:00
Alex Hoppen
4107d02759 [SourceKit] Verify the stdlib is loaded before creating an AST
We have seen a couple of crashes that look like they are being caused by `sourcekitd` being unable to load the Swift stdlib. Emit a proper error message explaining the issue instead of crashing.

This change assumes that all sourcekitd requests that create an AST require the stdlib. IMHO this is a reasonable assumption.

Fixes rdar://75740572 by catching the crash in the new check.
2021-04-07 14:25:25 +02:00
Brent Royal-Gordon
b440ab7331 [NFC] Move several types/functions to Import.h
To help consolidate our various types describing imports, this commit moves the following types and methods to Import.h:

* ImplicitImports
* ImplicitStdlibKind
* ImplicitImportInfo
* ModuleDecl::ImportedModule
* ModuleDecl::OrderImportedModules (as ImportedModule::Order)
* ModuleDecl::removeDuplicateImports() (as ImportedModule::removeDuplicates())
* SourceFile::ImportFlags
* SourceFile::ImportOptions
* SourceFile::ImportedModuleDesc

This commit is large and intentionally kept mechanical—nothing interesting to see here.
2020-10-09 18:57:07 -07:00
Varun Gandhi
d3369f7711 [NFC] Rename ImportFilterKind cases to be clearer. 2020-09-23 12:50:20 -07:00
Robert Widmann
a8766cce5b [NFC] Refactor InputFile's Accessors 2020-09-11 22:28:58 -06:00
Ben Langmuir
0d42d7d915 [gardening] format changed code 2020-08-25 10:43:43 -07:00
Ben Langmuir
af78895c45 [gardening] Sink compiler invocation code into libIDE 2020-08-25 10:39:37 -07:00
Martin Boehme
d806ba53f6 Give OptionSet an initializer_list constructor.
This makes it easier to specify OptionSet arguments.

Also modify appropriate uses of ModuleDecl::ImportFilter to take
advantage of the new constructor.
2020-06-22 06:57:29 +02:00
Ben Langmuir
fadfb6c945 Merge pull request #31874 from benlangmuir/driver-tmp-sad
[driver/sourcekit] Avoid creating temporary output files in TMPDIR
2020-06-05 13:43:23 -07:00