From 98cd30bb1cd37ae09fb06b07e198c6d51299d47b Mon Sep 17 00:00:00 2001 From: Alex Hoppen Date: Mon, 11 Aug 2025 09:23:39 +0200 Subject: [PATCH 1/2] Apply exhaustive swift-format configuration from swift-syntax Apply the exhaustive swift-format configuration from https://github.com/swiftlang/swift-syntax/pull/3117 to sourcekit-lsp. Also apply all automatic formattings. --- .swift-format | 68 +++++++++++++++++-- .../Sources/ConfigSchemaGen/JSONSchema.swift | 4 +- .../BuildServerManager.swift | 4 +- .../CompilerCommandLineOption.swift | 2 +- .../SplitShellCommand.swift | 4 +- .../SwiftPMBuildServer.swift | 10 +-- Sources/BuildServerProtocol/Messages.swift | 4 +- .../Components/PopularityTable.swift | 2 +- .../Semantics/SemanticClassification.swift | 2 +- .../Text/InfluencingIdentifiers.swift | 6 +- .../Text/MatchCollator.swift | 2 +- Sources/CompletionScoring/Text/Pattern.swift | 9 +-- .../Utilities/SwiftExtensions.swift | 4 +- .../CommandLineArgumentsReducer.swift | 2 +- Sources/Diagnose/DiagnoseCommand.swift | 8 +-- Sources/Diagnose/SourceReducer.swift | 26 +++---- .../Diagnose/TraceFromSignpostsCommand.swift | 6 +- .../DocCCatalogIndexManager.swift | 2 +- Sources/DocCDocumentation/DocCServer.swift | 2 +- .../DocCSymbolInformation.swift | 2 +- .../CustomCodable.swift | 8 +-- .../Requests/HoverRequest.swift | 4 +- .../Requests/SignatureHelpRequest.swift | 4 +- .../WorkDoneProgressManager.swift | 2 +- .../JSONRPCConnection.swift | 6 +- .../CustomLogStringConvertible.swift | 2 +- Sources/SKLogging/NonDarwinLogging.swift | 2 +- .../SKLogging/SetGlobalLogFileHandler.swift | 6 +- Sources/SKOptions/SourceKitLSPOptions.swift | 2 +- ...ompletionItem+clearingUnstableValues.swift | 2 +- .../ExternalBuildServerTestProject.swift | 2 +- Sources/SKTestSupport/LocationMarkers.swift | 6 +- .../TestSourceKitLSPClient.swift | 2 +- .../SemanticIndex/SemanticIndexManager.swift | 14 ++-- Sources/SemanticIndex/TaskScheduler.swift | 2 +- .../UpdateIndexStoreTaskDescription.swift | 14 ++-- Sources/SourceKitD/SKDRequestArray.swift | 6 +- Sources/SourceKitD/SKDRequestDictionary.swift | 10 +-- Sources/SourceKitD/SourceKitD.swift | 6 +- Sources/SourceKitD/SourceKitDRegistry.swift | 2 +- .../SourceKitLSP/IndexProgressManager.swift | 2 +- Sources/SourceKitLSP/Rename.swift | 12 ++-- Sources/SourceKitLSP/SourceKitLSPServer.swift | 6 +- .../AdjustPositionToStartOfIdentifier.swift | 2 +- .../ConvertJSONToCodableStruct.swift | 4 +- .../Swift/CodeCompletionSession.swift | 2 +- Sources/SourceKitLSP/Swift/Diagnostic.swift | 2 +- .../Swift/DoccDocumentation.swift | 2 +- .../Swift/DocumentFormatting.swift | 8 +-- .../SourceKitLSP/Swift/DocumentSymbols.swift | 2 +- Sources/SourceKitLSP/Swift/FoldingRange.swift | 2 +- .../Swift/RefactoringResponse.swift | 2 +- .../Swift/SwiftLanguageService.swift | 4 +- .../Swift/SyntacticTestIndex.swift | 6 +- Sources/SourceKitLSP/TestDiscovery.swift | 4 +- Sources/SwiftExtensions/AsyncUtils.swift | 2 +- .../ASTCompletion/ASTCompletionItem.swift | 4 +- .../CodeCompletion/Connection.swift | 4 +- .../CompletionResultsArrayBuilder.swift | 2 +- .../SKDResponseArrayBuilder.swift | 6 +- .../SKDResponseDictionaryBuilder.swift | 6 +- .../SKDResponseValue.swift | 4 +- .../CompletionResultsArray.swift | 2 +- .../SwitchableProcessResultExitStatus.swift | 6 +- Sources/ToolchainRegistry/Toolchain.swift | 2 +- .../ToolchainRegistry/ToolchainRegistry.swift | 30 ++++---- .../CompilationDatabaseTests.swift | 2 +- ...mpilerCommandLineOptionMatchingTests.swift | 2 +- .../SwiftExtensionsTests.swift | 2 +- .../XCTestCaseScoringAdditions.swift | 2 +- .../MessageParsingTests.swift | 2 +- .../LanguageServerProtocolTests.swift | 2 +- Tests/SKLoggingTests/LoggingTests.swift | 2 +- Tests/SKUtilitiesTests/LRUCacheTests.swift | 2 +- .../SKUtilitiesTests/LineTablePerfTests.swift | 4 +- .../TaskSchedulerTests.swift | 12 ++-- .../ClosureCompletionFormatTests.swift | 4 +- .../CompilationDatabaseTests.swift | 2 +- .../CrashRecoveryTests.swift | 2 +- .../DoccDocumentationTests.swift | 8 +-- .../DocumentSymbolTests.swift | 2 +- .../DocumentationLanguageServiceTests.swift | 2 +- .../SemanticTokensTests.swift | 6 +- .../SyntaxRefactorTests.swift | 4 +- .../TypeHierarchyTests.swift | 2 +- Tests/SourceKitLSPTests/WorkspaceTests.swift | 2 +- .../SwiftSourceKitPluginTests.swift | 10 +-- 87 files changed, 264 insertions(+), 211 deletions(-) diff --git a/.swift-format b/.swift-format index 176687e28..e882b3623 100644 --- a/.swift-format +++ b/.swift-format @@ -1,20 +1,76 @@ { - "version": 1, - "lineLength": 120, + "fileScopedDeclarationPrivacy": { + "accessLevel": "private" + }, + "indentConditionalCompilationBlocks": false, + "indentSwitchCaseLabels": false, "indentation": { "spaces": 2 }, + "lineBreakAroundMultilineExpressionChainComponents": false, + "lineBreakBeforeControlFlowKeywords": false, "lineBreakBeforeEachArgument": true, - "indentConditionalCompilationBlocks": false, + "lineBreakBeforeEachGenericRequirement": false, + "lineBreakBetweenDeclarationAttributes": false, + "lineLength": 120, + "maximumBlankLines": 1, + "multiElementCollectionTrailingCommas": true, + "noAssignmentInExpressions": { + "allowedFunctions": [ + "XCTAssertNoThrow" + ] + }, "prioritizeKeepingFunctionOutputTogether": true, + "reflowMultilineStringLiterals": { + "never": { + + } + }, + "respectsExistingLineBreaks": true, "rules": { + "AllPublicDeclarationsHaveDocumentation": false, + "AlwaysUseLiteralForEmptyCollectionInit": false, "AlwaysUseLowerCamelCase": false, "AmbiguousTrailingClosureOverload": false, + "BeginDocumentationCommentWithOneLineSummary": false, + "DoNotUseSemicolons": false, + "DontRepeatTypeInStaticProperties": false, + "FileScopedDeclarationPrivacy": true, + "FullyIndirectEnum": true, + "GroupNumericLiterals": true, + "IdentifiersMustBeASCII": true, + "NeverForceUnwrap": false, + "NeverUseForceTry": false, + "NeverUseImplicitlyUnwrappedOptionals": false, + "NoAccessLevelOnExtensionDeclaration": false, + "NoAssignmentInExpressions": true, "NoBlockComments": false, + "NoCasesWithOnlyFallthrough": true, + "NoEmptyTrailingClosureParentheses": true, + "NoLabelsInCasePatterns": true, + "NoLeadingUnderscores": false, + "NoParensAroundConditions": true, + "NoPlaygroundLiterals": true, + "NoVoidReturnOnFunctionSignature": true, + "OmitExplicitReturns": false, + "OneCasePerLine": true, + "OneVariableDeclarationPerLine": true, + "OnlyOneTrailingClosureArgument": true, "OrderedImports": true, + "ReplaceForEachWithForLoop": true, + "ReturnVoidInsteadOfEmptyTuple": true, + "TypeNamesShouldBeCapitalized": true, + "UseEarlyExits": false, + "UseExplicitNilCheckInConditions": true, "UseLetInEveryBoundCaseVariable": false, + "UseShorthandTypeNames": true, + "UseSingleLinePropertyGetter": true, "UseSynthesizedInitializer": false, - "ReturnVoidInsteadOfEmptyTuple": true, - "NoVoidReturnOnFunctionSignature": true, - } + "UseTripleSlashForDocumentationComments": true, + "UseWhereClausesInForLoops": false, + "ValidateDocumentationComments": false + }, + "spacesAroundRangeFormationOperators": false, + "spacesBeforeEndOfLineComments": 2, + "version": 1, } diff --git a/SourceKitLSPDevUtils/Sources/ConfigSchemaGen/JSONSchema.swift b/SourceKitLSPDevUtils/Sources/ConfigSchemaGen/JSONSchema.swift index ec35b5700..55f578633 100644 --- a/SourceKitLSPDevUtils/Sources/ConfigSchemaGen/JSONSchema.swift +++ b/SourceKitLSPDevUtils/Sources/ConfigSchemaGen/JSONSchema.swift @@ -101,10 +101,10 @@ struct JSONSchemaBuilder { case .integer: schema.type = "integer" case .number: schema.type = "number" case .string: schema.type = "string" - case .array(value: let value): + case .array(let value): schema.type = "array" schema.items = try buildJSONSchema(from: value) - case .dictionary(value: let value): + case .dictionary(let value): schema.type = "object" schema.additionalProperties = try buildJSONSchema(from: value) case .struct(let structInfo): diff --git a/Sources/BuildServerIntegration/BuildServerManager.swift b/Sources/BuildServerIntegration/BuildServerManager.swift index 8ba56a580..cfb1f85b3 100644 --- a/Sources/BuildServerIntegration/BuildServerManager.swift +++ b/Sources/BuildServerIntegration/BuildServerManager.swift @@ -24,7 +24,7 @@ package import ToolchainRegistry import struct TSCBasic.RelativePath -fileprivate typealias RequestCache = Cache +private typealias RequestCache = Cache /// An output path returned from the build server in the `SourceItem.data.outputPath` field. package enum OutputPath: Hashable, Comparable, CustomLogStringConvertible { @@ -1627,7 +1627,7 @@ fileprivate extension TextDocumentSourceKitOptionsResponse { } } -fileprivate let supplementalClangIndexingArgs: [String] = [ +private let supplementalClangIndexingArgs: [String] = [ // Retain extra information for indexing "-fretain-comments-from-system-headers", // Pick up macro definitions during indexing diff --git a/Sources/BuildServerIntegration/CompilerCommandLineOption.swift b/Sources/BuildServerIntegration/CompilerCommandLineOption.swift index 9aaeba464..6ead619d4 100644 --- a/Sources/BuildServerIntegration/CompilerCommandLineOption.swift +++ b/Sources/BuildServerIntegration/CompilerCommandLineOption.swift @@ -151,7 +151,7 @@ package struct CompilerCommandLineOption { } } -extension Array { +extension [CompilerCommandLineOption] { func firstMatch(for argument: String) -> CompilerCommandLineOption.Match? { for optionToRemove in self { if let match = optionToRemove.matches(argument: argument) { diff --git a/Sources/BuildServerIntegration/SplitShellCommand.swift b/Sources/BuildServerIntegration/SplitShellCommand.swift index 93f2a4fe1..0460cc5a5 100644 --- a/Sources/BuildServerIntegration/SplitShellCommand.swift +++ b/Sources/BuildServerIntegration/SplitShellCommand.swift @@ -12,7 +12,7 @@ // MARK: - Unix -fileprivate struct UnixCommandParser { +private struct UnixCommandParser { var content: Substring var i: Substring.UTF8View.Index var result: [String] = [] @@ -162,7 +162,7 @@ fileprivate extension Character { } } -fileprivate struct WindowsCommandParser { +private struct WindowsCommandParser { /// The content of the entire command that shall be parsed. private let content: String diff --git a/Sources/BuildServerIntegration/SwiftPMBuildServer.swift b/Sources/BuildServerIntegration/SwiftPMBuildServer.swift index f0b609341..037a93a1f 100644 --- a/Sources/BuildServerIntegration/SwiftPMBuildServer.swift +++ b/Sources/BuildServerIntegration/SwiftPMBuildServer.swift @@ -36,7 +36,7 @@ import struct TSCBasic.AbsolutePath import class TSCBasic.Process package import class ToolchainRegistry.Toolchain -fileprivate typealias AbsolutePath = Basics.AbsolutePath +private typealias AbsolutePath = Basics.AbsolutePath /// A build target in SwiftPM package typealias SwiftBuildTarget = SourceKitLSPAPI.BuildTarget @@ -78,7 +78,7 @@ fileprivate extension TSCBasic.AbsolutePath { } } -fileprivate let preparationTaskID: AtomicUInt32 = AtomicUInt32(initialValue: 0) +private let preparationTaskID: AtomicUInt32 = AtomicUInt32(initialValue: 0) /// Swift Package Manager build server and workspace support. /// @@ -779,7 +779,7 @@ package actor SwiftPMBuildServer: BuiltInBuildServer { switch exitStatus { case .terminated(code: 0): break - case .terminated(code: let code): + case .terminated(let code): // This most likely happens if there are compilation errors in the source file. This is nothing to worry about. let stdout = (try? String(bytes: result.output.get(), encoding: .utf8)) ?? "" let stderr = (try? String(bytes: result.stderrOutput.get(), encoding: .utf8)) ?? "" @@ -792,14 +792,14 @@ package actor SwiftPMBuildServer: BuiltInBuildServer { \(stdout) """ ) - case .signalled(signal: let signal): + case .signalled(let signal): if !Task.isCancelled { // The indexing job finished with a signal. Could be because the compiler crashed. // Ignore signal exit codes if this task has been cancelled because the compiler exits with SIGINT if it gets // interrupted. logger.error("Preparation of target \(target.forLogging) signaled \(signal)") } - case .abnormal(exception: let exception): + case .abnormal(let exception): if !Task.isCancelled { logger.error("Preparation of target \(target.forLogging) exited abnormally \(exception)") } diff --git a/Sources/BuildServerProtocol/Messages.swift b/Sources/BuildServerProtocol/Messages.swift index e252ad4e5..5a597488d 100644 --- a/Sources/BuildServerProtocol/Messages.swift +++ b/Sources/BuildServerProtocol/Messages.swift @@ -12,7 +12,7 @@ public import LanguageServerProtocol -fileprivate let requestTypes: [_RequestType.Type] = [ +private let requestTypes: [_RequestType.Type] = [ BuildShutdownRequest.self, BuildTargetPrepareRequest.self, BuildTargetSourcesRequest.self, @@ -24,7 +24,7 @@ fileprivate let requestTypes: [_RequestType.Type] = [ WorkspaceWaitForBuildSystemUpdatesRequest.self, ] -fileprivate let notificationTypes: [NotificationType.Type] = [ +private let notificationTypes: [NotificationType.Type] = [ CancelRequestNotification.self, FileOptionsChangedNotification.self, OnBuildExitNotification.self, diff --git a/Sources/CompletionScoring/Semantics/Components/PopularityTable.swift b/Sources/CompletionScoring/Semantics/Components/PopularityTable.swift index 60e94198f..ff4533824 100644 --- a/Sources/CompletionScoring/Semantics/Components/PopularityTable.swift +++ b/Sources/CompletionScoring/Semantics/Components/PopularityTable.swift @@ -138,7 +138,7 @@ package struct PopularityTable { } } -extension Dictionary { +extension [String: Popularity] { fileprivate mutating func record(scoreComponent: Double, for key: String) { let leastPopular = Popularity(scoreComponent: -Double.infinity) if self[key, default: leastPopular].scoreComponent < scoreComponent { diff --git a/Sources/CompletionScoring/Semantics/SemanticClassification.swift b/Sources/CompletionScoring/Semantics/SemanticClassification.swift index c4f13e9ec..5656717d3 100644 --- a/Sources/CompletionScoring/Semantics/SemanticClassification.swift +++ b/Sources/CompletionScoring/Semantics/SemanticClassification.swift @@ -155,7 +155,7 @@ extension SemanticClassification { } /// Used for debugging. -fileprivate protocol CompletionScoreComponent { +private protocol CompletionScoreComponent { var name: String { get } var instance: String { get } diff --git a/Sources/CompletionScoring/Text/InfluencingIdentifiers.swift b/Sources/CompletionScoring/Text/InfluencingIdentifiers.swift index ae43225ea..6e3098c26 100644 --- a/Sources/CompletionScoring/Text/InfluencingIdentifiers.swift +++ b/Sources/CompletionScoring/Text/InfluencingIdentifiers.swift @@ -12,7 +12,7 @@ import Foundation -fileprivate typealias UTF8Bytes = Pattern.UTF8Bytes +private typealias UTF8Bytes = Pattern.UTF8Bytes package struct InfluencingIdentifiers: Sendable { // `nonisolated(unsafe)` is fine because the underlying buffer is not modified until `deallocate` is called and the @@ -91,9 +91,7 @@ package struct InfluencingIdentifiers: Sendable { // TODO: We could turn this loop inside out to walk the candidate tokens first, and skip the ones that are shorter // than the shortest token, or keep bit for each length we have, and skip almost all of them. let matchedTokenCount = identifier.tokens.countOf { token in - if (RejectionFilter.match(pattern: token.rejectionFilter, candidate: candidate.rejectionFilter) - == .maybe) - { + if RejectionFilter.match(pattern: token.rejectionFilter, candidate: candidate.rejectionFilter) == .maybe { let candidateTokenization = candidateTokenization.lazyInitialize { Pattern.Tokenization.allocate( mixedcaseBytes: candidate.bytes, diff --git a/Sources/CompletionScoring/Text/MatchCollator.swift b/Sources/CompletionScoring/Text/MatchCollator.swift index 29c395b2e..1df396a0b 100644 --- a/Sources/CompletionScoring/Text/MatchCollator.swift +++ b/Sources/CompletionScoring/Text/MatchCollator.swift @@ -281,7 +281,7 @@ package struct MatchCollator { return definitiveGroupScoreComparison // Only compare `individualScore` within the same group, or among items that have no group. // Otherwise when the group score ties, we would interleave the members of the tying groups. - } else if (lhs.denseGroupID == rhs.denseGroupID), + } else if lhs.denseGroupID == rhs.denseGroupID, let definitiveIndividualScoreComparison = lhs.individualScore.value >? rhs.individualScore.value { return definitiveIndividualScoreComparison diff --git a/Sources/CompletionScoring/Text/Pattern.swift b/Sources/CompletionScoring/Text/Pattern.swift index 016661e81..65016889e 100644 --- a/Sources/CompletionScoring/Text/Pattern.swift +++ b/Sources/CompletionScoring/Text/Pattern.swift @@ -304,7 +304,7 @@ package final class Pattern: Sendable { // Allow skipping single character delemiters || ((token.length == 1) && candidateLowercaseBytes[cidx].isDelimiter) - if (tcidx > 0) { + if tcidx > 0 { candidate.matchedRanges.append(initialCidx.. Bool { - var cidx = startOffset, pidx = 0 + var cidx = startOffset + var pidx = 0 var currentlyMatching = false while (cidx < candidateBytes.count) && (pidx < patternBytes.count) { if candidateBytes[cidx] == patternBytes[pidx] { @@ -526,7 +527,7 @@ package final class Pattern: Sendable { patternCharactersRemaining -= coveredCharacters remainingCharacters -= coveredCharacters position += coveredCharacters - } while (remainingCharacters > 0) + } while remainingCharacters > 0 if (range.length > 1) || matchedTokenPrefix { score += pow(Double(range.length), 1.5) } @@ -538,7 +539,7 @@ package final class Pattern: Sendable { score *= 0.75 } - if (matchStyle == .acronym) { + if matchStyle == .acronym { badShortMatches = 0 falseStarts = 0 } diff --git a/Sources/CompletionScoring/Utilities/SwiftExtensions.swift b/Sources/CompletionScoring/Utilities/SwiftExtensions.swift index 42eeb8cf4..2d79bc114 100644 --- a/Sources/CompletionScoring/Utilities/SwiftExtensions.swift +++ b/Sources/CompletionScoring/Utilities/SwiftExtensions.swift @@ -338,7 +338,7 @@ extension Array { package func unsafeSlicedConcurrentMap( writer: @Sendable (ArraySlice, _ destination: UnsafeMutablePointer) -> Void ) -> [T] where Self: Sendable { - return Array(unsafeUninitializedCapacity: count) { buffer, initializedCount in + return [T](unsafeUninitializedCapacity: count) { buffer, initializedCount in if let bufferBase = buffer.baseAddress { // `nonisolated(unsafe)` is fine because every concurrent iteration accesses a disjunct slice of `buffer`. nonisolated(unsafe) let bufferBase = bufferBase @@ -384,7 +384,7 @@ extension Dictionary { } func mapKeys(overwritingDuplicates: Affirmative, _ map: (Key) -> K) -> [K: Value] { - var result = Dictionary(capacity: count) + var result = [K: Value](capacity: count) for (key, value) in self { result[map(key)] = value } diff --git a/Sources/Diagnose/CommandLineArgumentsReducer.swift b/Sources/Diagnose/CommandLineArgumentsReducer.swift index 7b4b2079d..ecea363b9 100644 --- a/Sources/Diagnose/CommandLineArgumentsReducer.swift +++ b/Sources/Diagnose/CommandLineArgumentsReducer.swift @@ -31,7 +31,7 @@ extension RequestInfo { // MARK: - FileProducer /// Reduces the compiler arguments needed to reproduce a sourcekitd crash. -fileprivate class CommandLineArgumentReducer { +private class CommandLineArgumentReducer { /// The executor that is used to run a sourcekitd request and check whether it /// still crashes. private let sourcekitdExecutor: SourceKitRequestExecutor diff --git a/Sources/Diagnose/DiagnoseCommand.swift b/Sources/Diagnose/DiagnoseCommand.swift index 232c516c6..32c1e85f8 100644 --- a/Sources/Diagnose/DiagnoseCommand.swift +++ b/Sources/Diagnose/DiagnoseCommand.swift @@ -36,7 +36,7 @@ private var progressBar: PercentProgressAnimation? = nil private var lastProgress: (Int, String)? = nil /// A component of the diagnostic bundle that's collected in independent stages. -fileprivate enum BundleComponent: String, CaseIterable, ExpressibleByArgument { +private enum BundleComponent: String, CaseIterable, ExpressibleByArgument { case crashReports = "crash-reports" case logs = "logs" case swiftVersions = "swift-versions" @@ -472,7 +472,7 @@ package struct DiagnoseCommand: AsyncParsableCommand { } /// Describes the state that the diagnose command is in. This is used to compute a progress bar. -fileprivate enum DiagnoseProgressState: Comparable { +private enum DiagnoseProgressState: Comparable { case collectingCrashReports case collectingLogMessages(progress: Double) case collectingSwiftVersions(progress: Double) @@ -513,8 +513,8 @@ fileprivate enum DiagnoseProgressState: Comparable { var elapsedEstimatedDuration = allFinalStates.filter { $0 < self }.reduce(0, { $0 + $1.estimatedDuration }) switch self { case .collectingCrashReports: break - case .collectingLogMessages(let progress), .collectingSwiftVersions(progress: let progress), - .reproducingSourcekitdCrash(progress: let progress), .reproducingSwiftFrontendCrash(progress: let progress): + case .collectingLogMessages(let progress), .collectingSwiftVersions(let progress), + .reproducingSourcekitdCrash(let progress), .reproducingSwiftFrontendCrash(let progress): elapsedEstimatedDuration += progress * self.estimatedDuration } return elapsedEstimatedDuration / estimatedTotalDuration diff --git a/Sources/Diagnose/SourceReducer.swift b/Sources/Diagnose/SourceReducer.swift index 017784dbc..6cdb250df 100644 --- a/Sources/Diagnose/SourceReducer.swift +++ b/Sources/Diagnose/SourceReducer.swift @@ -37,7 +37,7 @@ extension RequestInfo { /// The return value of a source reducer, indicating whether edits were made or if the reducer has finished reducing /// the source file. -fileprivate enum ReducerResult { +private enum ReducerResult { /// The reduction step produced edits that should be applied to the source file. case edits([SourceEdit]) @@ -55,7 +55,7 @@ fileprivate enum ReducerResult { /// The return value of `runReductionStep`, indicating whether applying the edits from a reducer reduced the issue, /// failed to reproduce the issue or if no changes were applied by the reducer. -fileprivate enum ReductionStepResult { +private enum ReductionStepResult { case reduced(RequestInfo) case didNotReproduce case noChange @@ -63,7 +63,7 @@ fileprivate enum ReductionStepResult { /// Reduces an input source file while continuing to reproduce the crash @MainActor -fileprivate class SourceReducer { +private class SourceReducer { /// The executor that is used to run a sourcekitd request and check whether it /// still crashes. private let sourcekitdExecutor: SourceKitRequestExecutor @@ -324,14 +324,14 @@ fileprivate class SourceReducer { // MARK: - Reduce functions /// See `SourceReducer.runReductionStep` -fileprivate protocol StatefulReducer { +private protocol StatefulReducer { func reduce(tree: SourceFileSyntax) -> ReducerResult } // MARK: Remove function bodies /// Tries removing the contents of function bodies one at a time. -fileprivate class RemoveFunctionBodies: StatefulReducer { +private class RemoveFunctionBodies: StatefulReducer { /// The function bodies that should not be removed. /// /// When we tried removing a function, it gets added to this list. @@ -391,7 +391,7 @@ fileprivate class RemoveFunctionBodies: StatefulReducer { /// /// If `simultaneousRemove` is set, it tries to remove that many adjacent top-level items at a time to quickly reduce /// the source file. -fileprivate class RemoveTopLevelItems: StatefulReducer { +private class RemoveTopLevelItems: StatefulReducer { /// The code block items that shouldn't be removed. /// /// See `ReplaceFunctionBodiesByFatalError.keepFunctionBodies`. @@ -454,7 +454,7 @@ fileprivate class RemoveTopLevelItems: StatefulReducer { // MARK: Remove members and code block items /// Tries removing `MemberBlockItemSyntax` and `CodeBlockItemSyntax` one at a time. -fileprivate class RemoveMembersAndCodeBlockItems: StatefulReducer { +private class RemoveMembersAndCodeBlockItems: StatefulReducer { /// The code block items / members that shouldn't be removed. /// /// See `ReplaceFunctionBodiesByFatalError.keepFunctionBodies`. @@ -512,7 +512,7 @@ fileprivate class RemoveMembersAndCodeBlockItems: StatefulReducer { } /// For any top-level items in the source file that occur multiple times, only keep the first occurrence. -fileprivate func mergeDuplicateTopLevelItems(in tree: SourceFileSyntax) -> ReducerResult { +private func mergeDuplicateTopLevelItems(in tree: SourceFileSyntax) -> ReducerResult { class DuplicateTopLevelItemMerger: SyntaxVisitor { var seenItems: Set = [] var edits: [SourceEdit] = [] @@ -539,7 +539,7 @@ fileprivate func mergeDuplicateTopLevelItems(in tree: SourceFileSyntax) -> Reduc } /// Removes all comments from the source file. -fileprivate func removeComments(from tree: SourceFileSyntax) -> ReducerResult { +private func removeComments(from tree: SourceFileSyntax) -> ReducerResult { class CommentRemover: SyntaxVisitor { var edits: [SourceEdit] = [] @@ -582,7 +582,7 @@ fileprivate extension TriviaPiece { // MARK: Inline first include -fileprivate class FirstImportFinder: SyntaxAnyVisitor { +private class FirstImportFinder: SyntaxAnyVisitor { var firstImport: ImportDeclSyntax? override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind { @@ -614,7 +614,7 @@ fileprivate class FirstImportFinder: SyntaxAnyVisitor { /// contain a target and SDK. This is useful when reducing a swift-frontend crash because sourcekitd requires driver /// arguments but the swift-frontend crash has frontend args. @MainActor -fileprivate func getSwiftInterface( +private func getSwiftInterface( _ moduleName: String, executor: SourceKitRequestExecutor, compilerArgs: [String], @@ -641,7 +641,7 @@ fileprivate func getSwiftInterface( let result: String switch try await executor.run(request: requestInfo) { - case .success(response: let response): + case .success(let response): result = response case .error where !areFallbackArgs: var fallbackArgs: [String] = [] @@ -688,7 +688,7 @@ fileprivate func getSwiftInterface( } @MainActor -fileprivate func inlineFirstImport( +private func inlineFirstImport( in tree: SourceFileSyntax, executor: SourceKitRequestExecutor, compilerArgs: [String] diff --git a/Sources/Diagnose/TraceFromSignpostsCommand.swift b/Sources/Diagnose/TraceFromSignpostsCommand.swift index 00dd22809..287d2bbd0 100644 --- a/Sources/Diagnose/TraceFromSignpostsCommand.swift +++ b/Sources/Diagnose/TraceFromSignpostsCommand.swift @@ -16,7 +16,7 @@ import RegexBuilder import SwiftExtensions /// Shared instance of the regex that is used to extract Signpost lines from `log stream --signpost`. -fileprivate struct LogParseRegex { +private struct LogParseRegex { @MainActor static let shared = LogParseRegex() let dateComponent = Reference(Substring.self) @@ -74,7 +74,7 @@ fileprivate struct LogParseRegex { } /// A signpost event extracted from a log. -fileprivate struct Signpost { +private struct Signpost { /// ID that identifies the signpost across the log. /// /// There might be multiple signposts with the same `signpostId` across multiple processes. @@ -126,7 +126,7 @@ fileprivate struct Signpost { /// A trace event in the *Trace Event Format* that can be opened using Perfetto. /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/mobilebasic -fileprivate struct TraceEvent: Codable { +private struct TraceEvent: Codable { enum EventType: String, Codable { case begin = "B" case end = "E" diff --git a/Sources/DocCDocumentation/DocCCatalogIndexManager.swift b/Sources/DocCDocumentation/DocCCatalogIndexManager.swift index 174d5a96c..66e428ed5 100644 --- a/Sources/DocCDocumentation/DocCCatalogIndexManager.swift +++ b/Sources/DocCDocumentation/DocCCatalogIndexManager.swift @@ -162,7 +162,7 @@ package struct DocCCatalogIndex: Sendable { } } -fileprivate enum WithSchemeError: LocalizedError { +private enum WithSchemeError: LocalizedError { case failedToRetrieveComponents(URL) case failedToEncode(URLComponents) diff --git a/Sources/DocCDocumentation/DocCServer.swift b/Sources/DocCDocumentation/DocCServer.swift index 3e54ca7f3..7e2e746d6 100644 --- a/Sources/DocCDocumentation/DocCServer.swift +++ b/Sources/DocCDocumentation/DocCServer.swift @@ -194,7 +194,7 @@ enum DocCServerError: LocalizedError { return "Received an unknown message type: '\(messageType)'." case .unexpectedlyNilPayload(let messageType): return "Received a message of type '\(messageType)' with a 'nil' payload." - case .internalError(underlyingError: let underlyingError): + case .internalError(let underlyingError): return underlyingError.errorDescription } } diff --git a/Sources/DocCDocumentation/DocCSymbolInformation.swift b/Sources/DocCDocumentation/DocCSymbolInformation.swift index 1a7a42112..dc2a7fb95 100644 --- a/Sources/DocCDocumentation/DocCSymbolInformation.swift +++ b/Sources/DocCDocumentation/DocCSymbolInformation.swift @@ -47,7 +47,7 @@ package struct DocCSymbolInformation { } } -fileprivate typealias KindIdentifier = SymbolGraph.Symbol.KindIdentifier +private typealias KindIdentifier = SymbolGraph.Symbol.KindIdentifier extension LinkCompletionTools.SymbolInformation { init(fromModuleName moduleName: String) { diff --git a/Sources/LanguageServerProtocol/CustomCodable.swift b/Sources/LanguageServerProtocol/CustomCodable.swift index 8a848594e..8713f4d58 100644 --- a/Sources/LanguageServerProtocol/CustomCodable.swift +++ b/Sources/LanguageServerProtocol/CustomCodable.swift @@ -93,16 +93,16 @@ extension Optional: CustomCodableWrapper where Wrapped: CustomCodableWrapper { extension KeyedDecodingContainer { public func decode( - _ type: CustomCodable>.Type, + _ type: CustomCodable.Type, forKey key: Key - ) throws -> CustomCodable> { - CustomCodable>(wrappedValue: try decodeIfPresent(T.self, forKey: key)?.wrappedValue) + ) throws -> CustomCodable { + CustomCodable(wrappedValue: try decodeIfPresent(T.self, forKey: key)?.wrappedValue) } } extension KeyedEncodingContainer { public mutating func encode( - _ value: CustomCodable>, + _ value: CustomCodable, forKey key: Key ) throws { try encodeIfPresent( diff --git a/Sources/LanguageServerProtocol/Requests/HoverRequest.swift b/Sources/LanguageServerProtocol/Requests/HoverRequest.swift index 4f829199c..87c1d407c 100644 --- a/Sources/LanguageServerProtocol/Requests/HoverRequest.swift +++ b/Sources/LanguageServerProtocol/Requests/HoverRequest.swift @@ -87,9 +87,9 @@ extension MarkedString: Codable, Sendable { public func encode(to encoder: Encoder) throws { switch self { - case .markdown(value: let value): + case .markdown(let value): try value.encode(to: encoder) - case .codeBlock(language: let language, value: let value): + case .codeBlock(let language, let value): try MarkdownCodeBlock(language: language, value: value).encode(to: encoder) } } diff --git a/Sources/LanguageServerProtocol/Requests/SignatureHelpRequest.swift b/Sources/LanguageServerProtocol/Requests/SignatureHelpRequest.swift index 4da902815..5abd1e87a 100644 --- a/Sources/LanguageServerProtocol/Requests/SignatureHelpRequest.swift +++ b/Sources/LanguageServerProtocol/Requests/SignatureHelpRequest.swift @@ -167,7 +167,7 @@ public struct ParameterInformation: Codable, Hashable, Sendable { public init(from decoder: Decoder) throws { if let string = try? String(from: decoder) { self = .string(string) - } else if let offsets = try? Array(from: decoder), offsets.count == 2 { + } else if let offsets = try? [Int](from: decoder), offsets.count == 2 { self = .offsets(start: offsets[0], end: offsets[1]) } else { let context = DecodingError.Context( @@ -182,7 +182,7 @@ public struct ParameterInformation: Codable, Hashable, Sendable { switch self { case .string(let string): try string.encode(to: encoder) - case .offsets(start: let start, end: let end): + case .offsets(let start, let end): try [start, end].encode(to: encoder) } } diff --git a/Sources/LanguageServerProtocolExtensions/WorkDoneProgressManager.swift b/Sources/LanguageServerProtocolExtensions/WorkDoneProgressManager.swift index 1fd046fd0..07d35e864 100644 --- a/Sources/LanguageServerProtocolExtensions/WorkDoneProgressManager.swift +++ b/Sources/LanguageServerProtocolExtensions/WorkDoneProgressManager.swift @@ -95,7 +95,7 @@ package actor WorkDoneProgressManager { } await waitUntilClientInitialized() switch statusToSend { - case .inProgress(message: let message, percentage: let percentage): + case .inProgress(let message, let percentage): if let token { connectionToClient.send( WorkDoneProgress( diff --git a/Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift b/Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift index 0c1853511..c2c1c6965 100644 --- a/Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift +++ b/Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift @@ -519,17 +519,17 @@ public final class JSONRPCConnection: Connection { switch message { case .notification(let notification): notification._handle(self.receiveHandler!) - case .request(let request, id: let id): + case .request(let request, let id): request._handle(self.receiveHandler!, id: id) { (response, id) in self.sendReply(response, id: id) } - case .response(let response, id: let id): + case .response(let response, let id): guard let outstanding = outstandingRequests.removeValue(forKey: id) else { logger.error("No outstanding requests for response ID \(id, privacy: .public)") return } outstanding.replyHandler(.success(response)) - case .errorResponse(let error, id: let id): + case .errorResponse(let error, let id): guard let id = id else { logger.error("Received error response for unknown request: \(error.forLogging)") return diff --git a/Sources/SKLogging/CustomLogStringConvertible.swift b/Sources/SKLogging/CustomLogStringConvertible.swift index 59f24b479..352fe1ca5 100644 --- a/Sources/SKLogging/CustomLogStringConvertible.swift +++ b/Sources/SKLogging/CustomLogStringConvertible.swift @@ -77,7 +77,7 @@ extension String { } private struct OptionalWrapper: CustomLogStringConvertible where Wrapped: CustomLogStringConvertible { - let optional: Optional + let optional: Wrapped? package var description: String { return optional?.description ?? "" diff --git a/Sources/SKLogging/NonDarwinLogging.swift b/Sources/SKLogging/NonDarwinLogging.swift index f973d660c..5b57f350f 100644 --- a/Sources/SKLogging/NonDarwinLogging.swift +++ b/Sources/SKLogging/NonDarwinLogging.swift @@ -237,7 +237,7 @@ package struct NonDarwinLogInterpolation: StringInterpolationProtocol, Sendable switch piece { case .string(let string): result += string - case .possiblyRedacted(description: let description, redactedDescription: let redacted, privacy: let privacy): + case .possiblyRedacted(let description, redactedDescription: let redacted, let privacy): if privacy > logPrivacyLevel { result += redacted() } else { diff --git a/Sources/SKLogging/SetGlobalLogFileHandler.swift b/Sources/SKLogging/SetGlobalLogFileHandler.swift index 0a15a02a3..9ea639c12 100644 --- a/Sources/SKLogging/SetGlobalLogFileHandler.swift +++ b/Sources/SKLogging/SetGlobalLogFileHandler.swift @@ -25,7 +25,7 @@ import WinSDK #endif #if !canImport(os) || SOURCEKIT_LSP_FORCE_NON_DARWIN_LOGGER -fileprivate struct FailedToCreateFileError: Error, CustomStringConvertible { +private struct FailedToCreateFileError: Error, CustomStringConvertible { let logFile: URL var description: String { @@ -37,13 +37,13 @@ fileprivate struct FailedToCreateFileError: Error, CustomStringConvertible { /// /// See comment on `logFileHandle`. @LogHandlerActor -fileprivate var logRotateIndex = 0 +private var logRotateIndex = 0 /// The file handle to the current log file. When the file managed by this handle reaches its maximum size, we increment /// the `logRotateIndex` by 1 and set the `logFileHandle` to `nil`. This causes a new log file handle with index /// `logRotateIndex % logRotateCount` to be created on the next log call. @LogHandlerActor -fileprivate var logFileHandle: FileHandle? +private var logFileHandle: FileHandle? @LogHandlerActor func getOrCreateLogFileHandle(logDirectory: URL, logRotateCount: Int) -> FileHandle { diff --git a/Sources/SKOptions/SourceKitLSPOptions.swift b/Sources/SKOptions/SourceKitLSPOptions.swift index 8ca3cb768..dbf07658a 100644 --- a/Sources/SKOptions/SourceKitLSPOptions.swift +++ b/Sources/SKOptions/SourceKitLSPOptions.swift @@ -322,7 +322,7 @@ public struct SourceKitLSPOptions: Sendable, Codable, Equatable { public var buildSettingsTimeout: Int? public var buildSettingsTimeoutOrDefault: Duration { // The default timeout of 500ms was chosen arbitrarily without any measurements. - get { .milliseconds(buildSettingsTimeout ?? 500) } + .milliseconds(buildSettingsTimeout ?? 500) } /// Extra command line arguments passed to `clangd` when launching it. diff --git a/Sources/SKTestSupport/CompletionItem+clearingUnstableValues.swift b/Sources/SKTestSupport/CompletionItem+clearingUnstableValues.swift index 3fa2e5961..f28a19e71 100644 --- a/Sources/SKTestSupport/CompletionItem+clearingUnstableValues.swift +++ b/Sources/SKTestSupport/CompletionItem+clearingUnstableValues.swift @@ -12,7 +12,7 @@ package import LanguageServerProtocol -extension Array { +extension [CompletionItem] { /// Remove `sortText` and `data` from all completion items as these are not stable across runs. Instead, sort items /// by `sortText` to ensure we test them in the order that an editor would display them in. package var clearingUnstableValues: [CompletionItem] { diff --git a/Sources/SKTestSupport/ExternalBuildServerTestProject.swift b/Sources/SKTestSupport/ExternalBuildServerTestProject.swift index 9e4e5592e..ae0dd35fb 100644 --- a/Sources/SKTestSupport/ExternalBuildServerTestProject.swift +++ b/Sources/SKTestSupport/ExternalBuildServerTestProject.swift @@ -15,7 +15,7 @@ package import SKOptions import SwiftExtensions import XCTest -fileprivate let sdkArgs = +private let sdkArgs = if let defaultSDKPath { """ "-sdk", r"\(defaultSDKPath)", diff --git a/Sources/SKTestSupport/LocationMarkers.swift b/Sources/SKTestSupport/LocationMarkers.swift index b6ee3f77d..16b0db0ed 100644 --- a/Sources/SKTestSupport/LocationMarkers.swift +++ b/Sources/SKTestSupport/LocationMarkers.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// /// Finds all marked ranges in the given text, see `Marker`. -fileprivate func findMarkedRanges(text: String) -> [Marker] { +private func findMarkedRanges(text: String) -> [Marker] { var markers = [Marker]() while let marker = nextMarkedRange(text: text, from: markers.last?.range.upperBound ?? text.startIndex) { markers.append(marker) @@ -29,7 +29,7 @@ extension Character { } } -fileprivate func nextMarkedRange(text: String, from: String.Index) -> Marker? { +private func nextMarkedRange(text: String, from: String.Index) -> Marker? { guard let start = text[from...].firstIndex(where: { $0.isMarkerEmoji }) else { return nil } @@ -41,7 +41,7 @@ fileprivate func nextMarkedRange(text: String, from: String.Index) -> Marker? { return Marker(name: name, range: markerRange) } -fileprivate struct Marker { +private struct Marker { /// The name of the marker. let name: Substring /// The range of the marker. diff --git a/Sources/SKTestSupport/TestSourceKitLSPClient.swift b/Sources/SKTestSupport/TestSourceKitLSPClient.swift index 5a062fe8e..42b4bcebb 100644 --- a/Sources/SKTestSupport/TestSourceKitLSPClient.swift +++ b/Sources/SKTestSupport/TestSourceKitLSPClient.swift @@ -43,7 +43,7 @@ extension SourceKitLSPOptions { } } -fileprivate struct NotificationTimeoutError: Error, CustomStringConvertible { +private struct NotificationTimeoutError: Error, CustomStringConvertible { var description: String = "Failed to receive next notification within timeout" } diff --git a/Sources/SemanticIndex/SemanticIndexManager.swift b/Sources/SemanticIndex/SemanticIndexManager.swift index 4823b1e4f..cad195edf 100644 --- a/Sources/SemanticIndex/SemanticIndexManager.swift +++ b/Sources/SemanticIndex/SemanticIndexManager.swift @@ -133,7 +133,7 @@ package enum IndexProgressStatus: Sendable, Equatable { } /// See `SemanticIndexManager.inProgressPrepareForEditorTask`. -fileprivate struct InProgressPrepareForEditorTask { +private struct InProgressPrepareForEditorTask { /// A unique ID that identifies the preparation task and is used to set /// `SemanticIndexManager.inProgressPrepareForEditorTask` to `nil` when the current in progress task finishes. let id: UUID @@ -146,7 +146,7 @@ fileprivate struct InProgressPrepareForEditorTask { } /// The reason why a target is being prepared. This is used to determine the `IndexProgressStatus`. -fileprivate enum TargetPreparationPurpose: Comparable { +private enum TargetPreparationPurpose: Comparable { /// We are preparing the target so we can index files in it. case forIndexing @@ -155,7 +155,7 @@ fileprivate enum TargetPreparationPurpose: Comparable { } /// An entry in `SemanticIndexManager.inProgressPreparationTasks`. -fileprivate struct InProgressPreparationTask { +private struct InProgressPreparationTask { let task: OpaqueQueuedIndexTask let purpose: TargetPreparationPurpose } @@ -239,7 +239,7 @@ package final actor SemanticIndexManager { switch inProgress.state { case .creatingIndexTask, .waitingForPreparation, .preparing: return IndexTaskStatus.scheduled - case .updatingIndexStore(updateIndexStoreTask: let updateIndexStoreTask, indexTask: _): + case .updatingIndexStore(let updateIndexStoreTask, indexTask: _): return updateIndexStoreTask.isExecuting ? IndexTaskStatus.executing : IndexTaskStatus.scheduled } } @@ -340,9 +340,9 @@ package final actor SemanticIndexManager { switch inProgress.state { case .creatingIndexTask: break - case .waitingForPreparation(preparationTaskID: _, indexTask: let indexTask), - .preparing(preparationTaskID: _, indexTask: let indexTask), - .updatingIndexStore(updateIndexStoreTask: _, indexTask: let indexTask): + case .waitingForPreparation(preparationTaskID: _, let indexTask), + .preparing(preparationTaskID: _, let indexTask), + .updatingIndexStore(updateIndexStoreTask: _, let indexTask): await indexTask.value } } diff --git a/Sources/SemanticIndex/TaskScheduler.swift b/Sources/SemanticIndex/TaskScheduler.swift index f728ba67b..56c2632b4 100644 --- a/Sources/SemanticIndex/TaskScheduler.swift +++ b/Sources/SemanticIndex/TaskScheduler.swift @@ -678,7 +678,7 @@ fileprivate extension Collection { } /// Version of the `withTaskPriorityChangedHandler` where the body doesn't throw. -fileprivate func withTaskPriorityChangedHandler( +private func withTaskPriorityChangedHandler( initialPriority: TaskPriority = Task.currentPriority, pollingInterval: Duration = .seconds(0.1), @_inheritActorContext operation: @escaping @Sendable () async -> Void, diff --git a/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift b/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift index e96694def..1e1240f4f 100644 --- a/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift +++ b/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift @@ -45,7 +45,7 @@ package enum FileToIndex: CustomLogStringConvertible, Hashable { package var sourceFile: DocumentURI { switch self { case .indexableFile(let uri): return uri - case .headerFile(header: let header, mainFile: _): return header + case .headerFile(let header, mainFile: _): return header } } @@ -56,7 +56,7 @@ package enum FileToIndex: CustomLogStringConvertible, Hashable { var mainFile: DocumentURI { switch self { case .indexableFile(let uri): return uri - case .headerFile(header: _, mainFile: let mainFile): return mainFile + case .headerFile(header: _, let mainFile): return mainFile } } @@ -64,7 +64,7 @@ package enum FileToIndex: CustomLogStringConvertible, Hashable { switch self { case .indexableFile(let uri): return uri.description - case .headerFile(header: let header, mainFile: let mainFile): + case .headerFile(let header, let mainFile): return "\(header.description) using main file \(mainFile.description)" } } @@ -73,7 +73,7 @@ package enum FileToIndex: CustomLogStringConvertible, Hashable { switch self { case .indexableFile(let uri): return uri.redactedDescription - case .headerFile(header: let header, mainFile: let mainFile): + case .headerFile(let header, let mainFile): return "\(header.redactedDescription) using main file \(mainFile.redactedDescription)" } } @@ -458,7 +458,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { switch exitStatus { case .terminated(code: 0): break - case .terminated(code: let code): + case .terminated(let code): // This most likely happens if there are compilation errors in the source file. This is nothing to worry about. let stdout = (try? String(bytes: result.output.get(), encoding: .utf8)) ?? "" let stderr = (try? String(bytes: result.stderrOutput.get(), encoding: .utf8)) ?? "" @@ -473,7 +473,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { """ ) BuildSettingsLogger.log(level: .debug, settings: buildSettings, for: indexFile) - case .signalled(signal: let signal): + case .signalled(let signal): if !Task.isCancelled { // The indexing job finished with a signal. Could be because the compiler crashed. // Ignore signal exit codes if this task has been cancelled because the compiler exits with SIGINT if it gets @@ -481,7 +481,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { logger.error("Updating index store for \(indexFile.forLogging) signaled \(signal)") BuildSettingsLogger.log(level: .error, settings: buildSettings, for: indexFile) } - case .abnormal(exception: let exception): + case .abnormal(let exception): if !Task.isCancelled { logger.error("Updating index store for \(indexFile.forLogging) exited abnormally \(exception)") BuildSettingsLogger.log(level: .error, settings: buildSettings, for: indexFile) diff --git a/Sources/SourceKitD/SKDRequestArray.swift b/Sources/SourceKitD/SKDRequestArray.swift index 3e1025591..515bc1fdc 100644 --- a/Sources/SourceKitD/SKDRequestArray.swift +++ b/Sources/SourceKitD/SKDRequestArray.swift @@ -60,11 +60,11 @@ package final class SKDRequestArray: Sendable { sourcekitd.api.request_array_set_value(array, -1, newValue.dict) case let newValue as SKDRequestArray: sourcekitd.api.request_array_set_value(array, -1, newValue.array) - case let newValue as Array: + case let newValue as [SKDRequestValue]: self.append(sourcekitd.array(newValue)) - case let newValue as Dictionary: + case let newValue as [sourcekitd_api_uid_t: SKDRequestValue]: self.append(sourcekitd.dictionary(newValue)) - case let newValue as Optional: + case let newValue as SKDRequestValue?: if let newValue { self.append(newValue) } diff --git a/Sources/SourceKitD/SKDRequestDictionary.swift b/Sources/SourceKitD/SKDRequestDictionary.swift index 29468b79d..6ae563766 100644 --- a/Sources/SourceKitD/SKDRequestDictionary.swift +++ b/Sources/SourceKitD/SKDRequestDictionary.swift @@ -38,8 +38,8 @@ extension Int: SKDRequestValue {} extension sourcekitd_api_uid_t: SKDRequestValue {} extension SKDRequestDictionary: SKDRequestValue {} extension SKDRequestArray: SKDRequestValue {} -extension Array: SKDRequestValue {} -extension Dictionary: SKDRequestValue {} +extension [SKDRequestValue]: SKDRequestValue {} +extension [sourcekitd_api_uid_t: SKDRequestValue]: SKDRequestValue {} extension Optional: SKDRequestValue where Wrapped: SKDRequestValue {} extension SourceKitD { @@ -78,11 +78,11 @@ package final class SKDRequestDictionary: Sendable { sourcekitd.api.request_dictionary_set_value(dict, key, newValue.dict) case let newValue as SKDRequestArray: sourcekitd.api.request_dictionary_set_value(dict, key, newValue.array) - case let newValue as Array: + case let newValue as [SKDRequestValue]: self.set(key, to: sourcekitd.array(newValue)) - case let newValue as Dictionary: + case let newValue as [sourcekitd_api_uid_t: SKDRequestValue]: self.set(key, to: sourcekitd.dictionary(newValue)) - case let newValue as Optional: + case let newValue as SKDRequestValue?: if let newValue { self.set(key, to: newValue) } diff --git a/Sources/SourceKitD/SourceKitD.swift b/Sources/SourceKitD/SourceKitD.swift index 7ac6a80f6..8765d8ce6 100644 --- a/Sources/SourceKitD/SourceKitD.swift +++ b/Sources/SourceKitD/SourceKitD.swift @@ -22,7 +22,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(compute: () -> WrappedValue) -> WrappedValue where T == Optional { + func computeIfNil(compute: () -> WrappedValue) -> WrappedValue where T == WrappedValue? { return withLock { value in if let value { return value @@ -35,7 +35,7 @@ fileprivate extension ThreadSafeBox { } #if canImport(Darwin) -fileprivate func setenv(name: String, value: String, override: Bool) throws { +private func setenv(name: String, value: String, override: Bool) throws { struct FailedToSetEnvError: Error { let errorCode: Int32 } @@ -50,7 +50,7 @@ fileprivate func setenv(name: String, value: String, override: Bool) throws { } #endif -fileprivate struct SourceKitDRequestHandle: Sendable { +private struct SourceKitDRequestHandle: Sendable { /// `nonisolated(unsafe)` is fine because we just use the handle as an opaque value. nonisolated(unsafe) let handle: sourcekitd_api_request_handle_t } diff --git a/Sources/SourceKitD/SourceKitDRegistry.swift b/Sources/SourceKitD/SourceKitDRegistry.swift index 420fdc2f8..f67e3a437 100644 --- a/Sources/SourceKitD/SourceKitDRegistry.swift +++ b/Sources/SourceKitD/SourceKitDRegistry.swift @@ -86,6 +86,6 @@ extension SourceKitDRegistry { package static let shared: SourceKitDRegistry = SourceKitDRegistry() } -fileprivate struct WeakSourceKitD { +private struct WeakSourceKitD { weak var value: SourceKitDType? } diff --git a/Sources/SourceKitLSP/IndexProgressManager.swift b/Sources/SourceKitLSP/IndexProgressManager.swift index f7ef3a00e..bc09ea8c7 100644 --- a/Sources/SourceKitLSP/IndexProgressManager.swift +++ b/Sources/SourceKitLSP/IndexProgressManager.swift @@ -96,7 +96,7 @@ actor IndexProgressManager { case .schedulingIndexing: message = "Scheduling tasks" percentage = 0 - case .indexing(preparationTasks: let preparationTasks, indexTasks: let indexTasks): + case .indexing(let preparationTasks, let indexTasks): // We can get into a situation where queuedIndexTasks < indexTasks.count if we haven't processed all // `indexTasksWereScheduled` calls yet but the semantic index managers already track them in their in-progress tasks. // Clip the finished tasks to 0 because showing a negative number there looks stupid. diff --git a/Sources/SourceKitLSP/Rename.swift b/Sources/SourceKitLSP/Rename.swift index f566b277a..7dcdc93a9 100644 --- a/Sources/SourceKitLSP/Rename.swift +++ b/Sources/SourceKitLSP/Rename.swift @@ -29,7 +29,7 @@ import SwiftSyntax /// - `foo(a:b:)` /// - `foo(_:b:)` /// - `foo` if no argument labels are specified, eg. for a variable. -fileprivate struct CompoundDeclName { +private struct CompoundDeclName { /// The parameter of a compound decl name, which can either be the parameter's name or `_` to indicate that the /// parameter is unnamed. enum Parameter: Equatable { @@ -78,7 +78,7 @@ fileprivate struct CompoundDeclName { } /// The kind of range that a `SyntacticRenamePiece` can be. -fileprivate enum SyntacticRenamePieceKind { +private enum SyntacticRenamePieceKind { /// The base name of a function or the name of a variable, which can be renamed. /// /// ### Examples @@ -164,7 +164,7 @@ fileprivate enum SyntacticRenamePieceKind { /// - The base name `foo` /// - The parameter name `x` /// - The call argument colon `: `. -fileprivate struct SyntacticRenamePiece { +private struct SyntacticRenamePiece { /// The range that represents this piece of the name let range: Range @@ -203,7 +203,7 @@ fileprivate struct SyntacticRenamePiece { } /// The context in which the location to be renamed occurred. -fileprivate enum SyntacticRenameNameContext { +private enum SyntacticRenameNameContext { /// No syntactic rename ranges for the rename location could be found. case unmatched @@ -242,7 +242,7 @@ fileprivate enum SyntacticRenameNameContext { /// A set of ranges that, combined, represent which edits need to be made to rename a possibly compound name. /// /// See `SyntacticRenamePiece` for more details. -fileprivate struct SyntacticRenameName { +private struct SyntacticRenameName { let pieces: [SyntacticRenamePiece] let category: SyntacticRenameNameContext @@ -483,7 +483,7 @@ package struct CrossLanguageName: Sendable { // MARK: - SourceKitLSPServer /// The kinds of symbol occurrence roles that should be renamed. -fileprivate let renameRoles: SymbolRole = [.declaration, .definition, .reference] +private let renameRoles: SymbolRole = [.declaration, .definition, .reference] extension SourceKitLSPServer { /// Returns a `DocumentSnapshot`, a position and the corresponding language service that references diff --git a/Sources/SourceKitLSP/SourceKitLSPServer.swift b/Sources/SourceKitLSP/SourceKitLSPServer.swift index a0a40c371..7e2900b0d 100644 --- a/Sources/SourceKitLSP/SourceKitLSPServer.swift +++ b/Sources/SourceKitLSP/SourceKitLSPServer.swift @@ -2653,7 +2653,7 @@ fileprivate extension SymbolOccurrence { /// Simple struct for pending notifications/requests, including a cancellation handler. /// For convenience the notifications/request handlers are type erased via wrapping. -fileprivate struct NotificationRequestOperation { +private struct NotificationRequestOperation { let operation: () async -> Void let cancellationHandler: (() -> Void)? } @@ -2662,7 +2662,7 @@ fileprivate struct NotificationRequestOperation { /// on build server operations such as fetching build settings. /// /// Note: This is not thread safe. Must be called from the `SourceKitLSPServer.queue`. -fileprivate struct DocumentNotificationRequestQueue { +private struct DocumentNotificationRequestQueue { fileprivate var queue = [NotificationRequestOperation]() /// Add an operation to the end of the queue. @@ -2683,7 +2683,7 @@ fileprivate struct DocumentNotificationRequestQueue { } /// Returns the USRs of the subtypes of `usrs` as well as their subtypes and extensions, transitively. -fileprivate func transitiveSubtypeClosure(ofUsrs usrs: [String], index: CheckedIndex) -> [String] { +private func transitiveSubtypeClosure(ofUsrs usrs: [String], index: CheckedIndex) -> [String] { var result: [String] = [] for usr in usrs { result.append(usr) diff --git a/Sources/SourceKitLSP/Swift/AdjustPositionToStartOfIdentifier.swift b/Sources/SourceKitLSP/Swift/AdjustPositionToStartOfIdentifier.swift index 11397a781..7acf20302 100644 --- a/Sources/SourceKitLSP/Swift/AdjustPositionToStartOfIdentifier.swift +++ b/Sources/SourceKitLSP/Swift/AdjustPositionToStartOfIdentifier.swift @@ -13,7 +13,7 @@ import LanguageServerProtocol import SwiftSyntax -fileprivate class StartOfIdentifierFinder: SyntaxAnyVisitor { +private class StartOfIdentifierFinder: SyntaxAnyVisitor { let requestedPosition: AbsolutePosition var resolvedPosition: AbsolutePosition? diff --git a/Sources/SourceKitLSP/Swift/CodeActions/ConvertJSONToCodableStruct.swift b/Sources/SourceKitLSP/Swift/CodeActions/ConvertJSONToCodableStruct.swift index adac120f9..fd29e35e7 100644 --- a/Sources/SourceKitLSP/Swift/CodeActions/ConvertJSONToCodableStruct.swift +++ b/Sources/SourceKitLSP/Swift/CodeActions/ConvertJSONToCodableStruct.swift @@ -208,7 +208,7 @@ extension ConvertJSONToCodableStruct: SyntaxRefactoringCodeActionProvider { /// A JSON object, which is has a set of fields, each of which has the given /// type. -fileprivate struct JSONObject { +private struct JSONObject { /// The fields of the JSON object. var fields: [String: JSONType] = [:] @@ -278,7 +278,7 @@ fileprivate struct JSONObject { } /// Describes the type of JSON data. -fileprivate enum JSONType { +private enum JSONType { /// String data case string diff --git a/Sources/SourceKitLSP/Swift/CodeCompletionSession.swift b/Sources/SourceKitLSP/Swift/CodeCompletionSession.swift index d558828b0..5e4f2e1da 100644 --- a/Sources/SourceKitLSP/Swift/CodeCompletionSession.swift +++ b/Sources/SourceKitLSP/Swift/CodeCompletionSession.swift @@ -655,7 +655,7 @@ extension CodeCompletionSession: CustomStringConvertible { } } -fileprivate class OutermostFunctionCallFinder: SyntaxAnyVisitor { +private class OutermostFunctionCallFinder: SyntaxAnyVisitor { /// Once a `FunctionCallExprSyntax` has been visited, that syntax node. var foundCall: FunctionCallExprSyntax? diff --git a/Sources/SourceKitLSP/Swift/Diagnostic.swift b/Sources/SourceKitLSP/Swift/Diagnostic.swift index 7c0f8b81b..ec98e1813 100644 --- a/Sources/SourceKitLSP/Swift/Diagnostic.swift +++ b/Sources/SourceKitLSP/Swift/Diagnostic.swift @@ -128,7 +128,7 @@ extension TextEdit { let replacementWithoutPlaceholders = rewriteSourceKitPlaceholders(in: replacement, clientSupportsSnippets: false) // If both the replacement without placeholders and the fixit are empty, no TextEdit should be created. - if (replacementWithoutPlaceholders.isEmpty && length == 0) { + if replacementWithoutPlaceholders.isEmpty && length == 0 { return nil } diff --git a/Sources/SourceKitLSP/Swift/DoccDocumentation.swift b/Sources/SourceKitLSP/Swift/DoccDocumentation.swift index be508d686..21857e919 100644 --- a/Sources/SourceKitLSP/Swift/DoccDocumentation.swift +++ b/Sources/SourceKitLSP/Swift/DoccDocumentation.swift @@ -128,7 +128,7 @@ extension SwiftLanguageService { } } -fileprivate struct DocumentableSymbol { +private struct DocumentableSymbol { let position: AbsolutePosition let documentationComments: [String] diff --git a/Sources/SourceKitLSP/Swift/DocumentFormatting.swift b/Sources/SourceKitLSP/Swift/DocumentFormatting.swift index f59af16e4..0a5d0e38d 100644 --- a/Sources/SourceKitLSP/Swift/DocumentFormatting.swift +++ b/Sources/SourceKitLSP/Swift/DocumentFormatting.swift @@ -96,9 +96,9 @@ private func swiftFormatConfiguration( extension CollectionDifference.Change { var offset: Int { switch self { - case .insert(offset: let offset, element: _, associatedWith: _): + case .insert(let offset, element: _, associatedWith: _): return offset - case .remove(offset: let offset, element: _, associatedWith: _): + case .remove(let offset, element: _, associatedWith: _): return offset } } @@ -110,10 +110,10 @@ private func edits(from original: DocumentSnapshot, to edited: String) -> [TextE let sequentialEdits = difference.map { change in switch change { - case .insert(offset: let offset, element: let element, associatedWith: _): + case .insert(let offset, let element, associatedWith: _): let absolutePosition = AbsolutePosition(utf8Offset: offset) return SourceEdit(range: absolutePosition.. { +extension [RefactoringEdit] { init?(_ dict: SKDResponseDictionary, _ snapshot: DocumentSnapshot, _ keys: sourcekitd_api_keys) { guard let categorizedEdits: SKDResponseArray = dict[keys.categorizedEdits] else { logger.fault("categorizedEdits doesn't exist in response dictionary") diff --git a/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift b/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift index dfc0438f4..9ed4dd21a 100644 --- a/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift +++ b/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift @@ -52,7 +52,7 @@ fileprivate extension Range { } /// Explicitly excluded `DocumentURI` schemes. -fileprivate let excludedDocumentURISchemes: [String] = [ +private let excludedDocumentURISchemes: [String] = [ "git", "hg", ] @@ -67,7 +67,7 @@ fileprivate let excludedDocumentURISchemes: [String] = [ /// the `-working-directory` argument is passed since it incorrectly applies it to the input /// argument but not the internal primary file, leading sourcekitd to believe that the input /// file is missing. -fileprivate func diagnosticsEnabled(for document: DocumentURI) -> Bool { +private func diagnosticsEnabled(for document: DocumentURI) -> Bool { guard let scheme = document.scheme else { return true } return !excludedDocumentURISchemes.contains(scheme) } diff --git a/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift b/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift index 44647886f..ebf20091b 100644 --- a/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift +++ b/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift @@ -17,7 +17,7 @@ import SKLogging import SwiftExtensions /// Task metadata for `SyntacticTestIndexer.indexingQueue` -fileprivate enum TaskMetadata: DependencyTracker, Equatable { +private enum TaskMetadata: DependencyTracker, Equatable { /// Determine the list of test files from the build server and scan them for tests. Only created when the /// `SyntacticTestIndex` is created case initialPopulation @@ -64,7 +64,7 @@ fileprivate enum TaskMetadata: DependencyTracker, Equatable { } /// Data from a syntactic scan of a source file for tests. -fileprivate struct IndexedTests { +private struct IndexedTests { /// The tests within the source file. let tests: [AnnotatedTestItem] @@ -78,7 +78,7 @@ fileprivate struct IndexedTests { /// Does not write the results to the index. /// /// The order of the returned tests is not defined. The results should be sorted before being returned to the editor. -fileprivate func testItems(in url: URL) async -> [AnnotatedTestItem] { +private func testItems(in url: URL) async -> [AnnotatedTestItem] { guard url.pathExtension == "swift" else { return [] } diff --git a/Sources/SourceKitLSP/TestDiscovery.swift b/Sources/SourceKitLSP/TestDiscovery.swift index 07a7731d4..37f7aedc6 100644 --- a/Sources/SourceKitLSP/TestDiscovery.swift +++ b/Sources/SourceKitLSP/TestDiscovery.swift @@ -414,7 +414,7 @@ extension AnnotatedTestItem { } } -fileprivate extension Array { +fileprivate extension [AnnotatedTestItem] { /// When the test scanners discover tests in extensions they are captured in their own parent `TestItem`, not the /// `TestItem` generated from the class/struct's definition. This is largely because of the syntatic nature of the /// test scanners as they are today, which only know about tests within the context of the current file. Extensions @@ -532,7 +532,7 @@ fileprivate extension Array { } } -fileprivate extension Array { +fileprivate extension [TestItem] { /// If multiple testItems share the same ID we add more context to make it unique. /// Two tests can share the same ID when two swift testing tests accept /// arguments of different types, i.e: diff --git a/Sources/SwiftExtensions/AsyncUtils.swift b/Sources/SwiftExtensions/AsyncUtils.swift index cc587e769..ccfc9f7c1 100644 --- a/Sources/SwiftExtensions/AsyncUtils.swift +++ b/Sources/SwiftExtensions/AsyncUtils.swift @@ -158,7 +158,7 @@ extension Collection where Element: Sendable { } return indexedResults } - return Array(unsafeUninitializedCapacity: indexedResults.count) { buffer, count in + return [TransformedElement](unsafeUninitializedCapacity: indexedResults.count) { buffer, count in for (index, transformedElement) in indexedResults { (buffer.baseAddress! + index).initialize(to: transformedElement) } diff --git a/Sources/SwiftSourceKitPlugin/ASTCompletion/ASTCompletionItem.swift b/Sources/SwiftSourceKitPlugin/ASTCompletion/ASTCompletionItem.swift index 8e4812b9e..454c25fbe 100644 --- a/Sources/SwiftSourceKitPlugin/ASTCompletion/ASTCompletionItem.swift +++ b/Sources/SwiftSourceKitPlugin/ASTCompletion/ASTCompletionItem.swift @@ -583,8 +583,8 @@ extension CompletionItem.PriorityBucket { self = .invalidTypeMatch } else { let skFlair = session.sourcekitd.ideApi.completion_item_get_flair(item.impl) - if (skFlair & SWIFTIDE_COMPLETION_FLAIR_EXPRESSIONSPECIFIC.rawValue != 0 - || skFlair & SWIFTIDE_COMPLETION_FLAIR_SUPERCHAIN.rawValue != 0) + if skFlair & SWIFTIDE_COMPLETION_FLAIR_EXPRESSIONSPECIFIC.rawValue != 0 + || skFlair & SWIFTIDE_COMPLETION_FLAIR_SUPERCHAIN.rawValue != 0 { self = .exprSpecific return diff --git a/Sources/SwiftSourceKitPlugin/CodeCompletion/Connection.swift b/Sources/SwiftSourceKitPlugin/CodeCompletion/Connection.swift index 3abc27be8..350ff9dc9 100644 --- a/Sources/SwiftSourceKitPlugin/CodeCompletion/Connection.swift +++ b/Sources/SwiftSourceKitPlugin/CodeCompletion/Connection.swift @@ -32,7 +32,7 @@ extension PopularityIndex.Scope { } /// Execute the given block on a thread with the given stack size and wait for that thread to finish. -fileprivate func withStackSize(_ stackSize: Int, execute block: @Sendable @escaping () -> T) -> T { +private func withStackSize(_ stackSize: Int, execute block: @Sendable @escaping () -> T) -> T { var result: T! = nil nonisolated(unsafe) let workItem = DispatchWorkItem(block: { result = block() @@ -55,7 +55,7 @@ final class Connection { var description: String { switch self { - case .openingFileFailed(path: let path): + case .openingFileFailed(let path): return "Could not open file '\(path)'" case .swiftIDEError(let message): return message diff --git a/Sources/SwiftSourceKitPlugin/CompletionResultsArrayBuilder.swift b/Sources/SwiftSourceKitPlugin/CompletionResultsArrayBuilder.swift index 8bfe7bcee..3510d5535 100644 --- a/Sources/SwiftSourceKitPlugin/CompletionResultsArrayBuilder.swift +++ b/Sources/SwiftSourceKitPlugin/CompletionResultsArrayBuilder.swift @@ -77,7 +77,7 @@ struct CompletionResultsArrayBuilder { + MemoryLayout.size // numResults + results.count * MemoryLayout.stride + nextString - return Array(unsafeUninitializedCapacity: capacity) { + return [UInt8](unsafeUninitializedCapacity: capacity) { (bytes: inout UnsafeMutableBufferPointer, size: inout Int) in size = capacity var cursor = UnsafeMutableRawBufferPointer(bytes) diff --git a/Sources/SwiftSourceKitPlugin/SKDResponseArrayBuilder.swift b/Sources/SwiftSourceKitPlugin/SKDResponseArrayBuilder.swift index a25885152..4fceadb35 100644 --- a/Sources/SwiftSourceKitPlugin/SKDResponseArrayBuilder.swift +++ b/Sources/SwiftSourceKitPlugin/SKDResponseArrayBuilder.swift @@ -55,11 +55,11 @@ struct SKDResponseArrayBuilder { sourcekitd.servicePluginApi.response_array_set_value(value, -1, newValue.value) case let newValue as SKDResponseArrayBuilder: sourcekitd.servicePluginApi.response_array_set_value(value, -1, newValue.value) - case let newValue as Array: + case let newValue as [SKDResponseValue]: self.append(sourcekitd.responseArray(newValue)) - case let newValue as Dictionary: + case let newValue as [sourcekitd_api_uid_t: SKDResponseValue]: self.append(sourcekitd.responseDictionary(newValue)) - case let newValue as Optional: + case let newValue as SKDResponseValue?: if let newValue { self.append(newValue) } diff --git a/Sources/SwiftSourceKitPlugin/SKDResponseDictionaryBuilder.swift b/Sources/SwiftSourceKitPlugin/SKDResponseDictionaryBuilder.swift index ee7ae2675..4a4d9333b 100644 --- a/Sources/SwiftSourceKitPlugin/SKDResponseDictionaryBuilder.swift +++ b/Sources/SwiftSourceKitPlugin/SKDResponseDictionaryBuilder.swift @@ -58,11 +58,11 @@ struct SKDResponseDictionaryBuilder { sourcekitd.servicePluginApi.response_dictionary_set_value(value, key, newValue.value) case let newValue as SKDResponseArrayBuilder: sourcekitd.servicePluginApi.response_dictionary_set_value(value, key, newValue.value) - case let newValue as Array: + case let newValue as [SKDResponseValue]: self.set(key, to: sourcekitd.responseArray(newValue)) - case let newValue as Dictionary: + case let newValue as [sourcekitd_api_uid_t: SKDResponseValue]: self.set(key, to: sourcekitd.responseDictionary(newValue)) - case let newValue as Optional: + case let newValue as SKDResponseValue?: if let newValue { self.set(key, to: newValue) } diff --git a/Sources/SwiftSourceKitPlugin/SKDResponseValue.swift b/Sources/SwiftSourceKitPlugin/SKDResponseValue.swift index 57b999b5d..b5c6d9be0 100644 --- a/Sources/SwiftSourceKitPlugin/SKDResponseValue.swift +++ b/Sources/SwiftSourceKitPlugin/SKDResponseValue.swift @@ -27,6 +27,6 @@ extension Double: SKDResponseValue {} extension sourcekitd_api_uid_t: SKDResponseValue {} extension SKDResponseDictionaryBuilder: SKDResponseValue {} extension SKDResponseArrayBuilder: SKDResponseValue {} -extension Array: SKDResponseValue {} -extension Dictionary: SKDResponseValue {} +extension [SKDResponseValue]: SKDResponseValue {} +extension [sourcekitd_api_uid_t: SKDResponseValue]: SKDResponseValue {} extension Optional: SKDResponseValue where Wrapped: SKDResponseValue {} diff --git a/Sources/SwiftSourceKitPluginCommon/CompletionResultsArray.swift b/Sources/SwiftSourceKitPluginCommon/CompletionResultsArray.swift index 5c4399af6..60b8a1da9 100644 --- a/Sources/SwiftSourceKitPluginCommon/CompletionResultsArray.swift +++ b/Sources/SwiftSourceKitPluginCommon/CompletionResultsArray.swift @@ -184,7 +184,7 @@ package struct CompletionResultsArray { try apply(keys.numBytesToErase, sourcekitd_api_variant_t(result.numBytesToErase), context) } try apply(keys.hasDiagnostic, sourcekitd_api_variant_t(result.hasDiagnostic), context) - if (result.groupID != 0) { + if result.groupID != 0 { try apply(keys.groupId, sourcekitd_api_variant_t(result.groupID), context) } } catch { diff --git a/Sources/TSCExtensions/SwitchableProcessResultExitStatus.swift b/Sources/TSCExtensions/SwitchableProcessResultExitStatus.swift index 900d75d36..f457e13d1 100644 --- a/Sources/TSCExtensions/SwitchableProcessResultExitStatus.swift +++ b/Sources/TSCExtensions/SwitchableProcessResultExitStatus.swift @@ -25,11 +25,11 @@ package enum SwitchableProcessResultExitStatus: Equatable { /// A description of the exit status that can be used in sentences like `Finished with `. package var description: String { switch self { - case .terminated(code: let code): + case .terminated(let code): "exit code \(code)" - case .abnormal(exception: let exception): + case .abnormal(let exception): "exception \(exception)" - case .signalled(signal: let signal): + case .signalled(let signal): "signal \(signal)" } } diff --git a/Sources/ToolchainRegistry/Toolchain.swift b/Sources/ToolchainRegistry/Toolchain.swift index 13dd0dfe3..a5fc5f046 100644 --- a/Sources/ToolchainRegistry/Toolchain.swift +++ b/Sources/ToolchainRegistry/Toolchain.swift @@ -36,7 +36,7 @@ package struct SwiftVersion: Sendable, Comparable, CustomStringConvertible { } } -fileprivate enum SwiftVersionParsingError: Error, CustomStringConvertible { +private enum SwiftVersionParsingError: Error, CustomStringConvertible { case failedToFindSwiftc case failedToParseOutput(output: String?) diff --git a/Sources/ToolchainRegistry/ToolchainRegistry.swift b/Sources/ToolchainRegistry/ToolchainRegistry.swift index 514949156..e429779cd 100644 --- a/Sources/ToolchainRegistry/ToolchainRegistry.swift +++ b/Sources/ToolchainRegistry/ToolchainRegistry.swift @@ -235,24 +235,22 @@ package final actor ToolchainRegistry { /// /// The default toolchain must be only of the registered toolchains. package var `default`: Toolchain? { - get { - // Toolchains discovered from the `SOURCEKIT_TOOLCHAIN_PATH` environment variable or relative to sourcekit-lsp's - // install path always take precedence over Xcode toolchains. - if let (toolchain, reason) = toolchainsAndReasons.first, reason < .xcode { - return toolchain - } - // Try finding the Xcode default toolchain. - if let tc = toolchainsByIdentifier[darwinToolchainIdentifier]?.first { - return tc - } - var result: Toolchain? = nil - for toolchain in toolchains { - if result == nil || toolchain.isProperSuperset(of: result!) { - result = toolchain - } + // Toolchains discovered from the `SOURCEKIT_TOOLCHAIN_PATH` environment variable or relative to sourcekit-lsp's + // install path always take precedence over Xcode toolchains. + if let (toolchain, reason) = toolchainsAndReasons.first, reason < .xcode { + return toolchain + } + // Try finding the Xcode default toolchain. + if let tc = toolchainsByIdentifier[darwinToolchainIdentifier]?.first { + return tc + } + var result: Toolchain? = nil + for toolchain in toolchains { + if result == nil || toolchain.isProperSuperset(of: result!) { + result = toolchain } - return result } + return result } /// The standard default toolchain identifier on Darwin. diff --git a/Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift b/Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift index 8a002d967..4b915c551 100644 --- a/Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift +++ b/Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift @@ -423,7 +423,7 @@ final class CompilationDatabaseTests: XCTestCase { } } -fileprivate var pathSeparator: String { +private var pathSeparator: String { #if os(Windows) return #"\"# #else diff --git a/Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift b/Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift index efb68ace1..7ca69c4d2 100644 --- a/Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift +++ b/Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift @@ -50,7 +50,7 @@ final class CompilerCommandLineOptionMatchingTests: XCTestCase { } } -fileprivate func assertOption( +private func assertOption( _ option: CompilerCommandLineOption, _ argument: String, _ expected: CompilerCommandLineOption.Match?, diff --git a/Tests/CompletionScoringTests/SwiftExtensionsTests.swift b/Tests/CompletionScoringTests/SwiftExtensionsTests.swift index d0c86f7a0..9e67ed0da 100644 --- a/Tests/CompletionScoringTests/SwiftExtensionsTests.swift +++ b/Tests/CompletionScoringTests/SwiftExtensionsTests.swift @@ -148,7 +148,7 @@ class SwiftExtensionsTests: XCTestCase { } } -fileprivate struct CompletionItem { +private struct CompletionItem { var score: Double var text: String } diff --git a/Tests/CompletionScoringTests/XCTestCaseScoringAdditions.swift b/Tests/CompletionScoringTests/XCTestCaseScoringAdditions.swift index bab93cf57..96ac7d930 100644 --- a/Tests/CompletionScoringTests/XCTestCaseScoringAdditions.swift +++ b/Tests/CompletionScoringTests/XCTestCaseScoringAdditions.swift @@ -108,7 +108,7 @@ fileprivate extension Double { } } -fileprivate func formatTable(rows: [[String]]) -> String { +private func formatTable(rows: [[String]]) -> String { if let headers = rows.first { let separator = " | " let headerSeparatorColumnSeparator = "-+-" diff --git a/Tests/LanguageServerProtocolJSONRPCTests/MessageParsingTests.swift b/Tests/LanguageServerProtocolJSONRPCTests/MessageParsingTests.swift index 3daea3e77..b30195341 100644 --- a/Tests/LanguageServerProtocolJSONRPCTests/MessageParsingTests.swift +++ b/Tests/LanguageServerProtocolJSONRPCTests/MessageParsingTests.swift @@ -227,7 +227,7 @@ final class MessageParsingTests: XCTestCase { XCTAssertEqual(Int(ascii: "\(Int.min)"), Int.min) XCTAssertEqual(Int(ascii: "\(Int.min+1)"), Int.min + 1) - XCTAssertEqual(Int(ascii: "1234567890"), 1234567890) + XCTAssertEqual(Int(ascii: "1234567890"), 1_234_567_890) XCTAssertEqual(Int(ascii: "\n\r \u{b}\u{d}\t45\n\t\r\u{c}"), 45) } } diff --git a/Tests/LanguageServerProtocolTests/LanguageServerProtocolTests.swift b/Tests/LanguageServerProtocolTests/LanguageServerProtocolTests.swift index 6524f84a3..5d94b0d67 100644 --- a/Tests/LanguageServerProtocolTests/LanguageServerProtocolTests.swift +++ b/Tests/LanguageServerProtocolTests/LanguageServerProtocolTests.swift @@ -13,7 +13,7 @@ import LanguageServerProtocol import XCTest -fileprivate func AssertDataIsString( +private func AssertDataIsString( _ data: Data, expected: String, file: StaticString = #filePath, diff --git a/Tests/SKLoggingTests/LoggingTests.swift b/Tests/SKLoggingTests/LoggingTests.swift index cd3ba9ed5..ee0b4e382 100644 --- a/Tests/SKLoggingTests/LoggingTests.swift +++ b/Tests/SKLoggingTests/LoggingTests.swift @@ -14,7 +14,7 @@ import SKTestSupport import XCTest -fileprivate func assertLogging( +private func assertLogging( logLevel: NonDarwinLogLevel = .default, privacyLevel: NonDarwinLogPrivacy = .private, expected: [String], diff --git a/Tests/SKUtilitiesTests/LRUCacheTests.swift b/Tests/SKUtilitiesTests/LRUCacheTests.swift index 7ce515be7..86eed99e6 100644 --- a/Tests/SKUtilitiesTests/LRUCacheTests.swift +++ b/Tests/SKUtilitiesTests/LRUCacheTests.swift @@ -137,7 +137,7 @@ final class LRUCacheTests: XCTestCase { } } -fileprivate func assertLRUCacheKeys( +private func assertLRUCacheKeys( _ lruCache: LRUCache, expectedKeys: [Key], file: StaticString = #filePath, diff --git a/Tests/SKUtilitiesTests/LineTablePerfTests.swift b/Tests/SKUtilitiesTests/LineTablePerfTests.swift index 6a651a384..7de519c60 100644 --- a/Tests/SKUtilitiesTests/LineTablePerfTests.swift +++ b/Tests/SKUtilitiesTests/LineTablePerfTests.swift @@ -15,7 +15,7 @@ import SKUtilities import XCTest /// A linear congruential generator with user-specified seed value. Useful for generating a predictable "random" number sequence. -fileprivate struct SimpleLCG: RandomNumberGenerator { +private struct SimpleLCG: RandomNumberGenerator { var state: UInt64 @@ -24,7 +24,7 @@ fileprivate struct SimpleLCG: RandomNumberGenerator { } package mutating func next() -> UInt64 { - state = state &* 6364136223846793005 &+ 1442695040888963407 + state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 return state } } diff --git a/Tests/SemanticIndexTests/TaskSchedulerTests.swift b/Tests/SemanticIndexTests/TaskSchedulerTests.swift index 22d43cef7..7e978f065 100644 --- a/Tests/SemanticIndexTests/TaskSchedulerTests.swift +++ b/Tests/SemanticIndexTests/TaskSchedulerTests.swift @@ -349,7 +349,7 @@ final class TaskSchedulerTests: XCTestCase { // MARK: - Test helpers /// Identifies a task that was scheduled in a test case. -fileprivate enum TaskID: Hashable, CustomDebugStringConvertible { +private enum TaskID: Hashable, CustomDebugStringConvertible { case lowPriority(Int) case highPriority(Int) @@ -385,7 +385,7 @@ fileprivate enum TaskID: Hashable, CustomDebugStringConvertible { } /// A `TaskDescriptionProtocol` that is based on closures, which makes it easy to use in test cases. -fileprivate final class ClosureTaskDescription: TaskDescriptionProtocol { +private final class ClosureTaskDescription: TaskDescriptionProtocol { let taskId: TaskID? let estimatedCPUCoreCount: Int private let closure: @Sendable () async -> Void @@ -442,7 +442,7 @@ fileprivate actor TaskExecutionRecorder { } } -fileprivate func runTaskScheduler( +private func runTaskScheduler( highPriorityTasks: Int = 4, lowPriorityTasks: Int = 2, highPriorityThreshold: TaskPriority = .high, @@ -523,7 +523,7 @@ fileprivate extension TaskScheduler { // MARK: - Misc assertion functions -fileprivate func assertAllSatisfy( +private func assertAllSatisfy( _ array: some Collection, _ predicate: (Element) -> Bool, file: StaticString = #filePath, @@ -532,7 +532,7 @@ fileprivate func assertAllSatisfy( XCTAssert(array.allSatisfy(predicate), "\(array) did not fulfill predicate", file: file, line: line) } -fileprivate func assertContains( +private func assertContains( _ array: some Collection, _ predicate: (Element) -> Bool, file: StaticString = #filePath, @@ -541,7 +541,7 @@ fileprivate func assertContains( XCTAssert(array.contains(where: predicate), "\(array) did not fulfill predicate", file: file, line: line) } -fileprivate func assertNotContains( +private func assertNotContains( _ array: some Collection, _ predicate: (Element) -> Bool, file: StaticString = #filePath, diff --git a/Tests/SourceKitLSPTests/ClosureCompletionFormatTests.swift b/Tests/SourceKitLSPTests/ClosureCompletionFormatTests.swift index 6ec213001..bc3f95091 100644 --- a/Tests/SourceKitLSPTests/ClosureCompletionFormatTests.swift +++ b/Tests/SourceKitLSPTests/ClosureCompletionFormatTests.swift @@ -18,7 +18,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import XCTest -fileprivate func assertFormatted( +private func assertFormatted( tree: T, expected: String, using format: ClosureCompletionFormat = ClosureCompletionFormat(indentationWidth: .spaces(4)), @@ -28,7 +28,7 @@ fileprivate func assertFormatted( XCTAssertEqual(tree.formatted(using: format).description, expected, file: file, line: line) } -fileprivate func assertFormatted( +private func assertFormatted( source: String, expected: String, using format: ClosureCompletionFormat = ClosureCompletionFormat(indentationWidth: .spaces(4)), diff --git a/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift b/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift index 48e954924..f4c5dead8 100644 --- a/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift +++ b/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift @@ -356,7 +356,7 @@ final class CompilationDatabaseTests: XCTestCase { } } -fileprivate let defaultSDKArgs: String = { +private let defaultSDKArgs: String = { if let defaultSDKPath { let escapedPath = defaultSDKPath.replacing(#"\"#, with: #"\\"#) return """ diff --git a/Tests/SourceKitLSPTests/CrashRecoveryTests.swift b/Tests/SourceKitLSPTests/CrashRecoveryTests.swift index 55b313d85..0d4fb7ea6 100644 --- a/Tests/SourceKitLSPTests/CrashRecoveryTests.swift +++ b/Tests/SourceKitLSPTests/CrashRecoveryTests.swift @@ -26,7 +26,7 @@ fileprivate extension HoverResponse { case .markedStrings(let markedStrings): for markedString in markedStrings { switch markedString { - case .markdown(value: let value), .codeBlock(language: _, value: let value): + case .markdown(let value), .codeBlock(language: _, let value): if value.contains(string) { return true } diff --git a/Tests/SourceKitLSPTests/DoccDocumentationTests.swift b/Tests/SourceKitLSPTests/DoccDocumentationTests.swift index b86ef933c..39ec46c92 100644 --- a/Tests/SourceKitLSPTests/DoccDocumentationTests.swift +++ b/Tests/SourceKitLSPTests/DoccDocumentationTests.swift @@ -936,12 +936,12 @@ final class DoccDocumentationTests: XCTestCase { } } -fileprivate enum PartialConvertResponse { +private enum PartialConvertResponse { case renderNode(kind: RenderNode.Kind, path: String? = nil, containing: String? = nil) case error(DocCDocumentationError) } -fileprivate func renderDocumentation( +private func renderDocumentation( fileName: String, project: SwiftPMTestProject, expectedResponses: [String: PartialConvertResponse], @@ -963,7 +963,7 @@ fileprivate func renderDocumentation( ) } -fileprivate func renderDocumentation( +private func renderDocumentation( markedText: String, language: Language = .swift, expectedResponses: [String: PartialConvertResponse], @@ -984,7 +984,7 @@ fileprivate func renderDocumentation( ) } -fileprivate func renderDocumentation( +private func renderDocumentation( testClient: TestSourceKitLSPClient, uri: DocumentURI, positions: DocumentPositions, diff --git a/Tests/SourceKitLSPTests/DocumentSymbolTests.swift b/Tests/SourceKitLSPTests/DocumentSymbolTests.swift index 9de912025..84621b979 100644 --- a/Tests/SourceKitLSPTests/DocumentSymbolTests.swift +++ b/Tests/SourceKitLSPTests/DocumentSymbolTests.swift @@ -791,7 +791,7 @@ final class DocumentSymbolTests: XCTestCase { } } -fileprivate func assertDocumentSymbols( +private func assertDocumentSymbols( _ markedText: String, _ expectedDocumentSymbols: (DocumentPositions) -> [DocumentSymbol], file: StaticString = #filePath, diff --git a/Tests/SourceKitLSPTests/DocumentationLanguageServiceTests.swift b/Tests/SourceKitLSPTests/DocumentationLanguageServiceTests.swift index d9607f56d..b03170524 100644 --- a/Tests/SourceKitLSPTests/DocumentationLanguageServiceTests.swift +++ b/Tests/SourceKitLSPTests/DocumentationLanguageServiceTests.swift @@ -25,7 +25,7 @@ final class DocumentationLanguageServiceTests: XCTestCase { } } -fileprivate func assertHandles(language: Language) async throws { +private func assertHandles(language: Language) async throws { let testClient = try await TestSourceKitLSPClient() let uri = DocumentURI(for: language) testClient.openDocument("", uri: uri) diff --git a/Tests/SourceKitLSPTests/SemanticTokensTests.swift b/Tests/SourceKitLSPTests/SemanticTokensTests.swift index 3d775d2f1..7cce37dec 100644 --- a/Tests/SourceKitLSPTests/SemanticTokensTests.swift +++ b/Tests/SourceKitLSPTests/SemanticTokensTests.swift @@ -1031,7 +1031,7 @@ final class SemanticTokensTests: XCTestCase { } } -fileprivate struct TokenSpec { +private struct TokenSpec { let marker: String let length: Int let kind: SemanticTokenTypes @@ -1050,7 +1050,7 @@ fileprivate struct TokenSpec { } } -fileprivate func assertSemanticTokens( +private func assertSemanticTokens( markedContents: String, language: Language = .swift, range: (startMarker: String, endMarker: String)? = nil, @@ -1085,7 +1085,7 @@ fileprivate func assertSemanticTokens( ) } -fileprivate func assertSemanticTokens( +private func assertSemanticTokens( uri: DocumentURI, in testClient: TestSourceKitLSPClient, positions: DocumentPositions, diff --git a/Tests/SourceKitLSPTests/SyntaxRefactorTests.swift b/Tests/SourceKitLSPTests/SyntaxRefactorTests.swift index abd9cd89b..460f07897 100644 --- a/Tests/SourceKitLSPTests/SyntaxRefactorTests.swift +++ b/Tests/SourceKitLSPTests/SyntaxRefactorTests.swift @@ -338,7 +338,7 @@ func assertRefactor( /// which this function was called. /// - line: The line number on which failure occurred. Defaults to the line number on which this /// function was called. -fileprivate func assertStringsEqualWithDiff( +private func assertStringsEqualWithDiff( _ actual: String, _ expected: String, _ message: String = "", @@ -360,7 +360,7 @@ fileprivate func assertStringsEqualWithDiff( } /// `XCTFail` with `diff`-style output. -fileprivate func failStringsEqualWithDiff( +private func failStringsEqualWithDiff( _ actual: String, _ expected: String, _ message: String = "", diff --git a/Tests/SourceKitLSPTests/TypeHierarchyTests.swift b/Tests/SourceKitLSPTests/TypeHierarchyTests.swift index 771c80abe..1fea83261 100644 --- a/Tests/SourceKitLSPTests/TypeHierarchyTests.swift +++ b/Tests/SourceKitLSPTests/TypeHierarchyTests.swift @@ -263,7 +263,7 @@ fileprivate extension TypeHierarchyItem { /// Compares the given type hierarchies ignoring the implementation-specific /// data field (which includes e.g. USRs that are difficult to test, especially /// in the presence of extensions, and are not user-visible anyway). -fileprivate func assertEqualIgnoringData( +private func assertEqualIgnoringData( _ actual: [TypeHierarchyItem]?, _ expected: [TypeHierarchyItem], file: StaticString = #filePath, diff --git a/Tests/SourceKitLSPTests/WorkspaceTests.swift b/Tests/SourceKitLSPTests/WorkspaceTests.swift index 87b38c87e..f054a48ad 100644 --- a/Tests/SourceKitLSPTests/WorkspaceTests.swift +++ b/Tests/SourceKitLSPTests/WorkspaceTests.swift @@ -1389,7 +1389,7 @@ final class WorkspaceTests: XCTestCase { } } -fileprivate let defaultSDKArgs: String = { +private let defaultSDKArgs: String = { if let defaultSDKPath { let escapedPath = defaultSDKPath.replacing(#"\"#, with: #"\\"#) return """ diff --git a/Tests/SwiftSourceKitPluginTests/SwiftSourceKitPluginTests.swift b/Tests/SwiftSourceKitPluginTests/SwiftSourceKitPluginTests.swift index 59bd49884..7607492c2 100644 --- a/Tests/SwiftSourceKitPluginTests/SwiftSourceKitPluginTests.swift +++ b/Tests/SwiftSourceKitPluginTests/SwiftSourceKitPluginTests.swift @@ -1679,7 +1679,7 @@ final class SwiftSourceKitPluginTests: XCTestCase { // MARK: - Structured result types -fileprivate struct CompletionResultSet: Sendable { +private struct CompletionResultSet: Sendable { var unfilteredResultCount: Int var memberAccessTypes: [String] var items: [CompletionResult] @@ -1711,7 +1711,7 @@ fileprivate struct CompletionResultSet: Sendable { } } -fileprivate struct CompletionResult: Equatable, Sendable { +private struct CompletionResult: Equatable, Sendable { nonisolated(unsafe) var kind: sourcekitd_api_uid_t var id: Int var name: String @@ -1765,7 +1765,7 @@ fileprivate struct CompletionResult: Equatable, Sendable { } } -fileprivate struct CompletionDocumentation { +private struct CompletionDocumentation { var docBrief: String? = nil var associatedUSRs: [String] = [] @@ -1776,7 +1776,7 @@ fileprivate struct CompletionDocumentation { } } -fileprivate struct CompletionDiagnostic { +private struct CompletionDiagnostic { var severity: sourcekitd_api_uid_t var description: String @@ -1793,7 +1793,7 @@ fileprivate struct CompletionDiagnostic { } } -fileprivate struct TestError: Error { +private struct TestError: Error { let error: String init(_ message: String) { From 6074529dac66289a12ba78d0bff51179a0889944 Mon Sep 17 00:00:00 2001 From: Alex Hoppen Date: Mon, 11 Aug 2025 09:31:09 +0200 Subject: [PATCH 2/2] Manually fix swift-format lint rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - I think there are valid calls with mixing inline and trailing closures (notably `Debouncer`), so I’m considering whether we should disable that rule. - The `forEach` rule is a little annoying because we have `forEach` on `SKDResponseArray`. But it caught two cases of using `forEach` on arrays, so I think it’s worth keeping. --- .../BuildServerManager.swift | 44 ++++++++++--------- .../CompilationDatabase.swift | 4 +- .../Messages/TaskStartNotification.swift | 2 +- .../Text/MatchCollator.swift | 15 ++++--- Sources/SKUtilities/Debouncer.swift | 4 +- Sources/SourceKitD/SKDResponseArray.swift | 4 ++ Sources/SourceKitD/sourcekitd_uids.swift | 6 +++ Sources/SourceKitLSP/Swift/CommentXML.swift | 7 ++- Sources/SourceKitLSP/Swift/Diagnostic.swift | 6 +++ .../Swift/RefactoringResponse.swift | 4 ++ .../Swift/RelatedIdentifiers.swift | 2 + .../Swift/SemanticRefactorCommand.swift | 2 + .../Swift/SyntaxHighlightingTokenParser.swift | 2 + .../SourceKitLSP/Swift/VariableTypeInfo.swift | 2 + .../CompletionProvider.swift | 2 + Tests/SKUtilitiesTests/DebouncerTests.swift | 12 +++-- 16 files changed, 80 insertions(+), 38 deletions(-) diff --git a/Sources/BuildServerIntegration/BuildServerManager.swift b/Sources/BuildServerIntegration/BuildServerManager.swift index cfb1f85b3..dd2cf5202 100644 --- a/Sources/BuildServerIntegration/BuildServerManager.swift +++ b/Sources/BuildServerIntegration/BuildServerManager.swift @@ -460,18 +460,19 @@ package actor BuildServerManager: QueueBasedMessageHandler { // The debounce duration of 500ms was chosen arbitrarily without any measurements. self.filesDependenciesUpdatedDebouncer = Debouncer( debounceDuration: .milliseconds(500), - combineResults: { $0.union($1) } - ) { - [weak self] (filesWithUpdatedDependencies) in - guard let self, let delegate = await self.delegate else { - logger.fault("Not calling filesDependenciesUpdated because no delegate exists in SwiftPMBuildServer") - return - } - let changedWatchedFiles = await self.watchedFilesReferencing(mainFiles: filesWithUpdatedDependencies) - if !changedWatchedFiles.isEmpty { - await delegate.filesDependenciesUpdated(changedWatchedFiles) + combineResults: { $0.union($1) }, + makeCall: { + [weak self] (filesWithUpdatedDependencies) in + guard let self, let delegate = await self.delegate else { + logger.fault("Not calling filesDependenciesUpdated because no delegate exists in SwiftPMBuildServer") + return + } + let changedWatchedFiles = await self.watchedFilesReferencing(mainFiles: filesWithUpdatedDependencies) + if !changedWatchedFiles.isEmpty { + await delegate.filesDependenciesUpdated(changedWatchedFiles) + } } - } + ) // We don't need a large debounce duration here. It just needs to be big enough to accumulate // `resultReceivedAfterTimeout` calls for the same document (see comment on `filesBuildSettingsChangedDebouncer`). @@ -479,17 +480,18 @@ package actor BuildServerManager: QueueBasedMessageHandler { // plenty while still not causing a noticeable delay to the user. self.filesBuildSettingsChangedDebouncer = Debouncer( debounceDuration: .milliseconds(20), - combineResults: { $0.union($1) } - ) { - [weak self] (filesWithChangedBuildSettings) in - guard let self, let delegate = await self.delegate else { - logger.fault("Not calling fileBuildSettingsChanged because no delegate exists in SwiftPMBuildServer") - return - } - if !filesWithChangedBuildSettings.isEmpty { - await delegate.fileBuildSettingsChanged(filesWithChangedBuildSettings) + combineResults: { $0.union($1) }, + makeCall: { + [weak self] (filesWithChangedBuildSettings) in + guard let self, let delegate = await self.delegate else { + logger.fault("Not calling fileBuildSettingsChanged because no delegate exists in SwiftPMBuildServer") + return + } + if !filesWithChangedBuildSettings.isEmpty { + await delegate.fileBuildSettingsChanged(filesWithChangedBuildSettings) + } } - } + ) // TODO: Forward file watch patterns from this initialize request to the client // (https://github.com/swiftlang/sourcekit-lsp/issues/1671) diff --git a/Sources/BuildServerIntegration/CompilationDatabase.swift b/Sources/BuildServerIntegration/CompilationDatabase.swift index 731fd600b..55903a9f9 100644 --- a/Sources/BuildServerIntegration/CompilationDatabase.swift +++ b/Sources/BuildServerIntegration/CompilationDatabase.swift @@ -140,7 +140,9 @@ package struct JSONCompilationDatabase: Equatable, Codable { package func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() - try commands.forEach { try container.encode($0) } + for command in commands { + try container.encode(command) + } } package subscript(_ uri: DocumentURI) -> [CompilationDatabaseCompileCommand] { diff --git a/Sources/BuildServerProtocol/Messages/TaskStartNotification.swift b/Sources/BuildServerProtocol/Messages/TaskStartNotification.swift index e43f355d6..444ee0c35 100644 --- a/Sources/BuildServerProtocol/Messages/TaskStartNotification.swift +++ b/Sources/BuildServerProtocol/Messages/TaskStartNotification.swift @@ -46,7 +46,7 @@ public struct TaskStartNotification: NotificationType { /// Message describing the task. public var message: String? - /** Kind of data to expect in the `data` field. If this field is not set, the kind of data is not specified. */ + /// Kind of data to expect in the `data` field. If this field is not set, the kind of data is not specified. public var dataKind: TaskStartDataKind? /// Optional metadata about the task. diff --git a/Sources/CompletionScoring/Text/MatchCollator.swift b/Sources/CompletionScoring/Text/MatchCollator.swift index 1df396a0b..07e6df1a3 100644 --- a/Sources/CompletionScoring/Text/MatchCollator.swift +++ b/Sources/CompletionScoring/Text/MatchCollator.swift @@ -415,15 +415,16 @@ package struct MatchCollator { influencingTokenizedIdentifiers: influencingTokenizedIdentifiers, patternUTF8Length: 0, orderingTiesBy: { _, _ in false }, - maximumNumberOfItemsForExpensiveSelection: Self.defaultMaximumNumberOfItemsForExpensiveSelection - ) { collator in - return (0.. { package init( debounceDuration: Duration, combineResults: @escaping (Parameter, Parameter) -> Parameter, - _ makeCall: @Sendable @escaping (Parameter) async -> Void + makeCall: @Sendable @escaping (Parameter) async -> Void ) { self.debounceDuration = debounceDuration self.combineParameters = combineResults @@ -84,7 +84,7 @@ package actor Debouncer { extension Debouncer { package init(debounceDuration: Duration, _ makeCall: @Sendable @escaping () async -> Void) { - self.init(debounceDuration: debounceDuration, combineResults: { _, _ in }, makeCall) + self.init(debounceDuration: debounceDuration, combineResults: { _, _ in }, makeCall: makeCall) } package func scheduleCall() { diff --git a/Sources/SourceKitD/SKDResponseArray.swift b/Sources/SourceKitD/SKDResponseArray.swift index f7a65c2c7..62784d8d5 100644 --- a/Sources/SourceKitD/SKDResponseArray.swift +++ b/Sources/SourceKitD/SKDResponseArray.swift @@ -62,6 +62,8 @@ package final class SKDResponseArray: Sendable { package func map(_ transform: (SKDResponseDictionary) throws -> T) rethrows -> [T] { var result: [T] = [] result.reserveCapacity(self.count) + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. try self.forEach { _, element in result.append(try transform(element)) return true @@ -71,6 +73,8 @@ package final class SKDResponseArray: Sendable { package func compactMap(_ transform: (SKDResponseDictionary) throws -> T?) rethrows -> [T] { var result: [T] = [] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. try self.forEach { _, element in if let transformed = try transform(element) { result.append(transformed) diff --git a/Sources/SourceKitD/sourcekitd_uids.swift b/Sources/SourceKitD/sourcekitd_uids.swift index 7ed088d0a..bc6d6a674 100644 --- a/Sources/SourceKitD/sourcekitd_uids.swift +++ b/Sources/SourceKitD/sourcekitd_uids.swift @@ -14,6 +14,8 @@ package import Csourcekitd +// swift-format-ignore: TypeNamesShouldBeCapitalized +// Matching C style types package struct sourcekitd_api_keys { /// `key.version_major` package let versionMajor: sourcekitd_api_uid_t @@ -776,6 +778,8 @@ package struct sourcekitd_api_keys { } } +// swift-format-ignore: TypeNamesShouldBeCapitalized +// Matching C style types package struct sourcekitd_api_requests { /// `source.request.protocol_version` package let protocolVersion: sourcekitd_api_uid_t @@ -947,6 +951,8 @@ package struct sourcekitd_api_requests { } } +// swift-format-ignore: TypeNamesShouldBeCapitalized +// Matching C style types package struct sourcekitd_api_values { /// `source.lang.swift.decl.function.free` package let declFunctionFree: sourcekitd_api_uid_t diff --git a/Sources/SourceKitLSP/Swift/CommentXML.swift b/Sources/SourceKitLSP/Swift/CommentXML.swift index 3aee62188..31b4f44e4 100644 --- a/Sources/SourceKitLSP/Swift/CommentXML.swift +++ b/Sources/SourceKitLSP/Swift/CommentXML.swift @@ -65,8 +65,11 @@ private struct XMLToMarkdown { // [XMLNode]? is the type of XMLNode.children. mutating func toMarkdown(_ nodes: [XMLNode]?, separator: String = "") { - nodes?.forEach { - toMarkdown($0) + guard let nodes else { + return + } + for node in nodes { + toMarkdown(node) out += separator } } diff --git a/Sources/SourceKitLSP/Swift/Diagnostic.swift b/Sources/SourceKitLSP/Swift/Diagnostic.swift index ec98e1813..4512c3c3b 100644 --- a/Sources/SourceKitLSP/Swift/Diagnostic.swift +++ b/Sources/SourceKitLSP/Swift/Diagnostic.swift @@ -26,6 +26,8 @@ extension CodeAction { /// If this is from a note, the note's description should be passed as `fromNote`. init?(fixits: SKDResponseArray, in snapshot: DocumentSnapshot, fromNote: String?) { var edits: [TextEdit] = [] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. let editsMapped = fixits.forEach { (_, skfixit) -> Bool in if let edit = TextEdit(fixit: skfixit, in: snapshot) { edits.append(edit) @@ -204,6 +206,8 @@ extension Diagnostic { range = Range(snapshot.positionOf(utf8Offset: utf8Offset)) } + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. // If the diagnostic has a range associated with it that starts at the same location as the diagnostics position, use it to retrieve a proper range for the diagnostic, instead of just reporting a zero-length range. (diag[keys.ranges] as SKDResponseArray?)?.forEach { index, skRange in guard let utf8Offset: Int = skRange[keys.offset], @@ -273,6 +277,8 @@ extension Diagnostic { var notes: [DiagnosticRelatedInformation]? = nil if let sknotes: SKDResponseArray = diag[keys.diagnostics] { notes = [] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. sknotes.forEach { (_, sknote) -> Bool in guard let note = DiagnosticRelatedInformation( diff --git a/Sources/SourceKitLSP/Swift/RefactoringResponse.swift b/Sources/SourceKitLSP/Swift/RefactoringResponse.swift index 623596181..804f5e9e7 100644 --- a/Sources/SourceKitLSP/Swift/RefactoringResponse.swift +++ b/Sources/SourceKitLSP/Swift/RefactoringResponse.swift @@ -29,11 +29,15 @@ extension [RefactoringEdit] { self = [] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. categorizedEdits.forEach { _, categorizedEdit in guard let edits: SKDResponseArray = categorizedEdit[keys.edits] else { logger.fault("edits doesn't exist in categorizedEdit dictionary") return true } + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. edits.forEach { _, edit in guard let startLine: Int = edit[keys.line], let startColumn: Int = edit[keys.column], diff --git a/Sources/SourceKitLSP/Swift/RelatedIdentifiers.swift b/Sources/SourceKitLSP/Swift/RelatedIdentifiers.swift index 229d28881..89ba66848 100644 --- a/Sources/SourceKitLSP/Swift/RelatedIdentifiers.swift +++ b/Sources/SourceKitLSP/Swift/RelatedIdentifiers.swift @@ -87,6 +87,8 @@ extension SwiftLanguageService { var relatedIdentifiers: [RelatedIdentifier] = [] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. results.forEach { _, value in guard let offset: Int = value[keys.offset], let length: Int = value[keys.length] else { return true // continue diff --git a/Sources/SourceKitLSP/Swift/SemanticRefactorCommand.swift b/Sources/SourceKitLSP/Swift/SemanticRefactorCommand.swift index 08f793847..476f2039f 100644 --- a/Sources/SourceKitLSP/Swift/SemanticRefactorCommand.swift +++ b/Sources/SourceKitLSP/Swift/SemanticRefactorCommand.swift @@ -86,6 +86,8 @@ extension Array where Element == SemanticRefactorCommand { return nil } var commands: [SemanticRefactorCommand] = [] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. results.forEach { _, value in if let name: String = value[keys.actionName], let actionuid: sourcekitd_api_uid_t = value[keys.actionUID], diff --git a/Sources/SourceKitLSP/Swift/SyntaxHighlightingTokenParser.swift b/Sources/SourceKitLSP/Swift/SyntaxHighlightingTokenParser.swift index c349e9f6d..b6fa55511 100644 --- a/Sources/SourceKitLSP/Swift/SyntaxHighlightingTokenParser.swift +++ b/Sources/SourceKitLSP/Swift/SyntaxHighlightingTokenParser.swift @@ -70,6 +70,8 @@ struct SyntaxHighlightingTokenParser { in snapshot: DocumentSnapshot, into tokens: inout SyntaxHighlightingTokens ) { + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. response.forEach { (_, value) in parseTokens(value, in: snapshot, into: &tokens) return true diff --git a/Sources/SourceKitLSP/Swift/VariableTypeInfo.swift b/Sources/SourceKitLSP/Swift/VariableTypeInfo.swift index 9c0346911..348913c2d 100644 --- a/Sources/SourceKitLSP/Swift/VariableTypeInfo.swift +++ b/Sources/SourceKitLSP/Swift/VariableTypeInfo.swift @@ -109,6 +109,8 @@ extension SwiftLanguageService { variableTypeInfos.reserveCapacity(skVariableTypeInfos.count) let syntaxTree = await syntaxTreeManager.syntaxTree(for: snapshot) + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDResponseArray.forEach`, not `Array.forEach`. skVariableTypeInfos.forEach { (_, skVariableTypeInfo) -> Bool in guard let info = VariableTypeInfo(skVariableTypeInfo, in: snapshot, syntaxTree: syntaxTree) else { assertionFailure("VariableTypeInfo failed to deserialize") diff --git a/Sources/SwiftSourceKitPlugin/CompletionProvider.swift b/Sources/SwiftSourceKitPlugin/CompletionProvider.swift index d02ed6d7b..cf248b9ea 100644 --- a/Sources/SwiftSourceKitPlugin/CompletionProvider.swift +++ b/Sources/SwiftSourceKitPlugin/CompletionProvider.swift @@ -31,6 +31,8 @@ import SwiftSourceKitPluginCommon /// Returns `nil` if parsing failed because one of he entries didn't contain a key or value. private func parsePopularityDict(_ data: SKDRequestArrayReader) -> [String: Popularity]? { var result: [String: Popularity] = [:] + // swift-format-ignore: ReplaceForEachWithForLoop + // Reference is to `SKDRequestArrayReader.forEach`, not `Array.forEach`. let iteratedAllEntries = data.forEach { (_, entry) -> Bool in // We can't deserialize double values in SourceKit requests at the moment. // We transfer the double value as an integer with 9 significant digits by multiplying it by 1 billion first. diff --git a/Tests/SKUtilitiesTests/DebouncerTests.swift b/Tests/SKUtilitiesTests/DebouncerTests.swift index 1527cbb61..b00b8fbb9 100644 --- a/Tests/SKUtilitiesTests/DebouncerTests.swift +++ b/Tests/SKUtilitiesTests/DebouncerTests.swift @@ -31,10 +31,14 @@ final class DebouncerTests: XCTestCase { func testDebouncerCombinesParameters() async throws { let expectation = self.expectation(description: "makeCallCalled") expectation.assertForOverFulfill = true - let debouncer = Debouncer(debounceDuration: .seconds(0.1), combineResults: { $0 + $1 }) { param in - XCTAssertEqual(param, 3) - expectation.fulfill() - } + let debouncer = Debouncer( + debounceDuration: .seconds(0.1), + combineResults: { $0 + $1 }, + makeCall: { param in + XCTAssertEqual(param, 3) + expectation.fulfill() + } + ) await debouncer.scheduleCall(1) await debouncer.scheduleCall(2) try await fulfillmentOfOrThrow(expectation)