Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Sources/BuildServerIntegration/BuildServerManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,10 @@ private enum BuildServerAdapter {
if Task.isCancelled {
return continuation.resume(throwing: CancellationError())
}
requestID.value = messageHandler.send(request) { response in
let id = messageHandler.send(request) { response in
continuation.resume(with: response)
}
requestID.withLock { $0 = id }
if Task.isCancelled {
// The task might have been cancelled after we checked `Task.isCancelled` above but before `requestID.value`
// is set, we won't send a `CancelRequestNotification` from the `onCancel` handler. Send it from here.
Expand Down
2 changes: 1 addition & 1 deletion Sources/Diagnose/DiagnoseCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ package struct DiagnoseCommand: AsyncParsableCommand {
)
try process.launch()
try await process.waitUntilExit()
processExited.value = true
processExited.withLock { $0 = true }
#endif
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import IndexStoreDB
import SemanticIndex
@_spi(Linkcompletion) @preconcurrency import SwiftDocC
import SwiftExtensions
@_spi(SourceKitLSP) import ToolsProtocolsSwiftExtensions

final class DocCReferenceResolutionService: DocumentationService, Sendable {
/// The message type that this service accepts.
Expand All @@ -33,11 +34,11 @@ final class DocCReferenceResolutionService: DocumentationService, Sendable {
init() {}

func addContext(_ context: DocCReferenceResolutionContext, withKey key: String) {
contextMap.value[key] = context
contextMap.withLock { $0[key] = context }
}

@discardableResult func removeContext(forKey key: String) -> DocCReferenceResolutionContext? {
contextMap.value.removeValue(forKey: key)
contextMap.withLock { $0.removeValue(forKey: key) }
}

func context(forKey key: String) -> DocCReferenceResolutionContext? {
Expand Down
3 changes: 2 additions & 1 deletion Sources/InProcessClient/InProcessSourceKitLSPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,10 @@ public final class InProcessSourceKitLSPClient: Sendable {
// possible.
return continuation.resume(throwing: CancellationError())
}
requestId.value = self.send(request) {
let id = self.send(request) {
continuation.resume(with: $0)
}
requestId.withLock { $0 = id }
if Task.isCancelled, let requestId = requestId.takeValue() {
// The task might have been cancelled after the above cancellation check but before `requestId` was assigned
// a value. To cover that case, check for cancellation here again. Note that we won't cancel twice from here
Expand Down
2 changes: 1 addition & 1 deletion Sources/SKTestSupport/CustomBuildServerTestProject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ package final class CustomBuildServerTestProject<BuildServer: CustomBuildServer>
XCTAssertNil(hooks.buildServerHooks.injectBuildServer)
hooks.buildServerHooks.injectBuildServer = { [buildServerBox] projectRoot, connectionToSourceKitLSP in
let buildServer = BuildServer(projectRoot: projectRoot, connectionToSourceKitLSP: connectionToSourceKitLSP)
buildServerBox.value = buildServer
buildServerBox.withLock { $0 = buildServer }
return LocalConnection(receiverName: "TestBuildServer", handler: buildServer)
}
try await super.init(
Expand Down
10 changes: 5 additions & 5 deletions Sources/SKTestSupport/TestSourceKitLSPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ final class PendingNotifications: Sendable {
private let values = ThreadSafeBox<[any NotificationType]>(initialValue: [])

nonisolated func add(_ value: any NotificationType) {
values.value.insert(value, at: 0)
values.withLock { $0.insert(value, at: 0) }
}

func next(timeout: Duration, pollingInterval: Duration = .milliseconds(10)) async throws -> any NotificationType {
for _ in 0..<Int(timeout.seconds / pollingInterval.seconds) {
if let value = values.value.popLast() {
if let value = values.withLock({ $0.popLast() }) {
return value
}
try await Task.sleep(for: pollingInterval)
Expand Down Expand Up @@ -387,12 +387,12 @@ package final class TestSourceKitLSPClient: MessageHandler, Sendable {
/// The request handler will only handle a single request. If the request is called again, the request handler won't
/// call again
package func handleSingleRequest<R: RequestType>(_ requestHandler: @escaping RequestHandler<R>) {
requestHandlers.value.append((requestHandler: requestHandler, isOneShot: true))
requestHandlers.withLock { $0.append((requestHandler: requestHandler, isOneShot: true)) }
}

/// Handle all requests of the given type that are sent to the client.
package func handleMultipleRequests<R: RequestType>(_ requestHandler: @escaping RequestHandler<R>) {
requestHandlers.value.append((requestHandler: requestHandler, isOneShot: false))
requestHandlers.withLock { $0.append((requestHandler: requestHandler, isOneShot: false)) }
}

/// Executes `operation` and waits until a request of the specified type is received from the server.
Expand All @@ -407,7 +407,7 @@ package final class TestSourceKitLSPClient: MessageHandler, Sendable {
// Register a one-shot handler that records when the request arrives.
let received = ThreadSafeBox<Bool>(initialValue: false)
self.handleSingleRequest { (_: R) in
received.value = true
received.withLock { $0 = true }
return VoidResponse()
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/SemanticIndex/CheckedIndex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package import Foundation
@_spi(SourceKitLSP) package import LanguageServerProtocol
@_spi(SourceKitLSP) import SKLogging
import SwiftExtensions
@_spi(SourceKitLSP) import ToolsProtocolsSwiftExtensions

/// Essentially a `DocumentManager` from the `SourceKitLSP` module.
///
Expand Down Expand Up @@ -355,7 +356,7 @@ package final actor UncheckedIndex: Sendable {
package func close() {
// IndexStoreDB writes the index to disk when the retain count of the `IndexStoreDB` object hits zero. We hope that
// nobody else still has a reference to `IndexStoreDB` here.
_underlyingIndexStoreDB.value = nil
_underlyingIndexStoreDB.withLock { $0 = nil }
}

/// Update the set of output paths that should be considered visible in the project. For example, if a source file is
Expand Down
2 changes: 1 addition & 1 deletion Sources/SourceKitD/SourceKitD.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ extension sourcekitd_api_values: @unchecked Sendable {}
fileprivate extension ThreadSafeBox {
/// If the wrapped value is `nil`, run `compute` and store the computed value. If it is not `nil`, return the stored
/// value.
func computeIfNil<WrappedValue: Sendable>(compute: () -> WrappedValue) -> WrappedValue where T == WrappedValue? {
func computeIfNil<WrappedValue: Sendable>(compute: () -> WrappedValue) -> WrappedValue where Value == WrappedValue? {
return withLock { (value: inout WrappedValue?) -> WrappedValue in
if let value {
return value
Expand Down
3 changes: 2 additions & 1 deletion Sources/SourceKitD/dlopen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

@_spi(SourceKitLSP) import SKLogging
import SwiftExtensions
@_spi(SourceKitLSP) import ToolsProtocolsSwiftExtensions

#if os(Windows)
import CRT
Expand Down Expand Up @@ -79,7 +80,7 @@ package final class DLHandle: Sendable {

/// The handle must not be used anymore after calling `leak`.
package func leak() {
rawValue.value = nil
rawValue.withLock { $0 = nil }
}
}

Expand Down
1 change: 1 addition & 0 deletions Sources/SourceKitLSP/DocumentManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package import SKUtilities
import SemanticIndex
import SwiftExtensions
package import SwiftSyntax
@_spi(SourceKitLSP) import ToolsProtocolsSwiftExtensions

/// An immutable snapshot of a document at a given time.
///
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftExtensions/AsyncUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ package func withTimeoutResult<T: Sendable>(
let stream = AsyncThrowingStream<WithTimeoutResult<T>, any Error> { continuation in
Task {
try await Task.sleep(for: timeout)
didHitTimeout.value = true
didHitTimeout.withLock { $0 = true }
continuation.yield(.timedOut)
}

Expand Down
2 changes: 0 additions & 2 deletions Sources/SwiftExtensions/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ set(sources
Duration+Seconds.swift
FileManagerExtensions.swift
LazyValue.swift
NSLock+WithLock.swift
PipeAsStringHandler.swift
Platform.swift
Process+terminate.swift
ResultExtensions.swift
RunWithCleanup.swift
Sequence+AsyncMap.swift
Sequence+ContainsAnyIn.swift
ThreadSafeBox.swift
TransitiveClosure.swift
URLExtensions.swift
)
Expand Down
21 changes: 0 additions & 21 deletions Sources/SwiftExtensions/NSLock+WithLock.swift

This file was deleted.

65 changes: 0 additions & 65 deletions Sources/SwiftExtensions/ThreadSafeBox.swift

This file was deleted.

2 changes: 1 addition & 1 deletion Sources/TSCExtensions/Process+Run.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ extension Process {
let hasExited = ThreadSafeBox<Bool>(initialValue: false)
return try await withTaskCancellationHandler {
defer {
hasExited.value = true
hasExited.withLock { $0 = true }
}
return try await waitUntilExit()
} onCancel: {
Expand Down
1 change: 1 addition & 0 deletions Sources/ToolchainRegistry/Toolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import RegexBuilder
@_spi(SourceKitLSP) import SKLogging
import SwiftExtensions
import TSCExtensions
@_spi(SourceKitLSP) import ToolsProtocolsSwiftExtensions

import class TSCBasic.Process

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import SKTestSupport
import SwiftExtensions
import TSCBasic
import ToolchainRegistry
@_spi(SourceKitLSP) import ToolsProtocolsSwiftExtensions
import XCTest

fileprivate actor TestBuildServer: CustomBuildServer {
Expand Down Expand Up @@ -63,7 +64,7 @@ private func createBuildServerManager(
kind: .injected({ projectRoot, connectionToSourceKitLSP in
assert(testBuildServer.value == nil, "Build server injector hook can only create a single TestBuildServer")
let buildServer = TestBuildServer(projectRoot: projectRoot, connectionToSourceKitLSP: connectionToSourceKitLSP)
testBuildServer.value = buildServer
testBuildServer.withLock { $0 = buildServer }
return LocalConnection(receiverName: "TestBuildServer", handler: buildServer)
}),
projectRoot: dummyPath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1334,11 +1334,11 @@ struct SwiftPMBuildServerTests {
in: tempDir,
reloadPackageDidStart: {
if packageInitialized.value {
unexpectedReloadStarted.value = true
unexpectedReloadStarted.withLock { $0 = true }
}
}
)
packageInitialized.value = true
packageInitialized.withLock { $0 = true }

// SwiftPM extracts the artifact bundle to:
// <scratch>/artifacts/<package-identity>/<target-name>/<artifact-name>/
Expand Down Expand Up @@ -1388,11 +1388,11 @@ struct SwiftPMBuildServerTests {
options: SourceKitLSPOptions(swiftPM: .init(scratchPath: try customScratch.filePath)),
reloadPackageDidStart: {
if packageInitialized.value {
unexpectedReloadStarted.value = true
unexpectedReloadStarted.withLock { $0 = true }
}
}
)
packageInitialized.value = true
packageInitialized.withLock { $0 = true }

// With a custom scratch path, SwiftPM extracts to <custom-scratch>/artifacts/.
// Simulate the delete-and-re-expand cycle for those paths.
Expand Down
2 changes: 1 addition & 1 deletion Tests/SemanticIndexTests/TaskSchedulerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ final class TaskSchedulerTests: SourceKitLSPTestCase {
return
}

taskExecutedBefore.value = true
taskExecutedBefore.withLock { $0 = true }

taskStartedExecuting.fulfill()

Expand Down
15 changes: 9 additions & 6 deletions Tests/SourceKitLSPTests/BackgroundIndexingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1392,7 +1392,7 @@ final class BackgroundIndexingTests: SourceKitLSPTestCase {
hooks: testHooks,
enableBackgroundIndexing: true
)
packageInitialized.value = true
packageInitialized.withLock { $0 = true }
project.testClient.send(
DidChangeWatchedFilesNotification(changes: [
FileEvent(uri: DocumentURI(project.scratchDirectory.appending(component: "random.swift")), type: .created)
Expand Down Expand Up @@ -2186,7 +2186,7 @@ final class BackgroundIndexingTests: SourceKitLSPTestCase {
return data.title == "Indexing"
}
)
receivedReportProgressNotification.value = true
receivedReportProgressNotification.withLock { $0 = true }

// Check that we receive an `end` notification
_ = try await project.testClient.nextNotification(
Expand Down Expand Up @@ -2255,7 +2255,7 @@ final class BackgroundIndexingTests: SourceKitLSPTestCase {

// Ensure that changing `/private/tmp/.../test.c` only causes `/tmp/.../test.c` to be indexed, not
// `/private/tmp/.../test.c`.
indexedFiles.value = []
indexedFiles.withLock { $0 = [] }
let testFileURL = try XCTUnwrap(project.uri(for: "test.c").fileURL?.realpath)
try await "void y() {}".writeWithRetry(to: testFileURL)
project.testClient.send(
Expand Down Expand Up @@ -2603,7 +2603,7 @@ final class BackgroundIndexingTests: SourceKitLSPTestCase {
let symbolsBeforeUpdate = try await project.testClient.send(WorkspaceSymbolsRequest(query: "myTestFu"))
XCTAssertEqual(symbolsBeforeUpdate, [])

testSetupComplete.value = true
testSetupComplete.withLock { $0 = true }
try await project.changeFileOnDisk(
"Test.swift",
newMarkedContents: """
Expand All @@ -2627,8 +2627,11 @@ final class BackgroundIndexingTests: SourceKitLSPTestCase {
let testHooks = Hooks(
buildServerHooks: BuildServerHooks(preHandleRequest: { request in
if let request = request as? BuildTargetPrepareRequest {
preparationRequests.value.append(request)
if preparationRequests.value.count >= 2 {
let count = preparationRequests.withLock { (value: inout [BuildTargetPrepareRequest]) in
value.append(request)
return value.count
}
if count >= 2 {
twoPreparationRequestsReceived.fulfill()
}
}
Expand Down
2 changes: 1 addition & 1 deletion Tests/SourceKitLSPTests/ClangdTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ final class ClangdTests: SourceKitLSPTestCase {
let clangdServer = try await unwrap(testClient.primaryLanguageService(for: uri))
await clangdServer.addStateChangeHandler { oldState, newState in
if oldState == .connectionInterrupted, newState == .connected {
clangdRestarted.value = true
clangdRestarted.withLock { $0 = true }
clangdRestartedExpectation.fulfill()
}
}
Expand Down
Loading