Skip to content

Apply exhaustive swift-format configuration from swift-syntax #2231

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 62 additions & 6 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -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,
}
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
48 changes: 25 additions & 23 deletions Sources/BuildServerIntegration/BuildServerManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ package import ToolchainRegistry

import struct TSCBasic.RelativePath

fileprivate typealias RequestCache<Request: RequestType & Hashable> = Cache<Request, Request.Response>
private typealias RequestCache<Request: RequestType & Hashable> = Cache<Request, Request.Response>

/// An output path returned from the build server in the `SourceItem.data.outputPath` field.
package enum OutputPath: Hashable, Comparable, CustomLogStringConvertible {
Expand Down Expand Up @@ -460,36 +460,38 @@ 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`).
// Since they should all come in at the same time, a couple of milliseconds should be sufficient here, an 20ms be
// 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)
Expand Down Expand Up @@ -1627,7 +1629,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
Expand Down
4 changes: 3 additions & 1 deletion Sources/BuildServerIntegration/CompilationDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ package struct CompilerCommandLineOption {
}
}

extension Array<CompilerCommandLineOption> {
extension [CompilerCommandLineOption] {
func firstMatch(for argument: String) -> CompilerCommandLineOption.Match? {
for optionToRemove in self {
if let match = optionToRemove.matches(argument: argument) {
Expand Down
4 changes: 2 additions & 2 deletions Sources/BuildServerIntegration/SplitShellCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

// MARK: - Unix

fileprivate struct UnixCommandParser {
private struct UnixCommandParser {
var content: Substring
var i: Substring.UTF8View.Index
var result: [String] = []
Expand Down Expand Up @@ -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

Expand Down
10 changes: 5 additions & 5 deletions Sources/BuildServerIntegration/SwiftPMBuildServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -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)) ?? "<no stderr>"
let stderr = (try? String(bytes: result.stderrOutput.get(), encoding: .utf8)) ?? "<no stderr>"
Expand All @@ -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)")
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/BuildServerProtocol/Messages.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

public import LanguageServerProtocol

fileprivate let requestTypes: [_RequestType.Type] = [
private let requestTypes: [_RequestType.Type] = [
BuildShutdownRequest.self,
BuildTargetPrepareRequest.self,
BuildTargetSourcesRequest.self,
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ package struct PopularityTable {
}
}

extension Dictionary<String, Popularity> {
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ extension SemanticClassification {
}

/// Used for debugging.
fileprivate protocol CompletionScoreComponent {
private protocol CompletionScoreComponent {
var name: String { get }

var instance: String { get }
Expand Down
6 changes: 2 additions & 4 deletions Sources/CompletionScoring/Text/InfluencingIdentifiers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
17 changes: 9 additions & 8 deletions Sources/CompletionScoring/Text/MatchCollator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -415,15 +415,16 @@ package struct MatchCollator {
influencingTokenizedIdentifiers: influencingTokenizedIdentifiers,
patternUTF8Length: 0,
orderingTiesBy: { _, _ in false },
maximumNumberOfItemsForExpensiveSelection: Self.defaultMaximumNumberOfItemsForExpensiveSelection
) { collator in
return (0..<iterations).reduce(0) { accumulation, _ in
collator.applyInfluence()
return collator.rescoredMatches.reduce(accumulation) { accumulation, match in
accumulation + match.individualScore.value
maximumNumberOfItemsForExpensiveSelection: Self.defaultMaximumNumberOfItemsForExpensiveSelection,
body: { collator in
return (0..<iterations).reduce(0) { accumulation, _ in
collator.applyInfluence()
return collator.rescoredMatches.reduce(accumulation) { accumulation, match in
accumulation + match.individualScore.value
}
}
}
}
)
}

package static func tokenize(
Expand Down
9 changes: 5 additions & 4 deletions Sources/CompletionScoring/Text/Pattern.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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..<cidx)
}
cidx = initialCidx + token.length
Expand Down Expand Up @@ -426,7 +426,8 @@ package final class Pattern: Sendable {
candidateBytes: UTF8Bytes,
patternBytes: UTF8Bytes
) -> 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] {
Expand Down Expand Up @@ -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)
}
Expand All @@ -538,7 +539,7 @@ package final class Pattern: Sendable {
score *= 0.75
}

if (matchStyle == .acronym) {
if matchStyle == .acronym {
badShortMatches = 0
falseStarts = 0
}
Expand Down
Loading