From 6452eff916eca4f89d2216fc13a771b49896f62e Mon Sep 17 00:00:00 2001 From: Tony Allevato Date: Tue, 1 Oct 2024 08:16:03 -0400 Subject: [PATCH 1/3] Bring over swift-syntax's formatter config into swift-format. --- .swift-format | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .swift-format diff --git a/.swift-format b/.swift-format new file mode 100644 index 000000000..41a022f26 --- /dev/null +++ b/.swift-format @@ -0,0 +1,18 @@ +{ + "version": 1, + "lineLength": 120, + "indentation": { + "spaces": 2 + }, + "lineBreakBeforeEachArgument": true, + "indentConditionalCompilationBlocks": false, + "prioritizeKeepingFunctionOutputTogether": true, + "rules": { + "AlwaysUseLowerCamelCase": false, + "AmbiguousTrailingClosureOverload": false, + "NoBlockComments": false, + "OrderedImports": true, + "UseLetInEveryBoundCaseVariable": false, + "UseSynthesizedInitializer": false + } +} From f0eabf80a43832045bd1b5692ca7cadbf38759e9 Mon Sep 17 00:00:00 2001 From: Tony Allevato Date: Tue, 1 Oct 2024 08:27:46 -0400 Subject: [PATCH 2/3] Run swift-format on swift-format. --- Package.swift | 9 +- Plugins/FormatPlugin/plugin.swift | 34 +- Plugins/LintPlugin/plugin.swift | 30 +- Sources/SwiftFormat/API/Configuration.swift | 39 +- Sources/SwiftFormat/API/Indent.swift | 8 +- Sources/SwiftFormat/API/Selection.swift | 3 +- Sources/SwiftFormat/API/SwiftFormatter.swift | 38 +- Sources/SwiftFormat/API/SwiftLinter.swift | 25 +- Sources/SwiftFormat/Core/Context.swift | 5 +- .../Core/DocumentationComment.swift | 5 +- .../Core/DocumentationCommentText.swift | 25 +- Sources/SwiftFormat/Core/FindingEmitter.swift | 4 +- Sources/SwiftFormat/Core/LintPipeline.swift | 9 +- .../Core/ModifierListSyntax+Convenience.swift | 2 +- Sources/SwiftFormat/Core/Rule.swift | 11 +- Sources/SwiftFormat/Core/RuleMask.swift | 12 +- .../Core/SyntaxProtocol+Convenience.swift | 3 +- .../Core/WithSemicolonSyntax.swift | 1 - .../SwiftFormat/PrettyPrint/PrettyPrint.swift | 47 ++- .../PrettyPrint/TokenStreamCreator.swift | 346 +++++++++++------- .../PrettyPrint/WhitespaceLinter.swift | 52 ++- ...waysUseLiteralForEmptyCollectionInit.swift | 56 ++- .../Rules/AlwaysUseLowerCamelCase.swift | 53 ++- .../AmbiguousTrailingClosureOverload.swift | 6 +- ...cumentationCommentWithOneLineSummary.swift | 93 ++--- .../Rules/FileScopedDeclarationPrivacy.swift | 6 +- .../SwiftFormat/Rules/FullyIndirectEnum.swift | 30 +- .../Rules/IdentifiersMustBeASCII.swift | 3 +- ...NeverUseImplicitlyUnwrappedOptionals.swift | 4 +- .../NoAccessLevelOnExtensionDeclaration.swift | 32 +- .../Rules/NoAssignmentInExpressions.swift | 7 +- .../NoEmptyLineOpeningClosingBraces.swift | 30 +- .../NoVoidReturnOnFunctionSignature.swift | 6 +- .../Rules/OmitExplicitReturns.swift | 48 ++- .../Rules/OneVariableDeclarationPerLine.swift | 4 +- .../SwiftFormat/Rules/OrderedImports.swift | 13 +- .../Rules/ReplaceForEachWithForLoop.swift | 5 +- .../Rules/ReturnVoidInsteadOfEmptyTuple.swift | 15 +- .../Rules/TypeNamesShouldBeCapitalized.swift | 5 +- Sources/SwiftFormat/Rules/UseEarlyExits.swift | 6 +- .../UseExplicitNilCheckInConditions.swift | 6 +- .../Rules/UseShorthandTypeNames.swift | 98 +++-- .../Rules/UseSynthesizedInitializer.swift | 23 +- .../Rules/UseWhereClausesInForLoops.swift | 5 +- .../Rules/ValidateDocumentationComments.swift | 23 +- .../SwiftFormat/Utilities/FileIterator.swift | 5 +- .../DiagnosingTestCase.swift | 30 +- .../_SwiftFormatTestSupport/MarkedText.swift | 4 +- .../PipelineGenerator.swift | 42 ++- .../generate-swift-format/RuleCollector.swift | 8 +- .../RuleDocumentationGenerator.swift | 25 +- .../RuleNameCacheGenerator.swift | 1 - Sources/generate-swift-format/main.swift | 15 +- .../Frontend/FormatFrontend.swift | 12 +- Sources/swift-format/Frontend/Frontend.swift | 34 +- .../swift-format/Frontend/LintFrontend.swift | 23 +- .../Subcommands/DumpConfiguration.swift | 6 +- Sources/swift-format/Subcommands/Format.swift | 6 +- Sources/swift-format/Subcommands/Lint.swift | 7 +- .../Subcommands/LintFormatOptions.swift | 41 ++- .../Utilities/DiagnosticsEngine.swift | 22 +- .../swift-format/Utilities/FormatError.swift | 3 +- Sources/swift-format/Utilities/TTY.swift | 14 +- .../WhitespaceLinterPerformanceTests.swift | 12 +- .../Core/DocumentationCommentTests.swift | 25 +- .../Core/DocumentationCommentTextTests.swift | 35 +- .../SwiftFormatTests/Core/RuleMaskTests.swift | 5 +- .../PrettyPrint/ArrayDeclTests.swift | 32 +- .../PrettyPrint/AssignmentExprTests.swift | 176 +++++---- .../PrettyPrint/AttributeTests.swift | 102 +++--- .../PrettyPrint/BinaryOperatorExprTests.swift | 12 +- .../PrettyPrint/ClassDeclTests.swift | 12 +- .../PrettyPrint/ClosureExprTests.swift | 10 +- .../PrettyPrint/CommaTests.swift | 148 ++++---- .../PrettyPrint/CommentTests.swift | 250 ++++++------- .../PrettyPrint/ConsumeExprTests.swift | 3 +- .../PrettyPrint/CopyExprSyntax.swift | 3 +- .../PrettyPrint/DeclNameArgumentTests.swift | 1 - .../PrettyPrint/DeinitializerDeclTests.swift | 2 +- .../PrettyPrint/DictionaryDeclTests.swift | 36 +- .../PrettyPrint/DiscardStmtTests.swift | 3 +- .../PrettyPrint/DoStmtTests.swift | 35 +- .../PrettyPrint/EnumDeclTests.swift | 12 +- .../PrettyPrint/ExtensionDeclTests.swift | 12 +- .../PrettyPrint/FunctionDeclTests.swift | 215 ++++++----- .../PrettyPrint/IfConfigTests.swift | 2 +- .../PrettyPrint/IgnoreNodeTests.swift | 2 +- .../PrettyPrint/InitializerDeclTests.swift | 192 +++++----- .../PrettyPrint/MacroCallTests.swift | 2 +- .../PrettyPrint/MemberAccessExprTests.swift | 69 ++-- .../PrettyPrint/ParameterPackTests.swift | 9 +- .../PrettyPrint/PrettyPrintTestCase.swift | 33 +- .../PrettyPrint/ProtocolDeclTests.swift | 9 +- .../RespectsExistingLineBreaksTests.swift | 56 ++- .../PrettyPrint/SemicolonTests.swift | 20 +- .../PrettyPrint/StringTests.swift | 99 ++--- .../PrettyPrint/StructDeclTests.swift | 8 +- .../PrettyPrint/SubscriptDeclTests.swift | 242 ++++++------ .../PrettyPrint/SubscriptExprTests.swift | 4 +- .../PrettyPrint/SwitchStmtTests.swift | 7 +- .../PrettyPrint/WhitespaceLintTests.swift | 2 +- .../PrettyPrint/WhitespaceTestCase.swift | 16 +- ...icDeclarationsHaveDocumentationTests.swift | 23 +- ...seLiteralForEmptyCollectionInitTests.swift | 3 +- .../Rules/AlwaysUseLowerCamelCaseTests.swift | 10 +- ...mbiguousTrailingClosureOverloadTests.swift | 19 +- .../AvoidRetroactiveConformancesTests.swift | 5 +- ...tationCommentWithOneLineSummaryTests.swift | 119 +++--- .../Rules/DoNotUseSemicolonsTests.swift | 15 +- ...ontRepeatTypeInStaticPropertiesTests.swift | 22 +- .../FileScopedDeclarationPrivacyTests.swift | 12 +- .../Rules/FullyIndirectEnumTests.swift | 7 +- .../Rules/GroupNumericLiteralsTests.swift | 3 +- .../Rules/IdentifiersMustBeASCIITests.swift | 3 +- .../Rules/ImportsXCTestVisitorTests.swift | 48 ++- .../Rules/LintOrFormatRuleTestCase.swift | 47 ++- .../Rules/NeverForceUnwrapTests.swift | 3 +- .../Rules/NeverUseForceTryTests.swift | 5 +- ...UseImplicitlyUnwrappedOptionalsTests.swift | 3 +- ...cessLevelOnExtensionDeclarationTests.swift | 24 +- .../NoAssignmentInExpressionsTests.swift | 19 +- .../Rules/NoBlockCommentsTests.swift | 3 +- .../NoCasesWithOnlyFallthroughTests.swift | 7 +- ...oEmptyLinesOpeningClosingBracesTests.swift | 157 ++++---- ...EmptyTrailingClosureParenthesesTests.swift | 3 +- .../Rules/NoLabelsInCasePatternsTests.swift | 3 +- .../Rules/NoLeadingUnderscoresTests.swift | 7 +- .../Rules/NoParensAroundConditionsTests.swift | 3 +- .../Rules/NoPlaygroundLiteralsTests.swift | 18 +- ...NoVoidReturnOnFunctionSignatureTests.swift | 3 +- .../Rules/OmitReturnsTests.swift | 135 +++---- .../Rules/OneCasePerLineTests.swift | 5 +- .../OneVariableDeclarationPerLineTests.swift | 9 +- .../OnlyOneTrailingClosureArgumentTests.swift | 8 +- .../Rules/OrderedImportsTests.swift | 25 +- .../ReplaceForEachWithForLoopTests.swift | 6 +- .../ReturnVoidInsteadOfEmptyTupleTests.swift | 3 +- .../TypeNamesShouldBeCapitalizedTests.swift | 8 +- .../Rules/UseEarlyExitsTests.swift | 7 +- ...UseExplicitNilCheckInConditionsTests.swift | 5 +- .../UseLetInEveryBoundCaseVariableTests.swift | 128 +++++-- .../Rules/UseShorthandTypeNamesTests.swift | 5 +- .../UseSingleLinePropertyGetterTests.swift | 8 +- .../UseSynthesizedInitializerTests.swift | 48 ++- ...leSlashForDocumentationCommentsTests.swift | 5 +- .../UseWhereClausesInForLoopsTests.swift | 3 +- .../ValidateDocumentationCommentsTests.swift | 19 +- .../Utilities/FileIteratorTests.swift | 17 +- 148 files changed, 2593 insertions(+), 1941 deletions(-) diff --git a/Package.swift b/Package.swift index 4ee03be04..d8c46cb4f 100644 --- a/Package.swift +++ b/Package.swift @@ -18,7 +18,7 @@ let package = Package( name: "swift-format", platforms: [ .macOS("12.0"), - .iOS("13.0") + .iOS("13.0"), ], products: [ .executable( @@ -131,7 +131,7 @@ let package = Package( .product(name: "SwiftSyntax", package: "swift-syntax"), .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), ] - ) + ), ] ) @@ -167,15 +167,12 @@ var dependencies: [Package.Dependency] { } } - - // MARK: - Compute custom build settings -var swiftformatLinkSettings: [LinkerSetting] { +var swiftformatLinkSettings: [LinkerSetting] { if installAction { return [.unsafeFlags(["-no-toolchain-stdlib-rpath"], .when(platforms: [.linux, .android]))] } else { return [] } } - diff --git a/Plugins/FormatPlugin/plugin.swift b/Plugins/FormatPlugin/plugin.swift index 96c77f4d2..66bf3b74e 100644 --- a/Plugins/FormatPlugin/plugin.swift +++ b/Plugins/FormatPlugin/plugin.swift @@ -1,28 +1,27 @@ -import PackagePlugin import Foundation +import PackagePlugin @main struct FormatPlugin { func format(tool: PluginContext.Tool, targetDirectories: [String], configurationFilePath: String?) throws { let swiftFormatExec = URL(fileURLWithPath: tool.path.string) - + var arguments: [String] = ["format"] - + arguments.append(contentsOf: targetDirectories) - + arguments.append(contentsOf: ["--recursive", "--parallel", "--in-place"]) - + if let configurationFilePath = configurationFilePath { arguments.append(contentsOf: ["--configuration", configurationFilePath]) } - + let process = try Process.run(swiftFormatExec, arguments: arguments) process.waitUntilExit() - + if process.terminationReason == .exit && process.terminationStatus == 0 { print("Formatted the source code.") - } - else { + } else { let problem = "\(process.terminationReason):\(process.terminationStatus)" Diagnostics.error("swift-format invocation failed: \(problem)") } @@ -35,15 +34,16 @@ extension FormatPlugin: CommandPlugin { arguments: [String] ) async throws { let swiftFormatTool = try context.tool(named: "swift-format") - + var argExtractor = ArgumentExtractor(arguments) let targetNames = argExtractor.extractOption(named: "target") - let targetsToFormat = targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames) - + let targetsToFormat = + targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames) + let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first - - let sourceCodeTargets = targetsToFormat.compactMap{ $0 as? SourceModuleTarget } - + + let sourceCodeTargets = targetsToFormat.compactMap { $0 as? SourceModuleTarget } + try format( tool: swiftFormatTool, targetDirectories: sourceCodeTargets.map(\.directory.string), @@ -58,10 +58,10 @@ import XcodeProjectPlugin extension FormatPlugin: XcodeCommandPlugin { func performCommand(context: XcodeProjectPlugin.XcodePluginContext, arguments: [String]) throws { let swiftFormatTool = try context.tool(named: "swift-format") - + var argExtractor = ArgumentExtractor(arguments) let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first - + try format( tool: swiftFormatTool, targetDirectories: [context.xcodeProject.directory.string], diff --git a/Plugins/LintPlugin/plugin.swift b/Plugins/LintPlugin/plugin.swift index 34644f6db..bb59c34a1 100644 --- a/Plugins/LintPlugin/plugin.swift +++ b/Plugins/LintPlugin/plugin.swift @@ -1,28 +1,27 @@ -import PackagePlugin import Foundation +import PackagePlugin @main struct LintPlugin { func lint(tool: PluginContext.Tool, targetDirectories: [String], configurationFilePath: String?) throws { let swiftFormatExec = URL(fileURLWithPath: tool.path.string) - + var arguments: [String] = ["lint"] - + arguments.append(contentsOf: targetDirectories) - + arguments.append(contentsOf: ["--recursive", "--parallel", "--strict"]) - + if let configurationFilePath = configurationFilePath { arguments.append(contentsOf: ["--configuration", configurationFilePath]) } - + let process = try Process.run(swiftFormatExec, arguments: arguments) process.waitUntilExit() - + if process.terminationReason == .exit && process.terminationStatus == 0 { print("Linted the source code.") - } - else { + } else { let problem = "\(process.terminationReason):\(process.terminationStatus)" Diagnostics.error("swift-format invocation failed: \(problem)") } @@ -35,16 +34,17 @@ extension LintPlugin: CommandPlugin { arguments: [String] ) async throws { let swiftFormatTool = try context.tool(named: "swift-format") - + // Extract the arguments that specify what targets to format. var argExtractor = ArgumentExtractor(arguments) let targetNames = argExtractor.extractOption(named: "target") - - let targetsToFormat = targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames) + + let targetsToFormat = + targetNames.isEmpty ? context.package.targets : try context.package.targets(named: targetNames) let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first - + let sourceCodeTargets = targetsToFormat.compactMap { $0 as? SourceModuleTarget } - + try lint( tool: swiftFormatTool, targetDirectories: sourceCodeTargets.map(\.directory.string), @@ -61,7 +61,7 @@ extension LintPlugin: XcodeCommandPlugin { let swiftFormatTool = try context.tool(named: "swift-format") var argExtractor = ArgumentExtractor(arguments) let configurationFilePath = argExtractor.extractOption(named: "swift-format-configuration").first - + try lint( tool: swiftFormatTool, targetDirectories: [context.xcodeProject.directory.string], diff --git a/Sources/SwiftFormat/API/Configuration.swift b/Sources/SwiftFormat/API/Configuration.swift index 531461a57..e1584a5c5 100644 --- a/Sources/SwiftFormat/API/Configuration.swift +++ b/Sources/SwiftFormat/API/Configuration.swift @@ -278,9 +278,11 @@ public struct Configuration: Codable, Equatable { self.version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 1 guard version <= highestSupportedConfigurationVersion else { throw DecodingError.dataCorruptedError( - forKey: .version, in: container, + forKey: .version, + in: container, debugDescription: - "This version of the formatter does not support configuration version \(version).") + "This version of the formatter does not support configuration version \(version)." + ) } // If we ever introduce a new version, this is where we should switch on the decoded version @@ -328,30 +330,40 @@ public struct Configuration: Codable, Equatable { ?? defaults.prioritizeKeepingFunctionOutputTogether self.indentConditionalCompilationBlocks = try container.decodeIfPresent(Bool.self, forKey: .indentConditionalCompilationBlocks) - ?? defaults.indentConditionalCompilationBlocks + ?? defaults.indentConditionalCompilationBlocks self.lineBreakAroundMultilineExpressionChainComponents = try container.decodeIfPresent( - Bool.self, forKey: .lineBreakAroundMultilineExpressionChainComponents) + Bool.self, + forKey: .lineBreakAroundMultilineExpressionChainComponents + ) ?? defaults.lineBreakAroundMultilineExpressionChainComponents self.spacesAroundRangeFormationOperators = try container.decodeIfPresent( - Bool.self, forKey: .spacesAroundRangeFormationOperators) + Bool.self, + forKey: .spacesAroundRangeFormationOperators + ) ?? defaults.spacesAroundRangeFormationOperators self.fileScopedDeclarationPrivacy = try container.decodeIfPresent( - FileScopedDeclarationPrivacyConfiguration.self, forKey: .fileScopedDeclarationPrivacy) + FileScopedDeclarationPrivacyConfiguration.self, + forKey: .fileScopedDeclarationPrivacy + ) ?? defaults.fileScopedDeclarationPrivacy self.indentSwitchCaseLabels = try container.decodeIfPresent(Bool.self, forKey: .indentSwitchCaseLabels) - ?? defaults.indentSwitchCaseLabels + ?? defaults.indentSwitchCaseLabels self.noAssignmentInExpressions = try container.decodeIfPresent( - NoAssignmentInExpressionsConfiguration.self, forKey: .noAssignmentInExpressions) + NoAssignmentInExpressionsConfiguration.self, + forKey: .noAssignmentInExpressions + ) ?? defaults.noAssignmentInExpressions self.multiElementCollectionTrailingCommas = try container.decodeIfPresent( - Bool.self, forKey: .multiElementCollectionTrailingCommas) - ?? defaults.multiElementCollectionTrailingCommas + Bool.self, + forKey: .multiElementCollectionTrailingCommas + ) + ?? defaults.multiElementCollectionTrailingCommas self.reflowMultilineStringLiterals = try container.decodeIfPresent(MultilineStringReflowBehavior.self, forKey: .reflowMultilineStringLiterals) @@ -384,9 +396,12 @@ public struct Configuration: Codable, Equatable { try container.encode(lineBreakBetweenDeclarationAttributes, forKey: .lineBreakBetweenDeclarationAttributes) try container.encode( lineBreakAroundMultilineExpressionChainComponents, - forKey: .lineBreakAroundMultilineExpressionChainComponents) + forKey: .lineBreakAroundMultilineExpressionChainComponents + ) try container.encode( - spacesAroundRangeFormationOperators, forKey: .spacesAroundRangeFormationOperators) + spacesAroundRangeFormationOperators, + forKey: .spacesAroundRangeFormationOperators + ) try container.encode(fileScopedDeclarationPrivacy, forKey: .fileScopedDeclarationPrivacy) try container.encode(indentSwitchCaseLabels, forKey: .indentSwitchCaseLabels) try container.encode(noAssignmentInExpressions, forKey: .noAssignmentInExpressions) diff --git a/Sources/SwiftFormat/API/Indent.swift b/Sources/SwiftFormat/API/Indent.swift index c8ca49c5c..5039da135 100644 --- a/Sources/SwiftFormat/API/Indent.swift +++ b/Sources/SwiftFormat/API/Indent.swift @@ -36,7 +36,9 @@ public enum Indent: Hashable, Codable { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: decoder.codingPath, - debugDescription: "Only one of \"tabs\" or \"spaces\" may be specified")) + debugDescription: "Only one of \"tabs\" or \"spaces\" may be specified" + ) + ) } if let spacesCount = spacesCount { self = .spaces(spacesCount) @@ -50,7 +52,9 @@ public enum Indent: Hashable, Codable { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: decoder.codingPath, - debugDescription: "One of \"tabs\" or \"spaces\" must be specified")) + debugDescription: "One of \"tabs\" or \"spaces\" must be specified" + ) + ) } public func encode(to encoder: Encoder) throws { diff --git a/Sources/SwiftFormat/API/Selection.swift b/Sources/SwiftFormat/API/Selection.swift index 9ea599db3..2e7d00109 100644 --- a/Sources/SwiftFormat/API/Selection.swift +++ b/Sources/SwiftFormat/API/Selection.swift @@ -24,7 +24,7 @@ public enum Selection { self = .infinite } else { let ranges = offsetRanges.map { - AbsolutePosition(utf8Offset: $0.lowerBound) ..< AbsolutePosition(utf8Offset: $0.upperBound) + AbsolutePosition(utf8Offset: $0.lowerBound).. Bool { diff --git a/Sources/SwiftFormat/API/SwiftFormatter.swift b/Sources/SwiftFormat/API/SwiftFormatter.swift index e91030b3c..0daeb22c6 100644 --- a/Sources/SwiftFormat/API/SwiftFormatter.swift +++ b/Sources/SwiftFormat/API/SwiftFormatter.swift @@ -72,7 +72,8 @@ public final class SwiftFormatter { assumingFileURL: url, selection: .infinite, to: &outputStream, - parsingDiagnosticHandler: parsingDiagnosticHandler) + parsingDiagnosticHandler: parsingDiagnosticHandler + ) } /// Formats the given Swift source code and writes the result to an output stream. @@ -109,10 +110,16 @@ public final class SwiftFormatter { source: source, operatorTable: .standardOperators, assumingFileURL: url, - parsingDiagnosticHandler: parsingDiagnosticHandler) + parsingDiagnosticHandler: parsingDiagnosticHandler + ) try format( - syntax: sourceFile, source: source, operatorTable: .standardOperators, assumingFileURL: url, - selection: selection, to: &outputStream) + syntax: sourceFile, + source: source, + operatorTable: .standardOperators, + assumingFileURL: url, + selection: selection, + to: &outputStream + ) } /// Formats the given Swift syntax tree and writes the result to an output stream. @@ -137,14 +144,24 @@ public final class SwiftFormatter { /// be written. /// - Throws: If an unrecoverable error occurs when formatting the code. public func format( - syntax: SourceFileSyntax, source: String, operatorTable: OperatorTable, - assumingFileURL url: URL?, selection: Selection, to outputStream: inout Output + syntax: SourceFileSyntax, + source: String, + operatorTable: OperatorTable, + assumingFileURL url: URL?, + selection: Selection, + to outputStream: inout Output ) throws { let assumedURL = url ?? URL(fileURLWithPath: "source") let context = Context( - configuration: configuration, operatorTable: operatorTable, findingConsumer: findingConsumer, - fileURL: assumedURL, selection: selection, sourceFileSyntax: syntax, source: source, - ruleNameCache: ruleNameCache) + configuration: configuration, + operatorTable: operatorTable, + findingConsumer: findingConsumer, + fileURL: assumedURL, + selection: selection, + sourceFileSyntax: syntax, + source: source, + ruleNameCache: ruleNameCache + ) let pipeline = FormatPipeline(context: context) let transformedSyntax = pipeline.rewrite(Syntax(syntax)) @@ -158,7 +175,8 @@ public final class SwiftFormatter { source: source, node: transformedSyntax, printTokenStream: debugOptions.contains(.dumpTokenStream), - whitespaceOnly: false) + whitespaceOnly: false + ) outputStream.write(printer.prettyPrint()) } } diff --git a/Sources/SwiftFormat/API/SwiftLinter.swift b/Sources/SwiftFormat/API/SwiftLinter.swift index 79568e2cb..25cfa2af1 100644 --- a/Sources/SwiftFormat/API/SwiftLinter.swift +++ b/Sources/SwiftFormat/API/SwiftLinter.swift @@ -67,7 +67,8 @@ public final class SwiftLinter { try lint( source: String(contentsOf: url, encoding: .utf8), assumingFileURL: url, - parsingDiagnosticHandler: parsingDiagnosticHandler) + parsingDiagnosticHandler: parsingDiagnosticHandler + ) } /// Lints the given Swift source code. @@ -97,9 +98,14 @@ public final class SwiftLinter { source: source, operatorTable: .standardOperators, assumingFileURL: url, - parsingDiagnosticHandler: parsingDiagnosticHandler) + parsingDiagnosticHandler: parsingDiagnosticHandler + ) try lint( - syntax: sourceFile, operatorTable: .standardOperators, assumingFileURL: url, source: source) + syntax: sourceFile, + operatorTable: .standardOperators, + assumingFileURL: url, + source: source + ) } /// Lints the given Swift syntax tree. @@ -133,8 +139,14 @@ public final class SwiftLinter { source: String ) throws { let context = Context( - configuration: configuration, operatorTable: operatorTable, findingConsumer: findingConsumer, - fileURL: url, sourceFileSyntax: syntax, source: source, ruleNameCache: ruleNameCache) + configuration: configuration, + operatorTable: operatorTable, + findingConsumer: findingConsumer, + fileURL: url, + sourceFileSyntax: syntax, + source: source, + ruleNameCache: ruleNameCache + ) let pipeline = LintPipeline(context: context) pipeline.walk(Syntax(syntax)) @@ -149,7 +161,8 @@ public final class SwiftLinter { source: source, node: Syntax(syntax), printTokenStream: debugOptions.contains(.dumpTokenStream), - whitespaceOnly: true) + whitespaceOnly: true + ) let formatted = printer.prettyPrint() let ws = WhitespaceLinter(user: syntax.description, formatted: formatted, context: context) ws.lint() diff --git a/Sources/SwiftFormat/Core/Context.swift b/Sources/SwiftFormat/Core/Context.swift index 2bbb900ac..e00e38b20 100644 --- a/Sources/SwiftFormat/Core/Context.swift +++ b/Sources/SwiftFormat/Core/Context.swift @@ -12,8 +12,8 @@ import Foundation import SwiftOperators -import SwiftSyntax import SwiftParser +import SwiftSyntax /// Context contains the bits that each formatter and linter will need access to. /// @@ -102,7 +102,8 @@ public final class Context { """ Missing cached rule name for '\(rule)'! \ Ensure `generate-swift-format` has been run and `ruleNameCache` was injected. - """) + """ + ) let ruleName = ruleNameCache[ObjectIdentifier(rule)] ?? R.ruleName switch ruleMask.ruleState(ruleName, at: loc) { diff --git a/Sources/SwiftFormat/Core/DocumentationComment.swift b/Sources/SwiftFormat/Core/DocumentationComment.swift index 4aa0d601b..d89b4c1c6 100644 --- a/Sources/SwiftFormat/Core/DocumentationComment.swift +++ b/Sources/SwiftFormat/Core/DocumentationComment.swift @@ -216,7 +216,8 @@ public struct DocumentationComment { ) -> Parameter? { var rewriter = ParameterOutlineMarkupRewriter( origin: listItem, - expectParameterLabel: expectParameterLabel) + expectParameterLabel: expectParameterLabel + ) guard let newListItem = listItem.accept(&rewriter) as? ListItem, let name = rewriter.parameterName @@ -275,7 +276,7 @@ private struct ParameterOutlineMarkupRewriter: MarkupRewriter { guard listItem.isIdentical(to: origin) else { return listItem } return defaultVisit(listItem) } - + mutating func visitParagraph(_ paragraph: Paragraph) -> Markup? { // Only recurse into the first paragraph in the list item. guard paragraph.indexInParent == 0 else { return paragraph } diff --git a/Sources/SwiftFormat/Core/DocumentationCommentText.swift b/Sources/SwiftFormat/Core/DocumentationCommentText.swift index 32dd82a18..7ee21b7ba 100644 --- a/Sources/SwiftFormat/Core/DocumentationCommentText.swift +++ b/Sources/SwiftFormat/Core/DocumentationCommentText.swift @@ -157,7 +157,8 @@ public struct DocumentationCommentText { private func indentationDistance(of text: Substring) -> Int { return text.distance( from: text.startIndex, - to: text.firstIndex { !$0.isWhitespace } ?? text.endIndex) + to: text.firstIndex { !$0.isWhitespace } ?? text.endIndex + ) } /// Returns the number of contiguous whitespace characters (spaces and tabs only) that precede the @@ -215,18 +216,16 @@ private func findCommentStartIndex(_ triviaArray: Array) -> Array( - _ visitor: (Rule) -> (Node) -> SyntaxVisitorContinueKind, for node: Node + _ visitor: (Rule) -> (Node) -> SyntaxVisitorContinueKind, + for node: Node ) { guard context.shouldFormat(Rule.self, node: Syntax(node)) else { return } let ruleId = ObjectIdentifier(Rule.self) @@ -48,7 +49,8 @@ extension LintPipeline { /// - node: The syntax node on which the rule will be applied. This lets us check whether the /// rule is enabled for the particular source range where the node occurs. func visitIfEnabled( - _ visitor: (Rule) -> (Node) -> Any, for node: Node + _ visitor: (Rule) -> (Node) -> Any, + for node: Node ) { // Note that visitor function type is expressed as `Any` because we ignore the return value, but // more importantly because the `visit` methods return protocol refinements of `Syntax` that @@ -66,7 +68,8 @@ extension LintPipeline { /// - rule: The type of the syntax rule we're cleaning up. /// - node: The syntax node htat our traversal has left. func onVisitPost( - rule: R.Type, for node: Node + rule: R.Type, + for node: Node ) { let rule = ObjectIdentifier(rule) if case .some(let skipNode) = self.shouldSkipChildren[rule] { diff --git a/Sources/SwiftFormat/Core/ModifierListSyntax+Convenience.swift b/Sources/SwiftFormat/Core/ModifierListSyntax+Convenience.swift index b1e58cc12..043f3b893 100644 --- a/Sources/SwiftFormat/Core/ModifierListSyntax+Convenience.swift +++ b/Sources/SwiftFormat/Core/ModifierListSyntax+Convenience.swift @@ -18,7 +18,7 @@ extension DeclModifierListSyntax { for modifier in self { switch modifier.name.tokenKind { case .keyword(.public), .keyword(.private), .keyword(.fileprivate), .keyword(.internal), - .keyword(.package): + .keyword(.package): return modifier default: continue diff --git a/Sources/SwiftFormat/Core/Rule.swift b/Sources/SwiftFormat/Core/Rule.swift index 5994ea76e..368c7087e 100644 --- a/Sources/SwiftFormat/Core/Rule.swift +++ b/Sources/SwiftFormat/Core/Rule.swift @@ -73,10 +73,14 @@ extension Rule { syntaxLocation = node.startLocation(converter: context.sourceLocationConverter) case .leadingTrivia(let index): syntaxLocation = node.startLocation( - ofLeadingTriviaAt: index, converter: context.sourceLocationConverter) + ofLeadingTriviaAt: index, + converter: context.sourceLocationConverter + ) case .trailingTrivia(let index): syntaxLocation = node.startLocation( - ofTrailingTriviaAt: index, converter: context.sourceLocationConverter) + ofTrailingTriviaAt: index, + converter: context.sourceLocationConverter + ) } } else { syntaxLocation = nil @@ -87,6 +91,7 @@ extension Rule { message, category: category, location: syntaxLocation.flatMap(Finding.Location.init), - notes: notes) + notes: notes + ) } } diff --git a/Sources/SwiftFormat/Core/RuleMask.swift b/Sources/SwiftFormat/Core/RuleMask.swift index b08a6942b..9edf2449c 100644 --- a/Sources/SwiftFormat/Core/RuleMask.swift +++ b/Sources/SwiftFormat/Core/RuleMask.swift @@ -154,7 +154,10 @@ fileprivate class RuleStatusCollectionVisitor: SyntaxVisitor { } let sourceRange = node.sourceRange( - converter: sourceLocationConverter, afterLeadingTrivia: false, afterTrailingTrivia: true) + converter: sourceLocationConverter, + afterLeadingTrivia: false, + afterTrailingTrivia: true + ) allRulesIgnoredRanges.append(sourceRange) return .skipChildren } @@ -181,9 +184,10 @@ fileprivate class RuleStatusCollectionVisitor: SyntaxVisitor { /// - Parameters: /// - token: A token that may have comments that modify the status of rules. /// - node: The node to which the token belongs. - private func appendRuleStatusDirectives(from token: TokenSyntax, of node: Syntax) - -> SyntaxVisitorContinueKind - { + private func appendRuleStatusDirectives( + from token: TokenSyntax, + of node: Syntax + ) -> SyntaxVisitorContinueKind { let isFirstInFile = token.previousToken(viewMode: .sourceAccurate) == nil let matches = loneLineComments(in: token.leadingTrivia, isFirstToken: isFirstInFile) .compactMap(ruleStatusDirectiveMatch) diff --git a/Sources/SwiftFormat/Core/SyntaxProtocol+Convenience.swift b/Sources/SwiftFormat/Core/SyntaxProtocol+Convenience.swift index 94147ef05..d359a1b23 100644 --- a/Sources/SwiftFormat/Core/SyntaxProtocol+Convenience.swift +++ b/Sources/SwiftFormat/Core/SyntaxProtocol+Convenience.swift @@ -155,7 +155,8 @@ extension SyntaxProtocol { var parent = self.parent while let existingParent = parent { if let functionDecl = existingParent.as(FunctionDeclSyntax.self), - functionDecl.hasAttribute("Test", inModule: "Testing") { + functionDecl.hasAttribute("Test", inModule: "Testing") + { return true } parent = existingParent.parent diff --git a/Sources/SwiftFormat/Core/WithSemicolonSyntax.swift b/Sources/SwiftFormat/Core/WithSemicolonSyntax.swift index 1f9a3d2d3..42ac7ce42 100644 --- a/Sources/SwiftFormat/Core/WithSemicolonSyntax.swift +++ b/Sources/SwiftFormat/Core/WithSemicolonSyntax.swift @@ -29,4 +29,3 @@ extension SyntaxProtocol { return self.asProtocol(WithSemicolonSyntax.self) != nil } } - diff --git a/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift b/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift index 8ad1c04c9..f9e9246e5 100644 --- a/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift +++ b/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import SwiftSyntax import Foundation +import SwiftSyntax /// PrettyPrinter takes a Syntax node and outputs a well-formatted, re-indented reproduction of the /// code as a String. @@ -151,7 +151,8 @@ public class PrettyPrinter { private var currentIndentation: [Indent] { let indentation = configuration.indentation var totalIndentation: [Indent] = activeOpenBreaks.flatMap { (open) -> [Indent] in - let count = (open.contributesBlockIndent ? 1 : 0) + let count = + (open.contributesBlockIndent ? 1 : 0) + (open.contributesContinuationIndent ? 1 : 0) return Array(repeating: indentation, count: count) } @@ -187,11 +188,15 @@ public class PrettyPrinter { self.tokens = node.makeTokenStream( configuration: configuration, selection: context.selection, - operatorTable: context.operatorTable) + operatorTable: context.operatorTable + ) self.maxLineLength = configuration.lineLength self.printTokenStream = printTokenStream self.whitespaceOnly = whitespaceOnly - self.outputBuffer = PrettyPrintBuffer(maximumBlankLines: configuration.maximumBlankLines, tabWidth: configuration.tabWidth) + self.outputBuffer = PrettyPrintBuffer( + maximumBlankLines: configuration.maximumBlankLines, + tabWidth: configuration.tabWidth + ) } /// Print out the provided token, and apply line-wrapping and indentation as needed. @@ -274,7 +279,8 @@ public class PrettyPrinter { // lines within it (unless they are themselves continuations within that particular // scope), so we need the continuation indentation to persist across all the lines in that // scope. Additionally, continuation open breaks must indent when the break fires. - let continuationBreakWillFire = openKind == .continuation + let continuationBreakWillFire = + openKind == .continuation && (outputBuffer.isAtStartOfLine || !canFit(length) || mustBreak) let contributesContinuationIndent = currentLineIsContinuation || continuationBreakWillFire @@ -284,7 +290,9 @@ public class PrettyPrinter { kind: openKind, lineNumber: currentLineNumber, contributesContinuationIndent: contributesContinuationIndent, - contributesBlockIndent: openKind == .block)) + contributesBlockIndent: openKind == .block + ) + ) continuationStack.append(currentLineIsContinuation) @@ -298,8 +306,7 @@ public class PrettyPrinter { fatalError("Unmatched closing break") } - let openedOnDifferentLine - = openCloseBreakCompensatingLineNumber != matchingOpenBreak.lineNumber + let openedOnDifferentLine = openCloseBreakCompensatingLineNumber != matchingOpenBreak.lineNumber if matchingOpenBreak.contributesBlockIndent { // The actual line number is used, instead of the compensating line number. When the close @@ -350,12 +357,14 @@ public class PrettyPrinter { // // Likewise, we need to do this if we popped an old continuation state off the stack, // even if the break *doesn't* fire. - let matchingOpenBreakIndented = matchingOpenBreak.contributesContinuationIndent + let matchingOpenBreakIndented = + matchingOpenBreak.contributesContinuationIndent || matchingOpenBreak.contributesBlockIndent currentLineIsContinuation = matchingOpenBreakIndented && openedOnDifferentLine } - let wasContinuationWhenOpened = (continuationStack.popLast() ?? false) + let wasContinuationWhenOpened = + (continuationStack.popLast() ?? false) || matchingOpenBreak.contributesContinuationIndent // This ensures a continuation indent is propagated to following scope when an initial // scope would've indented if the leading break wasn't at the start of a line. @@ -499,7 +508,8 @@ public class PrettyPrinter { // We never want to add a trailing comma in an initializer so we disable trailing commas on // single element collections. let shouldHaveTrailingComma = - startLineNumber != openCloseBreakCompensatingLineNumber && !isSingleElement && configuration.multiElementCollectionTrailingCommas + startLineNumber != openCloseBreakCompensatingLineNumber && !isSingleElement + && configuration.multiElementCollectionTrailingCommas if shouldHaveTrailingComma && !hasTrailingComma { diagnose(.addTrailingComma, category: .trailingComma) } else if !shouldHaveTrailingComma && hasTrailingComma { @@ -526,7 +536,9 @@ public class PrettyPrinter { var text = String(source[start.. SyntaxVisitorContinueKind { - let catchPrecedingBreak = config.lineBreakBeforeControlFlowKeywords + let catchPrecedingBreak = + config.lineBreakBeforeControlFlowKeywords ? Token.break(.same, newlines: .soft) : Token.space before(node.catchKeyword, tokens: catchPrecedingBreak) @@ -960,7 +975,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { let endToken = Token.commaDelimitedRegionEnd( hasTrailingComma: lastElement.trailingComma != nil, - isSingleElement: node.first == lastElement) + isSingleElement: node.first == lastElement + ) after(lastElement.expression.lastToken(viewMode: .sourceAccurate), tokens: [endToken]) } return .visitChildren @@ -1003,7 +1019,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { let endToken = Token.commaDelimitedRegionEnd( hasTrailingComma: lastElement.trailingComma != nil, - isSingleElement: node.first == node.last) + isSingleElement: node.first == node.last + ) after(lastElement.lastToken(viewMode: .sourceAccurate), tokens: endToken) } return .visitChildren @@ -1054,8 +1071,11 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { // When this function call is wrapped by a try-expr or await-expr, the group applied when // visiting that wrapping expression is sufficient. Adding another group here in that case // can result in unnecessarily breaking after the try/await keyword. - if !(base.firstToken(viewMode: .sourceAccurate)?.previousToken(viewMode: .all)?.parent?.is(TryExprSyntax.self) ?? false - || base.firstToken(viewMode: .sourceAccurate)?.previousToken(viewMode: .all)?.parent?.is(AwaitExprSyntax.self) ?? false) { + if !(base.firstToken(viewMode: .sourceAccurate)?.previousToken(viewMode: .all)?.parent?.is(TryExprSyntax.self) + ?? false + || base.firstToken(viewMode: .sourceAccurate)?.previousToken(viewMode: .all)?.parent?.is(AwaitExprSyntax.self) + ?? false) + { before(base.firstToken(viewMode: .sourceAccurate), tokens: .open) after(calledMemberAccessExpr.declName.baseName.lastToken(viewMode: .sourceAccurate), tokens: .close) } @@ -1072,13 +1092,15 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before( node.trailingClosure?.leftBrace, - tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true)) + ) arrangeFunctionCallArgumentList( arguments, leftDelimiter: node.leftParen, rightDelimiter: node.rightParen, - forcesBreakBeforeRightDelimiter: breakBeforeRightParen) + forcesBreakBeforeRightDelimiter: breakBeforeRightParen + ) return .visitChildren } @@ -1087,9 +1109,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { clearContextualBreakState(node) } - override func visit(_ node: MultipleTrailingClosureElementSyntax) - -> SyntaxVisitorContinueKind - { + override func visit( + _ node: MultipleTrailingClosureElementSyntax + ) -> SyntaxVisitorContinueKind { before(node.label, tokens: .space) after(node.colon, tokens: .space) return .visitChildren @@ -1114,7 +1136,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { if !arguments.isEmpty { var afterLeftDelimiter: [Token] = [.break(.open, size: 0)] var beforeRightDelimiter: [Token] = [ - .break(.close(mustBreak: forcesBreakBeforeRightDelimiter), size: 0), + .break(.close(mustBreak: forcesBreakBeforeRightDelimiter), size: 0) ] if shouldGroupAroundArgumentList(arguments) { @@ -1203,7 +1225,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { of: node, contentsKeyPath: \.statements, shouldResetBeforeLeftBrace: false, - openBraceNewlineBehavior: newlineBehavior) + openBraceNewlineBehavior: newlineBehavior + ) } return .visitChildren } @@ -1217,7 +1240,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before(node.firstToken(viewMode: .sourceAccurate), tokens: .open) arrangeAttributeList( - node.attributes, suppressFinalBreak: node.parameterClause == nil && node.capture == nil) + node.attributes, + suppressFinalBreak: node.parameterClause == nil && node.capture == nil + ) if let parameterClause = node.parameterClause { // We unconditionally put a break before the `in` keyword below, so we should only put a break @@ -1240,7 +1265,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { // Since the output clause is optional but the in-token is required, placing the .close // before `inTok` ensures the close gets into the token stream. before(node.inKeyword, tokens: .close) - } else { + } else { // Group outside of the parens, so that the argument list together, preferring to break // between the argument list and the output. before(parameterClause.firstToken(viewMode: .sourceAccurate), tokens: .open) @@ -1300,13 +1325,15 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before( node.trailingClosure?.leftBrace, - tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true)) + ) arrangeFunctionCallArgumentList( arguments, leftDelimiter: node.leftSquare, rightDelimiter: node.rightSquare, - forcesBreakBeforeRightDelimiter: breakBeforeRightBracket) + forcesBreakBeforeRightDelimiter: breakBeforeRightBracket + ) return .visitChildren } @@ -1329,13 +1356,15 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before( node.trailingClosure?.leftBrace, - tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true)) + ) arrangeFunctionCallArgumentList( node.arguments, leftDelimiter: node.leftParen, rightDelimiter: node.rightParen, - forcesBreakBeforeRightDelimiter: false) + forcesBreakBeforeRightDelimiter: false + ) return .visitChildren } @@ -1350,13 +1379,15 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before( node.trailingClosure?.leftBrace, - tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.same, newlines: .elective(ignoresDiscretionary: true)) + ) arrangeFunctionCallArgumentList( arguments, leftDelimiter: node.leftParen, rightDelimiter: node.rightParen, - forcesBreakBeforeRightDelimiter: breakBeforeRightParen) + forcesBreakBeforeRightDelimiter: breakBeforeRightParen + ) return .visitChildren } @@ -1393,7 +1424,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { arrangeAttributeList(node.attributes) before( node.secondName, - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) after(node.colon, tokens: .break) if let trailingComma = node.trailingComma { @@ -1408,7 +1440,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before(node.firstToken(viewMode: .sourceAccurate), tokens: .open) before( node.secondName, - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) after(node.colon, tokens: .break) if let trailingComma = node.trailingComma { @@ -1424,7 +1457,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { arrangeAttributeList(node.attributes) before( node.secondName, - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) after(node.colon, tokens: .break) if let trailingComma = node.trailingComma { @@ -1497,10 +1531,13 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { if !isNestedInPostfixIfConfig(node: Syntax(node)), let condition = node.condition { before( condition.firstToken(viewMode: .sourceAccurate), - tokens: .printerControl(kind: .disableBreaking(allowDiscretionary: true))) + tokens: .printerControl(kind: .disableBreaking(allowDiscretionary: true)) + ) after( condition.lastToken(viewMode: .sourceAccurate), - tokens: .printerControl(kind: .enableBreaking), .break(.reset, size: 0)) + tokens: .printerControl(kind: .enableBreaking), + .break(.reset, size: 0) + ) } return .visitChildren @@ -1518,7 +1555,11 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { let newlines: NewlineBehavior = item != node.last && shouldInsertNewline(basedOn: item.semicolon) ? .soft : .elective let resetSize = item.semicolon != nil ? 1 : 0 - after(item.lastToken(viewMode: .sourceAccurate), tokens: .close, .break(.reset, size: resetSize, newlines: newlines)) + after( + item.lastToken(viewMode: .sourceAccurate), + tokens: .close, + .break(.reset, size: resetSize, newlines: newlines) + ) } return .visitChildren } @@ -1560,7 +1601,11 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { override func visit(_ node: OperatorPrecedenceAndTypesSyntax) -> SyntaxVisitorContinueKind { before(node.colon, tokens: .space) after(node.colon, tokens: .break(.open), .open) - after(node.designatedTypes.lastToken(viewMode: .sourceAccurate) ?? node.lastToken(viewMode: .sourceAccurate), tokens: .break(.close, size: 0), .close) + after( + node.designatedTypes.lastToken(viewMode: .sourceAccurate) ?? node.lastToken(viewMode: .sourceAccurate), + tokens: .break(.close, size: 0), + .close + ) return .visitChildren } @@ -1647,7 +1692,11 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { let newlines: NewlineBehavior = item != node.last && shouldInsertNewline(basedOn: item.semicolon) ? .soft : .elective let resetSize = item.semicolon != nil ? 1 : 0 - after(item.lastToken(viewMode: .sourceAccurate), tokens: .close, .break(.reset, size: resetSize, newlines: newlines)) + after( + item.lastToken(viewMode: .sourceAccurate), + tokens: .close, + .break(.reset, size: resetSize, newlines: newlines) + ) } return .visitChildren } @@ -1661,7 +1710,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { // This group applies to a top-level if-stmt so that all of the bodies will have the same // breaking behavior. if let exprStmt = node.item.as(ExpressionStmtSyntax.self), - let ifStmt = exprStmt.expression.as(IfExprSyntax.self) { + let ifStmt = exprStmt.expression.as(IfExprSyntax.self) + { before(ifStmt.conditions.firstToken(viewMode: .sourceAccurate), tokens: .open(.consistent)) after(ifStmt.lastToken(viewMode: .sourceAccurate), tokens: .close) } @@ -1694,7 +1744,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { before(node.firstToken(viewMode: .sourceAccurate), tokens: .open) before( node.secondName, - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) after(node.colon, tokens: .break) if let trailingComma = node.trailingComma { @@ -1726,7 +1777,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { override func visit(_ node: TryExprSyntax) -> SyntaxVisitorContinueKind { before( node.expression.firstToken(viewMode: .sourceAccurate), - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) // Check for an anchor token inside of the expression to group with the try keyword. if let anchorToken = findTryAwaitExprConnectingToken(inExpr: node.expression) { @@ -1740,7 +1792,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { override func visit(_ node: AwaitExprSyntax) -> SyntaxVisitorContinueKind { before( node.expression.firstToken(viewMode: .sourceAccurate), - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) // Check for an anchor token inside of the expression to group with the await keyword. if !(node.parent?.is(TryExprSyntax.self) ?? false), @@ -1766,8 +1819,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { if let callingExpr = expr.asProtocol(CallingExprSyntaxProtocol.self) { return findTryAwaitExprConnectingToken(inExpr: callingExpr.calledExpression) } - if let memberAccessExpr = expr.as(MemberAccessExprSyntax.self), let base = memberAccessExpr.base - { + if let memberAccessExpr = expr.as(MemberAccessExprSyntax.self), let base = memberAccessExpr.base { // When there's a simple base (i.e. identifier), group the entire `try/await .` // sequence. This check has to happen here so that the `MemberAccessExprSyntax.name` is // available. @@ -1795,7 +1847,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { argumentList, leftDelimiter: leftParen, rightDelimiter: rightParen, - forcesBreakBeforeRightDelimiter: false) + forcesBreakBeforeRightDelimiter: false + ) } case .some: // Wrap the attribute's arguments in their own group, so arguments stay together with a higher @@ -1854,9 +1907,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { return .visitChildren } - override func visit(_ node: PlatformVersionItemListSyntax) - -> SyntaxVisitorContinueKind - { + override func visit( + _ node: PlatformVersionItemListSyntax + ) -> SyntaxVisitorContinueKind { insertTokens(.break(.same, size: 1), betweenElementsOf: node) return .visitChildren } @@ -1871,9 +1924,14 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { override func visit(_ node: BackDeployedAttributeArgumentsSyntax) -> SyntaxVisitorContinueKind { before( node.platforms.firstToken(viewMode: .sourceAccurate), - tokens: .break(.open, size: 1), .open(argumentListConsistency())) + tokens: .break(.open, size: 1), + .open(argumentListConsistency()) + ) after( - node.platforms.lastToken(viewMode: .sourceAccurate), tokens: .break(.close, size: 0), .close) + node.platforms.lastToken(viewMode: .sourceAccurate), + tokens: .break(.close, size: 0), + .close + ) return .visitChildren } @@ -1894,7 +1952,10 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { override func visit(_ node: ImportDeclSyntax) -> SyntaxVisitorContinueKind { // Import declarations should never be wrapped. - before(node.firstToken(viewMode: .sourceAccurate), tokens: .printerControl(kind: .disableBreaking(allowDiscretionary: false))) + before( + node.firstToken(viewMode: .sourceAccurate), + tokens: .printerControl(kind: .disableBreaking(allowDiscretionary: false)) + ) arrangeAttributeList(node.attributes) after(node.importKeyword, tokens: .space) @@ -1936,7 +1997,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { node.arguments, leftDelimiter: node.leftSquare, rightDelimiter: node.rightSquare, - forcesBreakBeforeRightDelimiter: breakBeforeRightParen) + forcesBreakBeforeRightDelimiter: breakBeforeRightParen + ) return .visitChildren } @@ -1961,7 +2023,10 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { after(node.questionMark, tokens: .space) before( node.colon, - tokens: .break(.close(mustBreak: false), size: 0), .break(.open(kind: .continuation)), .open) + tokens: .break(.close(mustBreak: false), size: 0), + .break(.open(kind: .continuation)), + .open + ) after(node.colon, tokens: .space) // When the ternary is wrapped in parens, absorb the closing paren into the ternary's group so @@ -2067,7 +2132,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { } after( unindentingNode.lastToken(viewMode: .sourceAccurate), - tokens: afterTokens) + tokens: afterTokens + ) } else { beforeTokens = [.break(.continue)] } @@ -2153,7 +2219,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { """ SequenceExpr should have already been folded; found at byte offsets \ \(node.position.utf8Offset)..<\(node.endPosition.utf8Offset) - """) + """ + ) } override func visit(_ node: AssignmentExprSyntax) -> SyntaxVisitorContinueKind { @@ -2214,7 +2281,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { if let typeAnnotation = node.typeAnnotation, !typeAnnotation.type.is(MissingTypeSyntax.self) { after( typeAnnotation.colon, - tokens: .break(.open(kind: .continuation), newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.open(kind: .continuation), newlines: .elective(ignoresDiscretionary: true)) + ) closesNeeded += 1 closeAfterToken = typeAnnotation.lastToken(viewMode: .sourceAccurate) } @@ -2305,7 +2373,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { for specifier in node.specifiers { after( specifier.firstToken(viewMode: .sourceAccurate), - tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.continue, newlines: .elective(ignoresDiscretionary: true)) + ) } return .visitChildren } @@ -2514,12 +2583,13 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { // Looks up the correct break kind based on prior context. let stringLiteralParent = node.parent? - .as(StringLiteralSegmentListSyntax.self)? - .parent? - .as(StringLiteralExprSyntax.self) - let breakKind = stringLiteralParent.map { - pendingMultilineStringBreakKinds[$0, default: .same] - } ?? .same + .as(StringLiteralSegmentListSyntax.self)? + .parent? + .as(StringLiteralExprSyntax.self) + let breakKind = + stringLiteralParent.map { + pendingMultilineStringBreakKinds[$0, default: .same] + } ?? .same let isMultiLineString = stringLiteralParent?.openingQuote.tokenKind == .multilineStringQuote @@ -2529,9 +2599,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { let emitSegmentTextTokens = // If our configure reflow behavior is never, always use the single line emit segment text tokens. isMultiLineString && !config.reflowMultilineStringLiterals.isNever - ? { (segment) in self.emitMultilineSegmentTextTokens(breakKind: breakKind, segment: segment) } - // For single line strings we don't allow line breaks, so emit the string as a single `.syntax` token - : { (segment) in self.appendToken(.syntax(String(segment))) } + ? { (segment) in self.emitMultilineSegmentTextTokens(breakKind: breakKind, segment: segment) } + // For single line strings we don't allow line breaks, so emit the string as a single `.syntax` token + : { (segment) in self.appendToken(.syntax(String(segment))) } let segmentText = node.content.text if segmentText.hasSuffix("\n") { @@ -2704,7 +2774,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { if let typeAnnotation = node.typeAnnotation { after( typeAnnotation.colon, - tokens: .break(.open(kind: .continuation), newlines: .elective(ignoresDiscretionary: true))) + tokens: .break(.open(kind: .continuation), newlines: .elective(ignoresDiscretionary: true)) + ) after(typeAnnotation.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false), size: 0)) } @@ -2768,9 +2839,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { return .visitChildren } - override func visit(_ node: DerivativeAttributeArgumentsSyntax) - -> SyntaxVisitorContinueKind - { + override func visit( + _ node: DerivativeAttributeArgumentsSyntax + ) -> SyntaxVisitorContinueKind { // This node encapsulates the entire list of arguments in a `@derivative(...)` or // `@transpose(...)` attribute. before(node.ofLabel, tokens: .open) @@ -2813,7 +2884,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { closeScopeTokens.forEach(appendToken) generateEnableFormattingIfNecessary( - token.positionAfterSkippingLeadingTrivia ..< token.endPositionBeforeTrailingTrivia + token.positionAfterSkippingLeadingTrivia.. (isLineComment: Bool, tokens: [Token]) - { + private func afterTokensForTrailingComment( + _ token: TokenSyntax + ) -> (isLineComment: Bool, tokens: [Token]) { let (_, trailingComments) = partitionTrailingTrivia(token.trailingTrivia) let trivia = Trivia(pieces: trailingComments) @@ -3299,9 +3392,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { /// closing-scope collection. The opening-scope collection contains `.open` and `.break` tokens /// that start a "scope" before the token. The closing-scope collection contains `.close` and /// `.break` tokens that end a "scope" after the token. - private func splitScopingBeforeTokens(of token: TokenSyntax) -> ( - openingScope: [Token], closingScope: [Token] - ) { + private func splitScopingBeforeTokens( + of token: TokenSyntax + ) -> (openingScope: [Token], closingScope: [Token]) { guard let beforeTokens = beforeMap[token] else { return ([], []) } @@ -3381,7 +3474,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { switch piece { case .lineComment(let text): if index > 0 || isStartOfFile { - generateEnableFormattingIfNecessary(position ..< position + piece.sourceLength) + generateEnableFormattingIfNecessary(position.. 0 || isStartOfFile { - generateEnableFormattingIfNecessary(position ..< position + piece.sourceLength) + generateEnableFormattingIfNecessary(position..( - of expr: T, argumentListPath: KeyPath + of expr: T, + argumentListPath: KeyPath ) -> Bool { guard let parent = expr.parent, @@ -3699,7 +3791,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { /// the expression. This is a hand-crafted list of expressions that generally look better when the /// break(s) before the expression fire before breaks inside of the expression. private func maybeGroupAroundSubexpression( - _ expr: ExprSyntax, combiningOperator operatorExpr: ExprSyntax? = nil + _ expr: ExprSyntax, + combiningOperator operatorExpr: ExprSyntax? = nil ) { switch Syntax(expr).kind { case .memberAccessExpr, .subscriptCallExpr: @@ -3839,7 +3932,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { /// alongside the last token of the given node. Any tokens between `node.lastToken` and the /// returned node's `lastToken` are delimiter tokens that shouldn't be preceded by a break. private func outermostEnclosingNode(from node: Syntax) -> Syntax? { - guard let afterToken = node.lastToken(viewMode: .sourceAccurate)?.nextToken(viewMode: .all), closingDelimiterTokens.contains(afterToken) + guard let afterToken = node.lastToken(viewMode: .sourceAccurate)?.nextToken(viewMode: .all), + closingDelimiterTokens.contains(afterToken) else { return nil } @@ -3957,9 +4051,12 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { ) } - if let leftmostExpr = leftmostExpr(of: rhs, ifMatching: { - $0.is(IfExprSyntax.self) || $0.is(SwitchExprSyntax.self) - }) { + if let leftmostExpr = leftmostExpr( + of: rhs, + ifMatching: { + $0.is(IfExprSyntax.self) || $0.is(SwitchExprSyntax.self) + } + ) { return ( unindentingNode: Syntax(leftmostExpr), shouldReset: false, @@ -3986,8 +4083,8 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { if let binaryOperator = operatorExpr.as(BinaryOperatorExprSyntax.self) { let token = binaryOperator.operator if !config.spacesAroundRangeFormationOperators, - let binOp = operatorTable.infixOperator(named: token.text), - let precedenceGroup = binOp.precedenceGroup, precedenceGroup == "RangeFormationPrecedence" + let binOp = operatorTable.infixOperator(named: token.text), + let precedenceGroup = binOp.precedenceGroup, precedenceGroup == "RangeFormationPrecedence" { // We want to omit whitespace around range formation operators if possible. We can't do this // if the token is either preceded by a postfix operator, followed by a prefix operator, or @@ -4028,7 +4125,9 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { // The leading trivia of the next token, after the ignored node, may contain content that // belongs with the ignored node. The trivia extraction that is performed for `lastToken` later // excludes that content so it needs to be extracted and added to the token stream here. - if let next = node.lastToken(viewMode: .sourceAccurate)?.nextToken(viewMode: .all), let trivia = next.leadingTrivia.first { + if let next = node.lastToken(viewMode: .sourceAccurate)?.nextToken(viewMode: .all), + let trivia = next.leadingTrivia.first + { switch trivia { case .lineComment, .blockComment: trivia.write(to: &nodeText) @@ -4070,16 +4169,16 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor { /// tokens. When visiting an expression node, `preVisitInsertingContextualBreaks(_:)` should be /// called instead of this helper. @discardableResult - private func insertContextualBreaks(_ expr: ExprSyntax, isTopLevel: Bool) -> ( - hasCompoundExpression: Bool, hasMemberAccess: Bool - ) { + private func insertContextualBreaks( + _ expr: ExprSyntax, + isTopLevel: Bool + ) -> (hasCompoundExpression: Bool, hasMemberAccess: Bool) { preVisitedExprs.insert(expr.id) if let memberAccessExpr = expr.as(MemberAccessExprSyntax.self) { // When the member access is part of a calling expression, the break before the dot is // inserted when visiting the parent node instead so that the break is inserted before any // scoping tokens (e.g. `contextualBreakingStart`, `open`). - if memberAccessExpr.base != nil && - expr.parent?.isProtocol(CallingExprSyntaxProtocol.self) != true { + if memberAccessExpr.base != nil && expr.parent?.isProtocol(CallingExprSyntaxProtocol.self) != true { before(memberAccessExpr.period, tokens: .break(.contextual, size: 0)) } var hasCompoundExpression = false @@ -4164,8 +4263,7 @@ private func isNestedInPostfixIfConfig(node: Syntax) -> Bool { return false } - if this?.is(IfConfigDeclSyntax.self) == true && - this?.parent?.is(PostfixIfConfigExprSyntax.self) == true { + if this?.is(IfConfigDeclSyntax.self) == true && this?.parent?.is(PostfixIfConfigExprSyntax.self) == true { return true } @@ -4264,9 +4362,9 @@ class CommentMovingRewriter: SyntaxRewriter { /// 2 trivia collections: the trivia that wasn't extracted and should remain in `token`'s leading /// trivia and the trivia that meets the criteria for extraction. /// - Parameter token: A token whose leading trivia should be split to extract line comments. - private func extractLineCommentTrivia(from token: TokenSyntax) -> ( - remainingTrivia: Trivia, extractedTrivia: Trivia - ) { + private func extractLineCommentTrivia( + from token: TokenSyntax + ) -> (remainingTrivia: Trivia, extractedTrivia: Trivia) { var pendingPieces = [TriviaPiece]() var keepWithTokenPieces = [TriviaPiece]() var extractingPieces = [TriviaPiece]() @@ -4320,8 +4418,8 @@ fileprivate func isFormatterIgnorePresent(inTrivia trivia: Trivia, isWholeFile: func isFormatterIgnore(in commentText: String, prefix: String, suffix: String) -> Bool { let trimmed = commentText.dropFirst(prefix.count) - .dropLast(suffix.count) - .trimmingCharacters(in: .whitespaces) + .dropLast(suffix.count) + .trimmingCharacters(in: .whitespaces) let pattern = isWholeFile ? "swift-format-ignore-file" : "swift-format-ignore" return trimmed == pattern } @@ -4365,7 +4463,7 @@ fileprivate func shouldFormatterIgnore(file: SourceFileSyntax) -> Bool { } extension NewlineBehavior { - static func +(lhs: NewlineBehavior, rhs: NewlineBehavior) -> NewlineBehavior { + static func + (lhs: NewlineBehavior, rhs: NewlineBehavior) -> NewlineBehavior { switch (lhs, rhs) { case (.elective, _): // `rhs` is either also elective or a required newline, which overwrites elective. @@ -4406,8 +4504,8 @@ protocol CallingExprSyntaxProtocol: ExprSyntaxProtocol { var calledExpression: ExprSyntax { get } } -extension FunctionCallExprSyntax: CallingExprSyntaxProtocol { } -extension SubscriptCallExprSyntax: CallingExprSyntaxProtocol { } +extension FunctionCallExprSyntax: CallingExprSyntaxProtocol {} +extension SubscriptCallExprSyntax: CallingExprSyntaxProtocol {} extension Syntax { func asProtocol(_: CallingExprSyntaxProtocol.Protocol) -> CallingExprSyntaxProtocol? { diff --git a/Sources/SwiftFormat/PrettyPrint/WhitespaceLinter.swift b/Sources/SwiftFormat/PrettyPrint/WhitespaceLinter.swift index c88c88c5b..c5c5e2ae8 100644 --- a/Sources/SwiftFormat/PrettyPrint/WhitespaceLinter.swift +++ b/Sources/SwiftFormat/PrettyPrint/WhitespaceLinter.swift @@ -59,7 +59,8 @@ public class WhitespaceLinter { assert( safeCodeUnit(at: userWhitespace.endIndex, in: userText) == safeCodeUnit(at: formattedWhitespace.endIndex, in: formattedText), - "Non-whitespace characters do not match") + "Non-whitespace characters do not match" + ) compareWhitespace(userWhitespace: userWhitespace, formattedWhitespace: formattedWhitespace) @@ -82,7 +83,8 @@ public class WhitespaceLinter { /// - formattedWhitespace: A slice of formatted text representing the current span of contiguous /// whitespace that will be compared to the user whitespace. private func compareWhitespace( - userWhitespace: ArraySlice, formattedWhitespace: ArraySlice + userWhitespace: ArraySlice, + formattedWhitespace: ArraySlice ) { // We use a custom-crafted lazy-splitting iterator here instead of the standard // `Collection.split` function because Time Profiler indicated that a very large proportion of @@ -97,7 +99,8 @@ public class WhitespaceLinter { userIndex: userWhitespace.startIndex, formattedIndex: formattedWhitespace.startIndex, userRuns: userRuns, - formattedRuns: formattedRuns) + formattedRuns: formattedRuns + ) // No need to perform any further checks if the whitespace is identical. guard userWhitespace != formattedWhitespace else { return } @@ -135,7 +138,10 @@ public class WhitespaceLinter { // If this isn't the last whitespace run, then it must precede a newline, so we check // for trailing whitespace violations. checkForTrailingWhitespaceErrors( - userIndex: userIndex, userRun: userRun, formattedRun: formattedRun) + userIndex: userIndex, + userRun: userRun, + formattedRun: formattedRun + ) } userIndex += userRun.count + 1 } @@ -152,7 +158,8 @@ public class WhitespaceLinter { checkForIndentationErrors( userIndex: userIndex, userRun: userRunsIterator.latestElement!, - formattedRun: lastFormattedRun) + formattedRun: lastFormattedRun + ) } } @@ -163,7 +170,8 @@ public class WhitespaceLinter { diagnose( .addLinesError(excessFormattedLines), category: .addLines, - utf8Offset: userWhitespace.startIndex) + utf8Offset: userWhitespace.startIndex + ) } } @@ -257,7 +265,9 @@ public class WhitespaceLinter { /// - userRun: A run of whitespace from the user text. /// - formattedRun: A run of whitespace from the formatted text. private func checkForIndentationErrors( - userIndex: Int, userRun: ArraySlice, formattedRun: ArraySlice + userIndex: Int, + userRun: ArraySlice, + formattedRun: ArraySlice ) { guard userRun != formattedRun else { return } @@ -266,7 +276,8 @@ public class WhitespaceLinter { diagnose( .indentationError(expected: expected, actual: actual), category: .indentation, - utf8Offset: userIndex) + utf8Offset: userIndex + ) } /// Compare user and formatted whitespace buffers, and check for trailing whitespace. @@ -276,7 +287,9 @@ public class WhitespaceLinter { /// - userRun: The tokenized user whitespace buffer. /// - formattedRun: The tokenized formatted whitespace buffer. private func checkForTrailingWhitespaceErrors( - userIndex: Int, userRun: ArraySlice, formattedRun: ArraySlice + userIndex: Int, + userRun: ArraySlice, + formattedRun: ArraySlice ) { if userRun != formattedRun { diagnose(.trailingWhitespaceError, category: .trailingWhitespace, utf8Offset: userIndex) @@ -294,7 +307,9 @@ public class WhitespaceLinter { /// - userRun: The tokenized user whitespace buffer. /// - formattedRun: The tokenized formatted whitespace buffer. private func checkForSpacingErrors( - userIndex: Int, userRun: ArraySlice, formattedRun: ArraySlice + userIndex: Int, + userRun: ArraySlice, + formattedRun: ArraySlice ) { guard userRun != formattedRun else { return } @@ -320,11 +335,13 @@ public class WhitespaceLinter { /// - data: The input string. /// - Returns: A slice of `data` that covers the contiguous whitespace starting at the given /// index. - private func contiguousWhitespace(startingAt offset: Int, in data: [UTF8.CodeUnit]) - -> ArraySlice - { - guard let whitespaceEnd = - data[offset...].firstIndex(where: { !UnicodeScalar($0).properties.isWhitespace }) + private func contiguousWhitespace( + startingAt offset: Int, + in data: [UTF8.CodeUnit] + ) -> ArraySlice { + guard + let whitespaceEnd = + data[offset...].firstIndex(where: { !UnicodeScalar($0).properties.isWhitespace }) else { return data[offset..]()` syntax. In call sites that should be replaced with `[]`, /// for initializations use explicit type combined with empty array literal `let _: [] = []` @@ -21,12 +21,13 @@ import SwiftParser /// Lint: Non-literal empty array initialization will yield a lint error. /// Format: All invalid use sites would be related with empty literal (with or without explicit type annotation). @_spi(Rules) -public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { +public final class AlwaysUseLiteralForEmptyCollectionInit: SyntaxFormatRule { public override class var isOptIn: Bool { return true } public override func visit(_ node: PatternBindingSyntax) -> PatternBindingSyntax { guard let initializer = node.initializer, - let type = isRewritable(initializer) else { + let type = isRewritable(initializer) + else { return node } @@ -43,7 +44,8 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { public override func visit(_ param: FunctionParameterSyntax) -> FunctionParameterSyntax { guard let initializer = param.defaultValue, - let type = isRewritable(initializer) else { + let type = isRewritable(initializer) + else { return param } @@ -62,7 +64,8 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { /// Return a type of the collection. public func isRewritable(_ initializer: InitializerClauseSyntax) -> TypeSyntax? { guard let initCall = initializer.value.as(FunctionCallExprSyntax.self), - initCall.arguments.isEmpty else { + initCall.arguments.isEmpty + else { return nil } @@ -77,8 +80,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { return nil } - private func rewrite(_ node: PatternBindingSyntax, - type: ArrayTypeSyntax) -> PatternBindingSyntax { + private func rewrite( + _ node: PatternBindingSyntax, + type: ArrayTypeSyntax + ) -> PatternBindingSyntax { var replacement = node diagnose(node, type: type) @@ -87,8 +92,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { // Drop trailing trivia after pattern because ':' has to appear connected to it. replacement.pattern = node.pattern.with(\.trailingTrivia, []) // Add explicit type annotation: ': []` - replacement.typeAnnotation = .init(type: type.with(\.leadingTrivia, .space) - .with(\.trailingTrivia, .space)) + replacement.typeAnnotation = .init( + type: type.with(\.leadingTrivia, .space) + .with(\.trailingTrivia, .space) + ) } let initializer = node.initializer! @@ -100,8 +107,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { return replacement } - private func rewrite(_ node: PatternBindingSyntax, - type: DictionaryTypeSyntax) -> PatternBindingSyntax { + private func rewrite( + _ node: PatternBindingSyntax, + type: DictionaryTypeSyntax + ) -> PatternBindingSyntax { var replacement = node diagnose(node, type: type) @@ -110,8 +119,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { // Drop trailing trivia after pattern because ':' has to appear connected to it. replacement.pattern = node.pattern.with(\.trailingTrivia, []) // Add explicit type annotation: ': []` - replacement.typeAnnotation = .init(type: type.with(\.leadingTrivia, .space) - .with(\.trailingTrivia, .space)) + replacement.typeAnnotation = .init( + type: type.with(\.leadingTrivia, .space) + .with(\.trailingTrivia, .space) + ) } let initializer = node.initializer! @@ -121,8 +132,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { return replacement } - private func rewrite(_ param: FunctionParameterSyntax, - type: ArrayTypeSyntax) -> FunctionParameterSyntax { + private func rewrite( + _ param: FunctionParameterSyntax, + type: ArrayTypeSyntax + ) -> FunctionParameterSyntax { guard let initializer = param.defaultValue else { return param } @@ -131,8 +144,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { return param.with(\.defaultValue, initializer.with(\.value, getEmptyArrayLiteral())) } - private func rewrite(_ param: FunctionParameterSyntax, - type: DictionaryTypeSyntax) -> FunctionParameterSyntax { + private func rewrite( + _ param: FunctionParameterSyntax, + type: DictionaryTypeSyntax + ) -> FunctionParameterSyntax { guard let initializer = param.defaultValue else { return param } @@ -201,9 +216,10 @@ public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { } extension Finding.Message { - fileprivate static func refactorIntoEmptyLiteral(replace: String, with: String) - -> Finding.Message - { + fileprivate static func refactorIntoEmptyLiteral( + replace: String, + with: String + ) -> Finding.Message { "replace '\(replace)' with '\(with)'" } } diff --git a/Sources/SwiftFormat/Rules/AlwaysUseLowerCamelCase.swift b/Sources/SwiftFormat/Rules/AlwaysUseLowerCamelCase.swift index aac9deadb..214daa253 100644 --- a/Sources/SwiftFormat/Rules/AlwaysUseLowerCamelCase.swift +++ b/Sources/SwiftFormat/Rules/AlwaysUseLowerCamelCase.swift @@ -56,7 +56,10 @@ public final class AlwaysUseLowerCamelCase: SyntaxLintRule { continue } diagnoseLowerCamelCaseViolations( - pat.identifier, allowUnderscores: false, description: identifierDescription(for: node)) + pat.identifier, + allowUnderscores: false, + description: identifierDescription(for: node) + ) } return .visitChildren } @@ -66,7 +69,10 @@ public final class AlwaysUseLowerCamelCase: SyntaxLintRule { return .visitChildren } diagnoseLowerCamelCaseViolations( - pattern.identifier, allowUnderscores: false, description: identifierDescription(for: node)) + pattern.identifier, + allowUnderscores: false, + description: identifierDescription(for: node) + ) return .visitChildren } @@ -75,15 +81,24 @@ public final class AlwaysUseLowerCamelCase: SyntaxLintRule { if let closureParamList = input.as(ClosureShorthandParameterListSyntax.self) { for param in closureParamList { diagnoseLowerCamelCaseViolations( - param.name, allowUnderscores: false, description: identifierDescription(for: node)) + param.name, + allowUnderscores: false, + description: identifierDescription(for: node) + ) } } else if let parameterClause = input.as(ClosureParameterClauseSyntax.self) { for param in parameterClause.parameters { diagnoseLowerCamelCaseViolations( - param.firstName, allowUnderscores: false, description: identifierDescription(for: node)) + param.firstName, + allowUnderscores: false, + description: identifierDescription(for: node) + ) if let secondName = param.secondName { diagnoseLowerCamelCaseViolations( - secondName, allowUnderscores: false, description: identifierDescription(for: node)) + secondName, + allowUnderscores: false, + description: identifierDescription(for: node) + ) } } } @@ -104,16 +119,24 @@ public final class AlwaysUseLowerCamelCase: SyntaxLintRule { let allowUnderscores = testCaseFuncs.contains(node) || node.hasAttribute("Test", inModule: "Testing") diagnoseLowerCamelCaseViolations( - node.name, allowUnderscores: allowUnderscores, - description: identifierDescription(for: node)) + node.name, + allowUnderscores: allowUnderscores, + description: identifierDescription(for: node) + ) for param in node.signature.parameterClause.parameters { // These identifiers aren't described using `identifierDescription(for:)` because no single // node can disambiguate the argument label from the parameter name. diagnoseLowerCamelCaseViolations( - param.firstName, allowUnderscores: false, description: "argument label") + param.firstName, + allowUnderscores: false, + description: "argument label" + ) if let paramName = param.secondName { diagnoseLowerCamelCaseViolations( - paramName, allowUnderscores: false, description: "function parameter") + paramName, + allowUnderscores: false, + description: "function parameter" + ) } } return .visitChildren @@ -121,7 +144,10 @@ public final class AlwaysUseLowerCamelCase: SyntaxLintRule { public override func visit(_ node: EnumCaseElementSyntax) -> SyntaxVisitorContinueKind { diagnoseLowerCamelCaseViolations( - node.name, allowUnderscores: false, description: identifierDescription(for: node)) + node.name, + allowUnderscores: false, + description: identifierDescription(for: node) + ) return .skipChildren } @@ -153,7 +179,9 @@ public final class AlwaysUseLowerCamelCase: SyntaxLintRule { } private func diagnoseLowerCamelCaseViolations( - _ identifier: TokenSyntax, allowUnderscores: Bool, description: String + _ identifier: TokenSyntax, + allowUnderscores: Bool, + description: String ) { guard case .identifier(let text) = identifier.tokenKind else { return } if text.isEmpty { return } @@ -197,7 +225,8 @@ extension ReturnClauseSyntax { extension Finding.Message { fileprivate static func nameMustBeLowerCamelCase( - _ name: String, description: String + _ name: String, + description: String ) -> Finding.Message { "rename the \(description) '\(name)' using lowerCamelCase" } diff --git a/Sources/SwiftFormat/Rules/AmbiguousTrailingClosureOverload.swift b/Sources/SwiftFormat/Rules/AmbiguousTrailingClosureOverload.swift index ecd2ff257..72eb28cc3 100644 --- a/Sources/SwiftFormat/Rules/AmbiguousTrailingClosureOverload.swift +++ b/Sources/SwiftFormat/Rules/AmbiguousTrailingClosureOverload.swift @@ -29,9 +29,11 @@ public final class AmbiguousTrailingClosureOverload: SyntaxLintRule { Finding.Note( message: .otherAmbiguousOverloadHere(decl.fullDeclName), location: Finding.Location( - decl.name.startLocation(converter: self.context.sourceLocationConverter)) + decl.name.startLocation(converter: self.context.sourceLocationConverter) + ) ) - }) + } + ) } } diff --git a/Sources/SwiftFormat/Rules/BeginDocumentationCommentWithOneLineSummary.swift b/Sources/SwiftFormat/Rules/BeginDocumentationCommentWithOneLineSummary.swift index 92fefce8a..6caf28ddc 100644 --- a/Sources/SwiftFormat/Rules/BeginDocumentationCommentWithOneLineSummary.swift +++ b/Sources/SwiftFormat/Rules/BeginDocumentationCommentWithOneLineSummary.swift @@ -11,10 +11,11 @@ //===----------------------------------------------------------------------===// import Foundation +import SwiftSyntax + #if os(macOS) import NaturalLanguage #endif -import SwiftSyntax /// All documentation comments must begin with a one-line summary of the declaration. /// @@ -123,50 +124,50 @@ public final class BeginDocumentationCommentWithOneLineSummary: SyntaxLintRule { /// actual text). private func sentences(in text: String) -> (sentences: [String], trailingText: Substring) { #if os(macOS) - if BeginDocumentationCommentWithOneLineSummary._forcesFallbackModeForTesting { - return nonLinguisticSentenceApproximations(in: text) - } + if BeginDocumentationCommentWithOneLineSummary._forcesFallbackModeForTesting { + return nonLinguisticSentenceApproximations(in: text) + } - var sentences = [String]() - var tags = [NLTag]() - var tokenRanges = [Range]() - - let tagger = NLTagger(tagSchemes: [.lexicalClass]) - tagger.string = text - tagger.enumerateTags( - in: text.startIndex..]() + + let tagger = NLTagger(tagSchemes: [.lexicalClass]) + tagger.string = text + tagger.enumerateTags( + in: text.startIndex.. ( + private func nonLinguisticSentenceApproximations( + in text: String + ) -> ( sentences: [String], trailingText: Substring ) { // If we find a period followed by a space, then there is definitely one (approximate) sentence; @@ -216,15 +219,15 @@ public final class BeginDocumentationCommentWithOneLineSummary: SyntaxLintRule { } extension Finding.Message { - fileprivate static func terminateSentenceWithPeriod(_ text: Sentence) - -> Finding.Message - { + fileprivate static func terminateSentenceWithPeriod( + _ text: Sentence + ) -> Finding.Message { "terminate this sentence with a period: \"\(text)\"" } - fileprivate static func addBlankLineAfterFirstSentence(_ text: Sentence) - -> Finding.Message - { + fileprivate static func addBlankLineAfterFirstSentence( + _ text: Sentence + ) -> Finding.Message { "add a blank comment line after this sentence: \"\(text)\"" } } diff --git a/Sources/SwiftFormat/Rules/FileScopedDeclarationPrivacy.swift b/Sources/SwiftFormat/Rules/FileScopedDeclarationPrivacy.swift index bc1a8f2f3..e0f9af4c5 100644 --- a/Sources/SwiftFormat/Rules/FileScopedDeclarationPrivacy.swift +++ b/Sources/SwiftFormat/Rules/FileScopedDeclarationPrivacy.swift @@ -35,9 +35,9 @@ public final class FileScopedDeclarationPrivacy: SyntaxFormatRule { /// /// - Parameter codeBlockItems: The list of code block items to rewrite. /// - Returns: A new `CodeBlockItemListSyntax` that has possibly been rewritten. - private func rewrittenCodeBlockItems(_ codeBlockItems: CodeBlockItemListSyntax) - -> CodeBlockItemListSyntax - { + private func rewrittenCodeBlockItems( + _ codeBlockItems: CodeBlockItemListSyntax + ) -> CodeBlockItemListSyntax { let newCodeBlockItems = codeBlockItems.map { codeBlockItem -> CodeBlockItemSyntax in switch codeBlockItem.item { case .decl(let decl): diff --git a/Sources/SwiftFormat/Rules/FullyIndirectEnum.swift b/Sources/SwiftFormat/Rules/FullyIndirectEnum.swift index 98466fe2f..53273f676 100644 --- a/Sources/SwiftFormat/Rules/FullyIndirectEnum.swift +++ b/Sources/SwiftFormat/Rules/FullyIndirectEnum.swift @@ -35,10 +35,15 @@ public final class FullyIndirectEnum: SyntaxFormatRule { Finding.Note( message: .removeIndirect, location: Finding.Location( - modifier.startLocation(converter: self.context.sourceLocationConverter))) + modifier.startLocation(converter: self.context.sourceLocationConverter) + ) + ) } diagnose( - .moveIndirectKeywordToEnumDecl(name: node.name.text), on: node.enumKeyword, notes: notes) + .moveIndirectKeywordToEnumDecl(name: node.name.text), + on: node.enumKeyword, + notes: notes + ) // Removes 'indirect' keyword from cases, reformats let newMembers = enumMembers.map { @@ -74,7 +79,12 @@ public final class FullyIndirectEnum: SyntaxFormatRule { let newModifier = DeclModifierSyntax( name: TokenSyntax.identifier( - "indirect", leadingTrivia: leadingTrivia, trailingTrivia: .spaces(1)), detail: nil) + "indirect", + leadingTrivia: leadingTrivia, + trailingTrivia: .spaces(1) + ), + detail: nil + ) newEnumDecl.modifiers = newEnumDecl.modifiers + [newModifier] newEnumDecl.memberBlock.members = MemberBlockItemListSyntax(newMembers) @@ -84,15 +94,17 @@ public final class FullyIndirectEnum: SyntaxFormatRule { /// Returns a value indicating whether all enum cases in the given list are indirect. /// /// Note that if the enum has no cases, this returns false. - private func indirectModifiersIfAllCasesIndirect(in members: MemberBlockItemListSyntax) - -> [DeclModifierSyntax] - { + private func indirectModifiersIfAllCasesIndirect( + in members: MemberBlockItemListSyntax + ) -> [DeclModifierSyntax] { var indirectModifiers = [DeclModifierSyntax]() for member in members { if let caseMember = member.decl.as(EnumCaseDeclSyntax.self) { - guard let indirectModifier = caseMember.modifiers.first( - where: { $0.name.text == "indirect" } - ) else { + guard + let indirectModifier = caseMember.modifiers.first( + where: { $0.name.text == "indirect" } + ) + else { return [] } indirectModifiers.append(indirectModifier) diff --git a/Sources/SwiftFormat/Rules/IdentifiersMustBeASCII.swift b/Sources/SwiftFormat/Rules/IdentifiersMustBeASCII.swift index 2da9d1290..913dc2a06 100644 --- a/Sources/SwiftFormat/Rules/IdentifiersMustBeASCII.swift +++ b/Sources/SwiftFormat/Rules/IdentifiersMustBeASCII.swift @@ -32,7 +32,8 @@ public final class IdentifiersMustBeASCII: SyntaxLintRule { extension Finding.Message { fileprivate static func nonASCIICharsNotAllowed( - _ invalidCharacters: [String], _ identifierName: String + _ invalidCharacters: [String], + _ identifierName: String ) -> Finding.Message { """ remove non-ASCII characters from '\(identifierName)': \ diff --git a/Sources/SwiftFormat/Rules/NeverUseImplicitlyUnwrappedOptionals.swift b/Sources/SwiftFormat/Rules/NeverUseImplicitlyUnwrappedOptionals.swift index 7fc8ad341..009969ddc 100644 --- a/Sources/SwiftFormat/Rules/NeverUseImplicitlyUnwrappedOptionals.swift +++ b/Sources/SwiftFormat/Rules/NeverUseImplicitlyUnwrappedOptionals.swift @@ -59,7 +59,9 @@ public final class NeverUseImplicitlyUnwrappedOptionals: SyntaxLintRule { private func diagnoseImplicitWrapViolation(_ type: TypeSyntax) { guard let violation = type.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) else { return } diagnose( - .doNotUseImplicitUnwrapping(identifier: violation.wrappedType.trimmedDescription), on: type) + .doNotUseImplicitUnwrapping(identifier: violation.wrappedType.trimmedDescription), + on: type + ) } } diff --git a/Sources/SwiftFormat/Rules/NoAccessLevelOnExtensionDeclaration.swift b/Sources/SwiftFormat/Rules/NoAccessLevelOnExtensionDeclaration.swift index aa3447c41..ea71fc510 100644 --- a/Sources/SwiftFormat/Rules/NoAccessLevelOnExtensionDeclaration.swift +++ b/Sources/SwiftFormat/Rules/NoAccessLevelOnExtensionDeclaration.swift @@ -89,11 +89,13 @@ public final class NoAccessLevelOnExtensionDeclaration: SyntaxFormatRule { // Create a note associated with each declaration that needs to have an access level modifier // added to it. - notes.append(Finding.Note( - message: .addModifierToExtensionMember(keyword: modifier.name.text), - location: - Finding.Location(decl.startLocation(converter: context.sourceLocationConverter)) - )) + notes.append( + Finding.Note( + message: .addModifierToExtensionMember(keyword: modifier.name.text), + location: + Finding.Location(decl.startLocation(converter: context.sourceLocationConverter)) + ) + ) var newItem = memberItem newItem.decl = applyingAccessModifierIfNone(modifier, to: decl) @@ -142,16 +144,28 @@ private func applyingAccessModifierIfNone( return applyingAccessModifierIfNone(modifier, to: funcDecl, declKeywordKeyPath: \.funcKeyword) case .structDecl(let structDecl): return applyingAccessModifierIfNone( - modifier, to: structDecl, declKeywordKeyPath: \.structKeyword) + modifier, + to: structDecl, + declKeywordKeyPath: \.structKeyword + ) case .subscriptDecl(let subscriptDecl): return applyingAccessModifierIfNone( - modifier, to: subscriptDecl, declKeywordKeyPath: \.subscriptKeyword) + modifier, + to: subscriptDecl, + declKeywordKeyPath: \.subscriptKeyword + ) case .typeAliasDecl(let typeAliasDecl): return applyingAccessModifierIfNone( - modifier, to: typeAliasDecl, declKeywordKeyPath: \.typealiasKeyword) + modifier, + to: typeAliasDecl, + declKeywordKeyPath: \.typealiasKeyword + ) case .variableDecl(let varDecl): return applyingAccessModifierIfNone( - modifier, to: varDecl, declKeywordKeyPath: \.bindingSpecifier) + modifier, + to: varDecl, + declKeywordKeyPath: \.bindingSpecifier + ) default: return decl } diff --git a/Sources/SwiftFormat/Rules/NoAssignmentInExpressions.swift b/Sources/SwiftFormat/Rules/NoAssignmentInExpressions.swift index b51a950dd..62db9130d 100644 --- a/Sources/SwiftFormat/Rules/NoAssignmentInExpressions.swift +++ b/Sources/SwiftFormat/Rules/NoAssignmentInExpressions.swift @@ -60,8 +60,8 @@ public final class NoAssignmentInExpressions: SyntaxFormatRule { var assignmentItem = CodeBlockItemSyntax(item: .expr(ExprSyntax(assignmentExpr))) assignmentItem.leadingTrivia = returnStmt.leadingTrivia - + returnStmt.returnKeyword.trailingTrivia.withoutLeadingSpaces() - + assignmentExpr.leadingTrivia + + returnStmt.returnKeyword.trailingTrivia.withoutLeadingSpaces() + + assignmentExpr.leadingTrivia assignmentItem.trailingTrivia = [] let trailingTrivia = returnStmt.trailingTrivia @@ -120,8 +120,7 @@ public final class NoAssignmentInExpressions: SyntaxFormatRule { /// `CodeBlockItem` parent. private func isStandaloneAssignmentStatement(_ node: InfixOperatorExprSyntax) -> Bool { var node = Syntax(node) - while - let parent = node.parent, + while let parent = node.parent, parent.is(TryExprSyntax.self) || parent.is(AwaitExprSyntax.self) { node = parent diff --git a/Sources/SwiftFormat/Rules/NoEmptyLineOpeningClosingBraces.swift b/Sources/SwiftFormat/Rules/NoEmptyLineOpeningClosingBraces.swift index 5fc32a5f0..4e5da2dcb 100644 --- a/Sources/SwiftFormat/Rules/NoEmptyLineOpeningClosingBraces.swift +++ b/Sources/SwiftFormat/Rules/NoEmptyLineOpeningClosingBraces.swift @@ -20,54 +20,54 @@ import SwiftSyntax @_spi(Rules) public final class NoEmptyLinesOpeningClosingBraces: SyntaxFormatRule { public override class var isOptIn: Bool { return true } - + public override func visit(_ node: AccessorBlockSyntax) -> AccessorBlockSyntax { var result = node switch node.accessors { - case .accessors(let accessors): - result.accessors = .init(rewritten(accessors)) - case .getter(let getter): - result.accessors = .init(rewritten(getter)) + case .accessors(let accessors): + result.accessors = .init(rewritten(accessors)) + case .getter(let getter): + result.accessors = .init(rewritten(getter)) } result.rightBrace = rewritten(node.rightBrace) return result } - + public override func visit(_ node: CodeBlockSyntax) -> CodeBlockSyntax { var result = node result.statements = rewritten(node.statements) result.rightBrace = rewritten(node.rightBrace) return result } - + public override func visit(_ node: MemberBlockSyntax) -> MemberBlockSyntax { var result = node result.members = rewritten(node.members) result.rightBrace = rewritten(node.rightBrace) return result } - + public override func visit(_ node: ClosureExprSyntax) -> ExprSyntax { var result = node result.statements = rewritten(node.statements) result.rightBrace = rewritten(node.rightBrace) return ExprSyntax(result) } - + public override func visit(_ node: SwitchExprSyntax) -> ExprSyntax { var result = node result.cases = rewritten(node.cases) result.rightBrace = rewritten(node.rightBrace) return ExprSyntax(result) } - + public override func visit(_ node: PrecedenceGroupDeclSyntax) -> DeclSyntax { var result = node result.attributes = rewritten(node.attributes) result.rightBrace = rewritten(node.rightBrace) return DeclSyntax(result) } - + func rewritten(_ token: TokenSyntax) -> TokenSyntax { let (trimmedLeadingTrivia, count) = token.leadingTrivia.trimmingSuperfluousNewlines() if trimmedLeadingTrivia.sourceLength != token.leadingTriviaLength { @@ -77,11 +77,11 @@ public final class NoEmptyLinesOpeningClosingBraces: SyntaxFormatRule { return token } } - + func rewritten(_ collection: C) -> C { var result = collection if let first = collection.first, first.leadingTrivia.containsNewlines, - let index = collection.index(of: first) + let index = collection.index(of: first) { let (trimmedLeadingTrivia, count) = first.leadingTrivia.trimmingSuperfluousNewlines() if trimmedLeadingTrivia.sourceLength != first.leadingTriviaLength { @@ -115,7 +115,7 @@ extension Trivia { // Retain other trivia pieces return partialResult + [piece] } - + return (Trivia(pieces: pieces), trimmmed) } } @@ -124,7 +124,7 @@ extension Finding.Message { fileprivate static func removeEmptyLinesAfter(_ count: Int) -> Finding.Message { "remove empty \(count > 1 ? "lines" : "line") after '{'" } - + fileprivate static func removeEmptyLinesBefore(_ count: Int) -> Finding.Message { "remove empty \(count > 1 ? "lines" : "line") before '}'" } diff --git a/Sources/SwiftFormat/Rules/NoVoidReturnOnFunctionSignature.swift b/Sources/SwiftFormat/Rules/NoVoidReturnOnFunctionSignature.swift index 47b948e26..3cacd29e0 100644 --- a/Sources/SwiftFormat/Rules/NoVoidReturnOnFunctionSignature.swift +++ b/Sources/SwiftFormat/Rules/NoVoidReturnOnFunctionSignature.swift @@ -42,9 +42,9 @@ public final class NoVoidReturnOnFunctionSignature: SyntaxFormatRule { } /// Returns a copy of the given function signature with the return clause removed. - private func removingReturnClause(from signature: FunctionSignatureSyntax) - -> FunctionSignatureSyntax - { + private func removingReturnClause( + from signature: FunctionSignatureSyntax + ) -> FunctionSignatureSyntax { var result = signature result.returnClause = nil return result diff --git a/Sources/SwiftFormat/Rules/OmitExplicitReturns.swift b/Sources/SwiftFormat/Rules/OmitExplicitReturns.swift index 1456a58c4..63c65fc2a 100644 --- a/Sources/SwiftFormat/Rules/OmitExplicitReturns.swift +++ b/Sources/SwiftFormat/Rules/OmitExplicitReturns.swift @@ -27,8 +27,9 @@ public final class OmitExplicitReturns: SyntaxFormatRule { // func () -> { return ... } guard var funcDecl = decl.as(FunctionDeclSyntax.self), - let body = funcDecl.body, - let returnStmt = containsSingleReturn(body.statements) else { + let body = funcDecl.body, + let returnStmt = containsSingleReturn(body.statements) + else { return decl } @@ -41,10 +42,11 @@ public final class OmitExplicitReturns: SyntaxFormatRule { let decl = super.visit(node) guard var subscriptDecl = decl.as(SubscriptDeclSyntax.self), - let accessorBlock = subscriptDecl.accessorBlock, - // We are assuming valid Swift code here where only - // one `get { ... }` is allowed. - let transformed = transformAccessorBlock(accessorBlock) else { + let accessorBlock = subscriptDecl.accessorBlock, + // We are assuming valid Swift code here where only + // one `get { ... }` is allowed. + let transformed = transformAccessorBlock(accessorBlock) + else { return decl } @@ -56,7 +58,8 @@ public final class OmitExplicitReturns: SyntaxFormatRule { var binding = node guard let accessorBlock = binding.accessorBlock, - let transformed = transformAccessorBlock(accessorBlock) else { + let transformed = transformAccessorBlock(accessorBlock) + else { return node } @@ -69,8 +72,9 @@ public final class OmitExplicitReturns: SyntaxFormatRule { // test { return ... } guard var closureExpr = expr.as(ClosureExprSyntax.self), - let returnStmt = containsSingleReturn(closureExpr.statements) else { - return expr + let returnStmt = containsSingleReturn(closureExpr.statements) + else { + return expr } closureExpr.statements = rewrapReturnedExpression(returnStmt) @@ -83,20 +87,25 @@ public final class OmitExplicitReturns: SyntaxFormatRule { // one `get { ... }` is allowed. switch accessorBlock.accessors { case .accessors(var accessors): - guard var getter = accessors.filter({ - $0.accessorSpecifier.tokenKind == .keyword(.get) - }).first else { + guard + var getter = accessors.filter({ + $0.accessorSpecifier.tokenKind == .keyword(.get) + }).first + else { return nil } guard let body = getter.body, - let returnStmt = containsSingleReturn(body.statements) else { + let returnStmt = containsSingleReturn(body.statements) + else { return nil } - guard let getterAt = accessors.firstIndex(where: { - $0.accessorSpecifier.tokenKind == .keyword(.get) - }) else { + guard + let getterAt = accessors.firstIndex(where: { + $0.accessorSpecifier.tokenKind == .keyword(.get) + }) + else { return nil } @@ -124,8 +133,8 @@ public final class OmitExplicitReturns: SyntaxFormatRule { private func containsSingleReturn(_ body: CodeBlockItemListSyntax) -> ReturnStmtSyntax? { guard let element = body.firstAndOnly, - let returnStmt = element.item.as(ReturnStmtSyntax.self) else - { + let returnStmt = element.item.as(ReturnStmtSyntax.self) + else { return nil } @@ -138,7 +147,8 @@ public final class OmitExplicitReturns: SyntaxFormatRule { leadingTrivia: returnStmt.leadingTrivia, item: .expr(returnStmt.expression!), semicolon: nil, - trailingTrivia: returnStmt.trailingTrivia) + trailingTrivia: returnStmt.trailingTrivia + ) ]) } } diff --git a/Sources/SwiftFormat/Rules/OneVariableDeclarationPerLine.swift b/Sources/SwiftFormat/Rules/OneVariableDeclarationPerLine.swift index 321e5948e..0387942fa 100644 --- a/Sources/SwiftFormat/Rules/OneVariableDeclarationPerLine.swift +++ b/Sources/SwiftFormat/Rules/OneVariableDeclarationPerLine.swift @@ -51,7 +51,8 @@ public final class OneVariableDeclarationPerLine: SyntaxFormatRule { var splitter = VariableDeclSplitter { CodeBlockItemSyntax( item: .decl(DeclSyntax($0)), - semicolon: nil) + semicolon: nil + ) } newItems.append(contentsOf: splitter.nodes(bySplitting: visitedDecl)) } @@ -214,4 +215,3 @@ private struct VariableDeclSplitter { bindingQueue = [] } } - diff --git a/Sources/SwiftFormat/Rules/OrderedImports.swift b/Sources/SwiftFormat/Rules/OrderedImports.swift index 6d2475a1b..75fcb4572 100644 --- a/Sources/SwiftFormat/Rules/OrderedImports.swift +++ b/Sources/SwiftFormat/Rules/OrderedImports.swift @@ -168,7 +168,8 @@ public final class OrderedImports: SyntaxFormatRule { switch lineType { case .regularImport, .declImport: diagnose( - .groupImports(before: lineType, after: LineType.testableImport), on: line.firstToken + .groupImports(before: lineType, after: LineType.testableImport), + on: line.firstToken ) default: () } @@ -178,7 +179,8 @@ public final class OrderedImports: SyntaxFormatRule { switch lineType { case .regularImport: diagnose( - .groupImports(before: lineType, after: LineType.declImport), on: line.firstToken + .groupImports(before: lineType, after: LineType.declImport), + on: line.firstToken ) default: () } @@ -281,9 +283,10 @@ fileprivate func joinLines(_ inputLineLists: [Line]...) -> [Line] { /// This function transforms the statements in a CodeBlockItemListSyntax object into a list of Line /// objects. Blank lines and standalone comments are represented by their own Line object. Code with /// a trailing comment are represented together in the same Line. -fileprivate func generateLines(codeBlockItemList: CodeBlockItemListSyntax, context: Context) - -> [Line] -{ +fileprivate func generateLines( + codeBlockItemList: CodeBlockItemListSyntax, + context: Context +) -> [Line] { var lines: [Line] = [] var currentLine = Line() diff --git a/Sources/SwiftFormat/Rules/ReplaceForEachWithForLoop.swift b/Sources/SwiftFormat/Rules/ReplaceForEachWithForLoop.swift index 120b69967..14e6dcbff 100644 --- a/Sources/SwiftFormat/Rules/ReplaceForEachWithForLoop.swift +++ b/Sources/SwiftFormat/Rules/ReplaceForEachWithForLoop.swift @@ -16,12 +16,11 @@ import SwiftSyntax /// /// Lint: invalid use of `forEach` yield will yield a lint error. @_spi(Rules) -public final class ReplaceForEachWithForLoop : SyntaxLintRule { +public final class ReplaceForEachWithForLoop: SyntaxLintRule { public override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind { // We are only interested in calls with a single trailing closure // argument. - if !node.arguments.isEmpty || node.trailingClosure == nil || - !node.additionalTrailingClosures.isEmpty { + if !node.arguments.isEmpty || node.trailingClosure == nil || !node.additionalTrailingClosures.isEmpty { return .visitChildren } diff --git a/Sources/SwiftFormat/Rules/ReturnVoidInsteadOfEmptyTuple.swift b/Sources/SwiftFormat/Rules/ReturnVoidInsteadOfEmptyTuple.swift index e98d67cdd..977c9bfe0 100644 --- a/Sources/SwiftFormat/Rules/ReturnVoidInsteadOfEmptyTuple.swift +++ b/Sources/SwiftFormat/Rules/ReturnVoidInsteadOfEmptyTuple.swift @@ -35,7 +35,8 @@ public final class ReturnVoidInsteadOfEmptyTuple: SyntaxFormatRule { // still diagnose it as a lint error but we don't replace it because it's not obvious where the // comment should go. if hasNonWhitespaceTrivia(returnType.leftParen, at: .trailing) - || hasNonWhitespaceTrivia(returnType.rightParen, at: .leading) { + || hasNonWhitespaceTrivia(returnType.rightParen, at: .leading) + { return super.visit(node) } @@ -64,7 +65,8 @@ public final class ReturnVoidInsteadOfEmptyTuple: SyntaxFormatRule { // still diagnose it as a lint error but we don't replace it because it's not obvious where the // comment should go. if hasNonWhitespaceTrivia(returnType.leftParen, at: .trailing) - || hasNonWhitespaceTrivia(returnType.rightParen, at: .leading) { + || hasNonWhitespaceTrivia(returnType.rightParen, at: .leading) + { return super.visit(node) } @@ -107,14 +109,15 @@ public final class ReturnVoidInsteadOfEmptyTuple: SyntaxFormatRule { /// Returns a type syntax node with the identifier `Void` whose leading and trailing trivia have /// been copied from the tuple type syntax node it is replacing. - private func makeVoidIdentifierType(toReplace node: TupleTypeSyntax) -> IdentifierTypeSyntax - { + private func makeVoidIdentifierType(toReplace node: TupleTypeSyntax) -> IdentifierTypeSyntax { return IdentifierTypeSyntax( name: TokenSyntax.identifier( "Void", leadingTrivia: node.firstToken(viewMode: .sourceAccurate)?.leadingTrivia ?? [], - trailingTrivia: node.lastToken(viewMode: .sourceAccurate)?.trailingTrivia ?? []), - genericArgumentClause: nil) + trailingTrivia: node.lastToken(viewMode: .sourceAccurate)?.trailingTrivia ?? [] + ), + genericArgumentClause: nil + ) } } diff --git a/Sources/SwiftFormat/Rules/TypeNamesShouldBeCapitalized.swift b/Sources/SwiftFormat/Rules/TypeNamesShouldBeCapitalized.swift index 3fdb53828..44912bad7 100644 --- a/Sources/SwiftFormat/Rules/TypeNamesShouldBeCapitalized.swift +++ b/Sources/SwiftFormat/Rules/TypeNamesShouldBeCapitalized.swift @@ -16,7 +16,7 @@ import SwiftSyntax /// /// Lint: Types with un-capitalized names will yield a lint error. @_spi(Rules) -public final class TypeNamesShouldBeCapitalized : SyntaxLintRule { +public final class TypeNamesShouldBeCapitalized: SyntaxLintRule { public override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { diagnoseNameConventionMismatch(node, name: node.name, kind: "struct") return .visitChildren @@ -59,7 +59,8 @@ public final class TypeNamesShouldBeCapitalized : SyntaxLintRule { ) { let leadingUnderscores = name.text.prefix { $0 == "_" } if let firstChar = name.text[leadingUnderscores.endIndex...].first, - firstChar.uppercased() != String(firstChar) { + firstChar.uppercased() != String(firstChar) + { diagnose(.capitalizeTypeName(name: name.text, kind: kind), on: name, severity: .convention) } } diff --git a/Sources/SwiftFormat/Rules/UseEarlyExits.swift b/Sources/SwiftFormat/Rules/UseEarlyExits.swift index 15f935b35..3f1e53912 100644 --- a/Sources/SwiftFormat/Rules/UseEarlyExits.swift +++ b/Sources/SwiftFormat/Rules/UseEarlyExits.swift @@ -69,12 +69,14 @@ public final class UseEarlyExits: SyntaxFormatRule { let guardKeyword = TokenSyntax.keyword( .guard, leadingTrivia: ifStatement.ifKeyword.leadingTrivia, - trailingTrivia: .spaces(1)) + trailingTrivia: .spaces(1) + ) let guardStatement = GuardStmtSyntax( guardKeyword: guardKeyword, conditions: ifStatement.conditions, elseKeyword: TokenSyntax.keyword(.else, trailingTrivia: .spaces(1)), - body: visit(elseBody)) + body: visit(elseBody) + ) newItems.append(CodeBlockItemSyntax(item: .stmt(StmtSyntax(guardStatement)))) diff --git a/Sources/SwiftFormat/Rules/UseExplicitNilCheckInConditions.swift b/Sources/SwiftFormat/Rules/UseExplicitNilCheckInConditions.swift index 2ff1ceee8..6e7e3e6c0 100644 --- a/Sources/SwiftFormat/Rules/UseExplicitNilCheckInConditions.swift +++ b/Sources/SwiftFormat/Rules/UseExplicitNilCheckInConditions.swift @@ -49,7 +49,8 @@ public final class UseExplicitNilCheckInConditions: SyntaxFormatRule { var inequalExpr = InfixOperatorExprSyntax( leftOperand: addingParenthesesIfNecessary(to: value), operator: operatorExpr, - rightOperand: NilLiteralExprSyntax()) + rightOperand: NilLiteralExprSyntax() + ) inequalExpr.leadingTrivia = node.leadingTrivia inequalExpr.trailingTrivia = trailingTrivia @@ -103,8 +104,7 @@ public final class UseExplicitNilCheckInConditions: SyntaxFormatRule { // Note that we could also cover the `tryExpr` and `ternaryExpr` cases above with this, but // this reparsing trick is going to be slower so we should avoid it whenever we can. let reparsedExpr = "\(expr) != nil" as ExprSyntax - if - let infixExpr = reparsedExpr.as(InfixOperatorExprSyntax.self), + if let infixExpr = reparsedExpr.as(InfixOperatorExprSyntax.self), let binOp = infixExpr.operator.as(BinaryOperatorExprSyntax.self), binOp.operator.text == "!=", infixExpr.rightOperand.is(NilLiteralExprSyntax.self) diff --git a/Sources/SwiftFormat/Rules/UseShorthandTypeNames.swift b/Sources/SwiftFormat/Rules/UseShorthandTypeNames.swift index ea48c5899..dc101a018 100644 --- a/Sources/SwiftFormat/Rules/UseShorthandTypeNames.swift +++ b/Sources/SwiftFormat/Rules/UseShorthandTypeNames.swift @@ -54,7 +54,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { newNode = shorthandArrayType( element: typeArgument.argument, leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia) + trailingTrivia: trailingTrivia + ) case "Dictionary": guard let typeArguments = exactlyTwoChildren(of: genericArgumentList) else { @@ -65,7 +66,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { key: typeArguments.0.argument, value: typeArguments.1.argument, leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia) + trailingTrivia: trailingTrivia + ) case "Optional": guard !isTypeOfUninitializedStoredVar(node) else { @@ -79,7 +81,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { newNode = shorthandOptionalType( wrapping: typeArgument.argument, leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia) + trailingTrivia: trailingTrivia + ) default: newNode = nil @@ -141,7 +144,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let arrayTypeExpr = makeArrayTypeExpression( elementType: typeArgument.argument, leftSquare: TokenSyntax.leftSquareToken(leadingTrivia: leadingTrivia), - rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia)) + rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia) + ) newNode = ExprSyntax(arrayTypeExpr) case "Dictionary": @@ -154,7 +158,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { valueType: typeArguments.1.argument, leftSquare: TokenSyntax.leftSquareToken(leadingTrivia: leadingTrivia), colon: TokenSyntax.colonToken(trailingTrivia: .spaces(1)), - rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia)) + rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia) + ) newNode = ExprSyntax(dictTypeExpr) case "Optional": @@ -165,7 +170,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let optionalTypeExpr = makeOptionalTypeExpression( wrapping: typeArgument.argument, leadingTrivia: leadingTrivia, - questionMark: TokenSyntax.postfixQuestionMarkToken(trailingTrivia: trailingTrivia)) + questionMark: TokenSyntax.postfixQuestionMarkToken(trailingTrivia: trailingTrivia) + ) newNode = ExprSyntax(optionalTypeExpr) default: @@ -187,9 +193,9 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { /// Returns the two arguments in the given argument list, if there are exactly two elements; /// otherwise, it returns nil. - private func exactlyTwoChildren(of argumentList: GenericArgumentListSyntax) - -> (GenericArgumentSyntax, GenericArgumentSyntax)? - { + private func exactlyTwoChildren( + of argumentList: GenericArgumentListSyntax + ) -> (GenericArgumentSyntax, GenericArgumentSyntax)? { var iterator = argumentList.makeIterator() guard let first = iterator.next() else { return nil } guard let second = iterator.next() else { return nil } @@ -207,7 +213,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let result = ArrayTypeSyntax( leftSquare: TokenSyntax.leftSquareToken(leadingTrivia: leadingTrivia), element: element, - rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia)) + rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia) + ) return TypeSyntax(result) } @@ -224,7 +231,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { key: key, colon: TokenSyntax.colonToken(trailingTrivia: .spaces(1)), value: value, - rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia)) + rightSquare: TokenSyntax.rightSquareToken(trailingTrivia: trailingTrivia) + ) return TypeSyntax(result) } @@ -258,7 +266,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let optionalType = OptionalTypeSyntax( wrappedType: wrappedType, - questionMark: TokenSyntax.postfixQuestionMarkToken(trailingTrivia: trailingTrivia)) + questionMark: TokenSyntax.postfixQuestionMarkToken(trailingTrivia: trailingTrivia) + ) return TypeSyntax(optionalType) } @@ -276,9 +285,10 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { return ArrayExprSyntax( leftSquare: leftSquare, elements: ArrayElementListSyntax([ - ArrayElementSyntax(expression: elementTypeExpr, trailingComma: nil), + ArrayElementSyntax(expression: elementTypeExpr, trailingComma: nil) ]), - rightSquare: rightSquare) + rightSquare: rightSquare + ) } /// Returns a `DictionaryExprSyntax` whose single key/value pair is the expression representations @@ -302,12 +312,14 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { key: keyTypeExpr, colon: colon, value: valueTypeExpr, - trailingComma: nil), + trailingComma: nil + ) ]) return DictionaryExprSyntax( leftSquare: leftSquare, content: .elements(dictElementList), - rightSquare: rightSquare) + rightSquare: rightSquare + ) } /// Returns an `OptionalChainingExprSyntax` whose wrapped expression is the expression @@ -337,7 +349,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { return OptionalChainingExprSyntax( expression: wrappedTypeExpr, - questionMark: questionMark) + questionMark: questionMark + ) } /// Returns the given type wrapped in parentheses. @@ -349,7 +362,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let tupleType = TupleTypeSyntax( leftParen: .leftParenToken(leadingTrivia: leadingTrivia), elements: TupleTypeElementListSyntax([tupleTypeElement]), - rightParen: .rightParenToken()) + rightParen: .rightParenToken() + ) return TypeSyntax(tupleType) } @@ -362,7 +376,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let tupleExpr = TupleExprSyntax( leftParen: .leftParenToken(leadingTrivia: leadingTrivia), elements: LabeledExprListSyntax([tupleExprElement]), - rightParen: .rightParenToken()) + rightParen: .rightParenToken() + ) return ExprSyntax(tupleExpr) } @@ -377,7 +392,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { case .identifierType(let simpleTypeIdentifier): let identifierExpr = DeclReferenceExprSyntax( baseName: simpleTypeIdentifier.name, - argumentNames: nil) + argumentNames: nil + ) // If the type has a generic argument clause, we need to construct a `SpecializeExpr` to wrap // the identifier and the generic arguments. Otherwise, we can return just the @@ -386,7 +402,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let newGenericArgumentClause = visit(genericArgumentClause) let result = GenericSpecializationExprSyntax( expression: ExprSyntax(identifierExpr), - genericArgumentClause: newGenericArgumentClause) + genericArgumentClause: newGenericArgumentClause + ) return ExprSyntax(result) } else { return ExprSyntax(identifierExpr) @@ -407,7 +424,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let result = makeArrayTypeExpression( elementType: arrayType.element, leftSquare: arrayType.leftSquare, - rightSquare: arrayType.rightSquare) + rightSquare: arrayType.rightSquare + ) return ExprSyntax(result) case .dictionaryType(let dictionaryType): @@ -416,14 +434,16 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { valueType: dictionaryType.value, leftSquare: dictionaryType.leftSquare, colon: dictionaryType.colon, - rightSquare: dictionaryType.rightSquare) + rightSquare: dictionaryType.rightSquare + ) return ExprSyntax(result) case .optionalType(let optionalType): let result = makeOptionalTypeExpression( wrapping: optionalType.wrappedType, leadingTrivia: optionalType.firstToken(viewMode: .sourceAccurate)?.leadingTrivia ?? [], - questionMark: optionalType.questionMark) + questionMark: optionalType.questionMark + ) return ExprSyntax(result) case .functionType(let functionType): @@ -442,7 +462,8 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let result = TupleExprSyntax( leftParen: tupleType.leftParen, elements: elementExprs, - rightParen: tupleType.rightParen) + rightParen: tupleType.rightParen + ) return ExprSyntax(result) case .someOrAnyType(let someOrAnyType): @@ -456,9 +477,9 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { } } - private func expressionRepresentation(of tupleTypeElements: TupleTypeElementListSyntax) - -> LabeledExprListSyntax? - { + private func expressionRepresentation( + of tupleTypeElements: TupleTypeElementListSyntax + ) -> LabeledExprListSyntax? { guard !tupleTypeElements.isEmpty else { return nil } var exprElements = [LabeledExprSyntax]() @@ -469,7 +490,9 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { label: typeElement.firstName, colon: typeElement.colon, expression: elementExpr, - trailingComma: typeElement.trailingComma)) + trailingComma: typeElement.trailingComma + ) + ) } return LabeledExprListSyntax(exprElements) } @@ -492,23 +515,26 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { let tupleExpr = TupleExprSyntax( leftParen: leftParen, elements: parameterExprs, - rightParen: rightParen) + rightParen: rightParen + ) let arrowExpr = ArrowExprSyntax( effectSpecifiers: effectSpecifiers, - arrow: arrow) + arrow: arrow + ) return InfixOperatorExprSyntax( leftOperand: tupleExpr, operator: arrowExpr, - rightOperand: returnTypeExpr) + rightOperand: returnTypeExpr + ) } /// Returns the leading and trailing trivia from the front and end of the entire given node. /// /// In other words, this is the leading trivia from the first token of the node and the trailing /// trivia from the last token. - private func boundaryTrivia(around node: Syntax) - -> (leadingTrivia: Trivia, trailingTrivia: Trivia) - { + private func boundaryTrivia( + around node: Syntax + ) -> (leadingTrivia: Trivia, trailingTrivia: Trivia) { return ( leadingTrivia: node.firstToken(viewMode: .sourceAccurate)?.leadingTrivia ?? [], trailingTrivia: node.lastToken(viewMode: .sourceAccurate)?.trailingTrivia ?? [] @@ -558,7 +584,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule { isStoredProperty(patternBinding), patternBinding.initializer == nil, let variableDecl = nearestAncestor(of: patternBinding, type: VariableDeclSyntax.self), - variableDecl.bindingSpecifier.tokenKind == .keyword(.var) + variableDecl.bindingSpecifier.tokenKind == .keyword(.var) { return true } diff --git a/Sources/SwiftFormat/Rules/UseSynthesizedInitializer.swift b/Sources/SwiftFormat/Rules/UseSynthesizedInitializer.swift index 80614b64a..a523dd47c 100644 --- a/Sources/SwiftFormat/Rules/UseSynthesizedInitializer.swift +++ b/Sources/SwiftFormat/Rules/UseSynthesizedInitializer.swift @@ -50,13 +50,16 @@ public final class UseSynthesizedInitializer: SyntaxLintRule { initializer.attributes.isEmpty, matchesPropertyList( parameters: initializer.signature.parameterClause.parameters, - properties: storedProperties), + properties: storedProperties + ), matchesAssignmentBody( variables: storedProperties, - initBody: initializer.body), + initBody: initializer.body + ), matchesAccessLevel( modifiers: initializer.modifiers, - properties: storedProperties) + properties: storedProperties + ) else { continue } @@ -83,7 +86,8 @@ public final class UseSynthesizedInitializer: SyntaxLintRule { /// - properties: The properties from the enclosing type. /// - Returns: Whether the initializer has the same access level as the synthesized initializer. private func matchesAccessLevel( - modifiers: DeclModifierListSyntax?, properties: [VariableDeclSyntax] + modifiers: DeclModifierListSyntax?, + properties: [VariableDeclSyntax] ) -> Bool { let synthesizedAccessLevel = synthesizedInitAccessLevel(using: properties) let accessLevel = modifiers?.accessLevelModifier @@ -125,8 +129,11 @@ public final class UseSynthesizedInitializer: SyntaxLintRule { if propertyId.identifier.text != parameter.firstName.text || propertyType.description.trimmingCharacters( - in: .whitespaces) != parameter.type.description.trimmingCharacters(in: .whitespacesAndNewlines) - { return false } + in: .whitespaces + ) != parameter.type.description.trimmingCharacters(in: .whitespacesAndNewlines) + { + return false + } } return true } @@ -209,10 +216,10 @@ fileprivate func synthesizedInitAccessLevel(using properties: [VariableDeclSynta var hasFileprivate = false for property in properties { // Private takes precedence, so finding 1 private property defines the access level. - if property.modifiers.contains(where: {$0.name.tokenKind == .keyword(.private) && $0.detail == nil}) { + if property.modifiers.contains(where: { $0.name.tokenKind == .keyword(.private) && $0.detail == nil }) { return .private } - if property.modifiers.contains(where: {$0.name.tokenKind == .keyword(.fileprivate) && $0.detail == nil}) { + if property.modifiers.contains(where: { $0.name.tokenKind == .keyword(.fileprivate) && $0.detail == nil }) { hasFileprivate = true // Can't break here because a later property might be private. } diff --git a/Sources/SwiftFormat/Rules/UseWhereClausesInForLoops.swift b/Sources/SwiftFormat/Rules/UseWhereClausesInForLoops.swift index b8224b51c..6671879e4 100644 --- a/Sources/SwiftFormat/Rules/UseWhereClausesInForLoops.swift +++ b/Sources/SwiftFormat/Rules/UseWhereClausesInForLoops.swift @@ -55,7 +55,7 @@ public final class UseWhereClausesInForLoops: SyntaxFormatRule { case .expressionStmt(let exprStmt): switch Syntax(exprStmt.expression).as(SyntaxEnum.self) { case .ifExpr(let ifExpr) - where ifExpr.conditions.count == 1 + where ifExpr.conditions.count == 1 && ifExpr.elseKeyword == nil && forInStmt.body.statements.count == 1: // Extract the condition of the IfExpr. @@ -105,7 +105,8 @@ fileprivate func updateWithWhereCondition( if lastToken?.trailingTrivia.containsSpaces == false { whereLeadingTrivia = .spaces(1) } - let whereKeyword = TokenSyntax.keyword(.where, + let whereKeyword = TokenSyntax.keyword( + .where, leadingTrivia: whereLeadingTrivia, trailingTrivia: .spaces(1) ) diff --git a/Sources/SwiftFormat/Rules/ValidateDocumentationComments.swift b/Sources/SwiftFormat/Rules/ValidateDocumentationComments.swift index 8bb5b117b..e99d1556e 100644 --- a/Sources/SwiftFormat/Rules/ValidateDocumentationComments.swift +++ b/Sources/SwiftFormat/Rules/ValidateDocumentationComments.swift @@ -29,13 +29,19 @@ public final class ValidateDocumentationComments: SyntaxLintRule { public override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { return checkFunctionLikeDocumentation( - DeclSyntax(node), name: "init", signature: node.signature) + DeclSyntax(node), + name: "init", + signature: node.signature + ) } public override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { return checkFunctionLikeDocumentation( - DeclSyntax(node), name: node.name.text, signature: node.signature, - returnClause: node.signature.returnClause) + DeclSyntax(node), + name: node.name.text, + signature: node.signature, + returnClause: node.signature.returnClause + ) } private func checkFunctionLikeDocumentation( @@ -65,12 +71,14 @@ public final class ValidateDocumentationComments: SyntaxLintRule { signature.effectSpecifiers?.throwsClause?.throwsSpecifier, name: name, throwsDescription: docComment.throws, - node: node) + node: node + ) validateReturn( returnClause, name: name, returnsDescription: docComment.returns, - node: node) + node: node + ) let funcParameters = funcParametersIdentifiers(in: signature.parameterClause.parameters) // If the documentation of the parameters is wrong 'docCommentInfo' won't @@ -107,7 +115,7 @@ public final class ValidateDocumentationComments: SyntaxLintRule { diagnose(.removeReturnComment(funcName: name), on: node) } else if let returnClause = returnClause, returnsDescription == nil { if let returnTypeIdentifier = returnClause.type.as(IdentifierTypeSyntax.self), - returnTypeIdentifier.name.text == "Never" + returnTypeIdentifier.name.text == "Never" { return } @@ -131,7 +139,8 @@ public final class ValidateDocumentationComments: SyntaxLintRule { if !needsThrowsDesc && throwsDescription != nil { diagnose( .removeThrowsComment(funcName: name), - on: throwsOrRethrowsKeyword ?? node.firstToken(viewMode: .sourceAccurate)) + on: throwsOrRethrowsKeyword ?? node.firstToken(viewMode: .sourceAccurate) + ) } else if needsThrowsDesc && throwsDescription == nil { diagnose(.documentErrorsThrown(funcName: name), on: throwsOrRethrowsKeyword) } diff --git a/Sources/SwiftFormat/Utilities/FileIterator.swift b/Sources/SwiftFormat/Utilities/FileIterator.swift index d274d71c3..bd3a2c0f0 100644 --- a/Sources/SwiftFormat/Utilities/FileIterator.swift +++ b/Sources/SwiftFormat/Utilities/FileIterator.swift @@ -86,7 +86,8 @@ public struct FileIterator: Sequence, IteratorProtocol { dirIterator = FileManager.default.enumerator( at: next, includingPropertiesForKeys: nil, - options: [.skipsHiddenFiles]) + options: [.skipsHiddenFiles] + ) currentDirectory = next default: @@ -114,7 +115,7 @@ public struct FileIterator: Sequence, IteratorProtocol { break } #if os(Windows) - // Windows does not consider files and directories starting with `.` as hidden but we don't want to traverse + // Windows does not consider files and directories starting with `.` as hidden but we don't want to traverse // into eg. `.build`. Manually skip any items starting with `.`. if item.lastPathComponent.hasPrefix(".") { dirIterator?.skipDescendants() diff --git a/Sources/_SwiftFormatTestSupport/DiagnosingTestCase.swift b/Sources/_SwiftFormatTestSupport/DiagnosingTestCase.swift index 1c8054d23..cb4e07267 100644 --- a/Sources/_SwiftFormatTestSupport/DiagnosingTestCase.swift +++ b/Sources/_SwiftFormatTestSupport/DiagnosingTestCase.swift @@ -1,9 +1,8 @@ import SwiftFormat +@_spi(Rules) @_spi(Testing) import SwiftFormat import SwiftSyntax import XCTest -@_spi(Rules) @_spi(Testing) import SwiftFormat - /// DiagnosingTestCase is an XCTestCase subclass meant to inject diagnostic-specific testing /// routines into specific formatting test cases. open class DiagnosingTestCase: XCTestCase { @@ -25,7 +24,8 @@ open class DiagnosingTestCase: XCTestCase { fileURL: URL(fileURLWithPath: "/tmp/test.swift"), selection: selection, sourceFileSyntax: sourceFileSyntax, - ruleNameCache: ruleNameCache) + ruleNameCache: ruleNameCache + ) return context } @@ -49,7 +49,8 @@ open class DiagnosingTestCase: XCTestCase { emittedFindings: &emittedFindings, context: context, file: file, - line: line) + line: line + ) } // Emit test failures for any findings that did not have matches. @@ -63,7 +64,8 @@ open class DiagnosingTestCase: XCTestCase { XCTFail( "Unexpected finding '\(finding.message)' was emitted (\(locationString))", file: file, - line: line) + line: line + ) } } @@ -97,7 +99,8 @@ open class DiagnosingTestCase: XCTestCase { (line:col \(markerLocation.line):\(markerLocation.column), offset \(utf8Offset)) """, file: file, - line: line) + line: line + ) return } @@ -112,7 +115,8 @@ open class DiagnosingTestCase: XCTestCase { had the wrong message """, file: file, - line: line) + line: line + ) // Assert that a note exists for each of the expected nodes in the finding. var emittedNotes = matchedFinding.notes @@ -123,7 +127,8 @@ open class DiagnosingTestCase: XCTestCase { emittedNotes: &emittedNotes, context: context, file: file, - line: line) + line: line + ) } // Emit test failures for any notes that weren't specified. @@ -137,7 +142,8 @@ open class DiagnosingTestCase: XCTestCase { XCTFail( "Unexpected note '\(note.message)' was emitted (\(locationString))", file: file, - line: line) + line: line + ) } } @@ -170,7 +176,8 @@ open class DiagnosingTestCase: XCTestCase { (line:col \(markerLocation.line):\(markerLocation.column), offset \(utf8Offset)) """, file: file, - line: line) + line: line + ) return } @@ -185,7 +192,8 @@ open class DiagnosingTestCase: XCTestCase { had the wrong message """, file: file, - line: line) + line: line + ) } /// Asserts that the two strings are equal, providing Unix `diff`-style output if they are not. diff --git a/Sources/_SwiftFormatTestSupport/MarkedText.swift b/Sources/_SwiftFormatTestSupport/MarkedText.swift index 071a7540a..9d63a4812 100644 --- a/Sources/_SwiftFormatTestSupport/MarkedText.swift +++ b/Sources/_SwiftFormatTestSupport/MarkedText.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -import SwiftSyntax import SwiftFormat +import SwiftSyntax /// Encapsulates the locations of emoji markers extracted from source text. public struct MarkedText { @@ -38,7 +38,7 @@ public struct MarkedText { if marker.name == "⏩" { lastRangeStart = text.utf8.count } else if marker.name == "⏪" { - offsets.append(lastRangeStart ..< text.utf8.count) + offsets.append(lastRangeStart.. SyntaxVisitorContinueKind { - """) + """ + ) for ruleName in lintRules.sorted() { handle.write( """ visitIfEnabled(\(ruleName).visit, for: node) - """) + """ + ) } handle.write( @@ -88,27 +90,29 @@ final class PipelineGenerator: FileGenerator { return .visitChildren } - """) + """ + ) - handle.write( - """ - override func visitPost(_ node: \(nodeType)) { - - """ - ) - for ruleName in lintRules.sorted() { - handle.write( - """ - onVisitPost(rule: \(ruleName).self, for: node) + handle.write( + """ + override func visitPost(_ node: \(nodeType)) { - """) - } + """ + ) + for ruleName in lintRules.sorted() { handle.write( """ - } + onVisitPost(rule: \(ruleName).self, for: node) """ ) + } + handle.write( + """ + } + + """ + ) } handle.write( @@ -128,7 +132,8 @@ final class PipelineGenerator: FileGenerator { """ node = \(ruleName)(context: context).rewrite(node) - """) + """ + ) } handle.write( @@ -137,6 +142,7 @@ final class PipelineGenerator: FileGenerator { } } - """) + """ + ) } } diff --git a/Sources/generate-swift-format/RuleCollector.swift b/Sources/generate-swift-format/RuleCollector.swift index d3564f11c..f39dc66e0 100644 --- a/Sources/generate-swift-format/RuleCollector.swift +++ b/Sources/generate-swift-format/RuleCollector.swift @@ -11,10 +11,9 @@ //===----------------------------------------------------------------------===// import Foundation -import SwiftSyntax -import SwiftParser - @_spi(Rules) import SwiftFormat +import SwiftParser +import SwiftSyntax /// Collects information about rules in the formatter code base. final class RuleCollector { @@ -149,7 +148,8 @@ final class RuleCollector { description: description?.text, visitedNodes: visitedNodes, canFormat: canFormat, - isOptIn: ruleType.isOptIn) + isOptIn: ruleType.isOptIn + ) } return nil diff --git a/Sources/generate-swift-format/RuleDocumentationGenerator.swift b/Sources/generate-swift-format/RuleDocumentationGenerator.swift index c90cc62e4..eb2375f26 100644 --- a/Sources/generate-swift-format/RuleDocumentationGenerator.swift +++ b/Sources/generate-swift-format/RuleDocumentationGenerator.swift @@ -44,27 +44,30 @@ final class RuleDocumentationGenerator: FileGenerator { ) for detectedRule in ruleCollector.allLinters.sorted(by: { $0.typeName < $1.typeName }) { - handle.write(""" - - [\(detectedRule.typeName)](#\(detectedRule.typeName)) + handle.write( + """ + - [\(detectedRule.typeName)](#\(detectedRule.typeName)) - """) + """ + ) } for detectedRule in ruleCollector.allLinters.sorted(by: { $0.typeName < $1.typeName }) { - handle.write(""" + handle.write( + """ - ### \(detectedRule.typeName) + ### \(detectedRule.typeName) - \(detectedRule.description ?? "") - \(ruleFormatSupportDescription(for: detectedRule)) + \(detectedRule.description ?? "") + \(ruleFormatSupportDescription(for: detectedRule)) - """) + """ + ) } } private func ruleFormatSupportDescription(for rule: RuleCollector.DetectedRule) -> String { - return rule.canFormat ? - "`\(rule.typeName)` rule can format your code automatically." : - "`\(rule.typeName)` is a linter-only rule." + return rule.canFormat + ? "`\(rule.typeName)` rule can format your code automatically." : "`\(rule.typeName)` is a linter-only rule." } } diff --git a/Sources/generate-swift-format/RuleNameCacheGenerator.swift b/Sources/generate-swift-format/RuleNameCacheGenerator.swift index 55db7063b..b6be4ff96 100644 --- a/Sources/generate-swift-format/RuleNameCacheGenerator.swift +++ b/Sources/generate-swift-format/RuleNameCacheGenerator.swift @@ -53,4 +53,3 @@ final class RuleNameCacheGenerator: FileGenerator { handle.write("]\n") } } - diff --git a/Sources/generate-swift-format/main.swift b/Sources/generate-swift-format/main.swift index 75df61f9e..ea40bcd1b 100644 --- a/Sources/generate-swift-format/main.swift +++ b/Sources/generate-swift-format/main.swift @@ -16,24 +16,29 @@ import SwiftSyntax let sourcesDirectory = URL(fileURLWithPath: #file) .deletingLastPathComponent() .deletingLastPathComponent() -let rulesDirectory = sourcesDirectory +let rulesDirectory = + sourcesDirectory .appendingPathComponent("SwiftFormat") .appendingPathComponent("Rules") -let pipelineFile = sourcesDirectory +let pipelineFile = + sourcesDirectory .appendingPathComponent("SwiftFormat") .appendingPathComponent("Core") .appendingPathComponent("Pipelines+Generated.swift") -let ruleRegistryFile = sourcesDirectory +let ruleRegistryFile = + sourcesDirectory .appendingPathComponent("SwiftFormat") .appendingPathComponent("Core") .appendingPathComponent("RuleRegistry+Generated.swift") -let ruleNameCacheFile = sourcesDirectory +let ruleNameCacheFile = + sourcesDirectory .appendingPathComponent("SwiftFormat") .appendingPathComponent("Core") .appendingPathComponent("RuleNameCache+Generated.swift") -let ruleDocumentationFile = sourcesDirectory +let ruleDocumentationFile = + sourcesDirectory .appendingPathComponent("..") .appendingPathComponent("Documentation") .appendingPathComponent("RuleDocumentation.md") diff --git a/Sources/swift-format/Frontend/FormatFrontend.swift b/Sources/swift-format/Frontend/FormatFrontend.swift index ae3713a81..850086d61 100644 --- a/Sources/swift-format/Frontend/FormatFrontend.swift +++ b/Sources/swift-format/Frontend/FormatFrontend.swift @@ -35,7 +35,8 @@ class FormatFrontend: Frontend { let url = fileToProcess.url guard let source = fileToProcess.sourceText else { diagnosticsEngine.emitError( - "Unable to format \(url.relativePath): file is not readable or does not exist.") + "Unable to format \(url.relativePath): file is not readable or does not exist." + ) return } @@ -56,7 +57,8 @@ class FormatFrontend: Frontend { assumingFileURL: url, selection: fileToProcess.selection, to: &buffer, - parsingDiagnosticHandler: diagnosticHandler) + parsingDiagnosticHandler: diagnosticHandler + ) if buffer != source { let bufferData = buffer.data(using: .utf8)! // Conversion to UTF-8 cannot fail @@ -68,11 +70,13 @@ class FormatFrontend: Frontend { assumingFileURL: url, selection: fileToProcess.selection, to: &stdoutStream, - parsingDiagnosticHandler: diagnosticHandler) + parsingDiagnosticHandler: diagnosticHandler + ) } } catch SwiftFormatError.fileNotReadable { diagnosticsEngine.emitError( - "Unable to format \(url.relativePath): file is not readable or does not exist.") + "Unable to format \(url.relativePath): file is not readable or does not exist." + ) return } catch SwiftFormatError.fileContainsInvalidSyntax { guard !lintFormatOptions.ignoreUnparsableFiles else { diff --git a/Sources/swift-format/Frontend/Frontend.swift b/Sources/swift-format/Frontend/Frontend.swift index 307335883..a3ea18a4f 100644 --- a/Sources/swift-format/Frontend/Frontend.swift +++ b/Sources/swift-format/Frontend/Frontend.swift @@ -12,8 +12,8 @@ import Foundation @_spi(Internal) import SwiftFormat -import SwiftSyntax import SwiftParser +import SwiftSyntax class Frontend { /// Represents a file to be processed by the frontend and any file-specific options associated @@ -89,7 +89,8 @@ class Frontend { self.lintFormatOptions = lintFormatOptions self.diagnosticPrinter = StderrDiagnosticPrinter( - colorMode: lintFormatOptions.colorDiagnostics.map { $0 ? .on : .off } ?? .auto) + colorMode: lintFormatOptions.colorDiagnostics.map { $0 ? .on : .off } ?? .auto + ) self.diagnosticsEngine = DiagnosticsEngine(diagnosticsHandlers: [diagnosticPrinter.printDiagnostic]) } @@ -101,7 +102,8 @@ class Frontend { } else { processURLs( lintFormatOptions.paths.map(URL.init(fileURLWithPath:)), - parallel: lintFormatOptions.parallel) + parallel: lintFormatOptions.parallel + ) } } @@ -119,9 +121,11 @@ class Frontend { private func processStandardInput() { let assumedUrl = lintFormatOptions.assumeFilename.map(URL.init(fileURLWithPath:)) - guard let configuration = configuration( - fromPathOrString: lintFormatOptions.configuration, - orInferredFromSwiftFileAt: assumedUrl) + guard + let configuration = configuration( + fromPathOrString: lintFormatOptions.configuration, + orInferredFromSwiftFileAt: assumedUrl + ) else { // Already diagnosed in the called method. return @@ -131,7 +135,8 @@ class Frontend { fileHandle: FileHandle.standardInput, url: assumedUrl ?? URL(fileURLWithPath: ""), configuration: configuration, - selection: Selection(offsetRanges: lintFormatOptions.offsets)) + selection: Selection(offsetRanges: lintFormatOptions.offsets) + ) processFile(fileToProcess) } @@ -139,7 +144,8 @@ class Frontend { private func processURLs(_ urls: [URL], parallel: Bool) { precondition( !urls.isEmpty, - "processURLs(_:) should only be called when 'urls' is non-empty.") + "processURLs(_:) should only be called when 'urls' is non-empty." + ) if parallel { let filesToProcess = @@ -161,14 +167,16 @@ class Frontend { private func openAndPrepareFile(at url: URL) -> FileToProcess? { guard let sourceFile = try? FileHandle(forReadingFrom: url) else { diagnosticsEngine.emitError( - "Unable to open \(url.relativePath): file is not readable or does not exist") + "Unable to open \(url.relativePath): file is not readable or does not exist" + ) return nil } guard let configuration = configuration( fromPathOrString: lintFormatOptions.configuration, - orInferredFromSwiftFileAt: url) + orInferredFromSwiftFileAt: url + ) else { // Already diagnosed in the called method. return nil @@ -237,7 +245,8 @@ class Frontend { // Fall through to the default return at the end of the function. } catch { diagnosticsEngine.emitError( - "Unable to read configuration for \(swiftFileURL.path): \(error.localizedDescription)") + "Unable to read configuration for \(swiftFileURL.path): \(error.localizedDescription)" + ) return nil } } else { @@ -253,7 +262,8 @@ class Frontend { } } catch { diagnosticsEngine.emitError( - "Unable to read configuration for \(cwd): \(error.localizedDescription)") + "Unable to read configuration for \(cwd): \(error.localizedDescription)" + ) return nil } } diff --git a/Sources/swift-format/Frontend/LintFrontend.swift b/Sources/swift-format/Frontend/LintFrontend.swift index 4ef989826..f7c4ee52c 100644 --- a/Sources/swift-format/Frontend/LintFrontend.swift +++ b/Sources/swift-format/Frontend/LintFrontend.swift @@ -19,30 +19,35 @@ import SwiftSyntax class LintFrontend: Frontend { override func processFile(_ fileToProcess: FileToProcess) { let linter = SwiftLinter( - configuration: fileToProcess.configuration, findingConsumer: diagnosticsEngine.consumeFinding) + configuration: fileToProcess.configuration, + findingConsumer: diagnosticsEngine.consumeFinding + ) linter.debugOptions = debugOptions let url = fileToProcess.url guard let source = fileToProcess.sourceText else { diagnosticsEngine.emitError( - "Unable to lint \(url.relativePath): file is not readable or does not exist.") + "Unable to lint \(url.relativePath): file is not readable or does not exist." + ) return } do { try linter.lint( source: source, - assumingFileURL: url) { (diagnostic, location) in - guard !self.lintFormatOptions.ignoreUnparsableFiles else { - // No diagnostics should be emitted in this mode. - return - } - self.diagnosticsEngine.consumeParserDiagnostic(diagnostic, location) + assumingFileURL: url + ) { (diagnostic, location) in + guard !self.lintFormatOptions.ignoreUnparsableFiles else { + // No diagnostics should be emitted in this mode. + return + } + self.diagnosticsEngine.consumeParserDiagnostic(diagnostic, location) } } catch SwiftFormatError.fileNotReadable { diagnosticsEngine.emitError( - "Unable to lint \(url.relativePath): file is not readable or does not exist.") + "Unable to lint \(url.relativePath): file is not readable or does not exist." + ) return } catch SwiftFormatError.fileContainsInvalidSyntax { guard !lintFormatOptions.ignoreUnparsableFiles else { diff --git a/Sources/swift-format/Subcommands/DumpConfiguration.swift b/Sources/swift-format/Subcommands/DumpConfiguration.swift index 9e6f03c43..ff41c8554 100644 --- a/Sources/swift-format/Subcommands/DumpConfiguration.swift +++ b/Sources/swift-format/Subcommands/DumpConfiguration.swift @@ -18,7 +18,8 @@ extension SwiftFormatCommand { /// Dumps the tool's default configuration in JSON format to standard output. struct DumpConfiguration: ParsableCommand { static var configuration = CommandConfiguration( - abstract: "Dump the default configuration in JSON format to standard output") + abstract: "Dump the default configuration in JSON format to standard output" + ) func run() throws { let configuration = Configuration() @@ -34,7 +35,8 @@ extension SwiftFormatCommand { // This should never happen, but let's make sure we fail more gracefully than crashing, just // in case. throw FormatError( - message: "Could not dump the default configuration: the JSON was not valid UTF-8") + message: "Could not dump the default configuration: the JSON was not valid UTF-8" + ) } print(jsonString) } catch { diff --git a/Sources/swift-format/Subcommands/Format.swift b/Sources/swift-format/Subcommands/Format.swift index 548e30e18..42c2da165 100644 --- a/Sources/swift-format/Subcommands/Format.swift +++ b/Sources/swift-format/Subcommands/Format.swift @@ -17,14 +17,16 @@ extension SwiftFormatCommand { struct Format: ParsableCommand { static var configuration = CommandConfiguration( abstract: "Format Swift source code", - discussion: "When no files are specified, it expects the source from standard input.") + discussion: "When no files are specified, it expects the source from standard input." + ) /// Whether or not to format the Swift file in-place. /// /// If specified, the current file is overwritten when formatting. @Flag( name: .shortAndLong, - help: "Overwrite the current file when formatting.") + help: "Overwrite the current file when formatting." + ) var inPlace: Bool = false @OptionGroup() diff --git a/Sources/swift-format/Subcommands/Lint.swift b/Sources/swift-format/Subcommands/Lint.swift index 43b3872a9..3002c5912 100644 --- a/Sources/swift-format/Subcommands/Lint.swift +++ b/Sources/swift-format/Subcommands/Lint.swift @@ -17,11 +17,12 @@ extension SwiftFormatCommand { struct Lint: ParsableCommand { static var configuration = CommandConfiguration( abstract: "Diagnose style issues in Swift source code", - discussion: "When no files are specified, it expects the source from standard input.") + discussion: "When no files are specified, it expects the source from standard input." + ) @OptionGroup() var lintOptions: LintFormatOptions - + @Flag( name: .shortAndLong, help: "Fail on warnings." @@ -35,7 +36,7 @@ extension SwiftFormatCommand { try performanceMeasurementOptions.printingInstructionCountIfRequested { let frontend = LintFrontend(lintFormatOptions: lintOptions) frontend.run() - + if frontend.diagnosticsEngine.hasErrors || strict && frontend.diagnosticsEngine.hasWarnings { throw ExitCode.failure } diff --git a/Sources/swift-format/Subcommands/LintFormatOptions.swift b/Sources/swift-format/Subcommands/LintFormatOptions.swift index 098ad25d1..bd15dc4e7 100644 --- a/Sources/swift-format/Subcommands/LintFormatOptions.swift +++ b/Sources/swift-format/Subcommands/LintFormatOptions.swift @@ -23,7 +23,8 @@ struct LintFormatOptions: ParsableArguments { help: """ The path to a JSON file containing the configuration of the linter/formatter or a JSON \ string containing the configuration directly. - """) + """ + ) var configuration: String? /// A list of comma-separated "start:end" pairs specifying UTF-8 offsets of the ranges to format. @@ -34,7 +35,8 @@ struct LintFormatOptions: ParsableArguments { help: """ A "start:end" pair specifying UTF-8 offsets of the range to format. Multiple ranges can be formatted by specifying several --offsets arguments. - """) + """ + ) var offsets: [Range] = [] /// The filename for the source code when reading from standard input, to include in diagnostic @@ -50,23 +52,27 @@ struct LintFormatOptions: ParsableArguments { /// If set, we recursively run on all ".swift" files in any provided directories. @Flag( name: .shortAndLong, - help: "Recursively run on '.swift' files in any provided directories.") + help: "Recursively run on '.swift' files in any provided directories." + ) var recursive: Bool = false /// Whether unparsable files, due to syntax errors or unrecognized syntax, should be ignored or /// treated as containing an error. When ignored, unparsable files are output verbatim in format /// mode and no diagnostics are raised in lint mode. When not ignored, unparsable files raise a /// diagnostic in both format and lint mode. - @Flag(help: """ - Ignores unparsable files, disabling all diagnostics and formatting for files that contain \ - invalid syntax. - """) + @Flag( + help: """ + Ignores unparsable files, disabling all diagnostics and formatting for files that contain \ + invalid syntax. + """ + ) var ignoreUnparsableFiles: Bool = false /// Whether or not to run the formatter/linter in parallel. @Flag( name: .shortAndLong, - help: "Process files in parallel, simultaneously across multiple cores.") + help: "Process files in parallel, simultaneously across multiple cores." + ) var parallel: Bool = false /// Whether colors should be used in diagnostics printed to standard error. @@ -79,14 +85,17 @@ struct LintFormatOptions: ParsableArguments { Enables or disables color diagnostics when printing to standard error. The default behavior \ if this flag is omitted is to use colors if standard error is connected to a terminal, and \ to not use colors otherwise. - """) + """ + ) var colorDiagnostics: Bool? /// Whether symlinks should be followed. - @Flag(help: """ - Follow symbolic links passed on the command line, or found during directory traversal when \ - using `-r/--recursive`. - """) + @Flag( + help: """ + Follow symbolic links passed on the command line, or found during directory traversal when \ + using `-r/--recursive`. + """ + ) var followSymlinks: Bool = false /// The list of paths to Swift source files that should be formatted or linted. @@ -129,7 +138,7 @@ extension Range { public init?(argument: String) { let pair = argument.components(separatedBy: ":") if pair.count == 2, let start = Int(pair[0]), let end = Int(pair[1]), start <= end { - self = start ..< end + self = start.. { } #if compiler(>=6) -extension Range : @retroactive ExpressibleByArgument {} +extension Range: @retroactive ExpressibleByArgument {} #else -extension Range : ExpressibleByArgument {} +extension Range: ExpressibleByArgument {} #endif diff --git a/Sources/swift-format/Utilities/DiagnosticsEngine.swift b/Sources/swift-format/Utilities/DiagnosticsEngine.swift index a6cd6978f..220a2a23c 100644 --- a/Sources/swift-format/Utilities/DiagnosticsEngine.swift +++ b/Sources/swift-format/Utilities/DiagnosticsEngine.swift @@ -10,9 +10,9 @@ // //===----------------------------------------------------------------------===// +import SwiftDiagnostics import SwiftFormat import SwiftSyntax -import SwiftDiagnostics /// Unifies the handling of findings from the linter, parsing errors from the syntax parser, and /// generic errors from the frontend so that they are emitted in a uniform fashion. @@ -62,7 +62,9 @@ final class DiagnosticsEngine { Diagnostic( severity: .error, location: location.map(Diagnostic.Location.init), - message: message)) + message: message + ) + ) } /// Emits a generic warning message. @@ -76,7 +78,9 @@ final class DiagnosticsEngine { Diagnostic( severity: .warning, location: location.map(Diagnostic.Location.init), - message: message)) + message: message + ) + ) } /// Emits a finding from the linter and any of its associated notes as diagnostics. @@ -90,7 +94,9 @@ final class DiagnosticsEngine { Diagnostic( severity: .note, location: note.location.map(Diagnostic.Location.init), - message: "\(note.message)")) + message: "\(note.message)" + ) + ) } } @@ -115,13 +121,14 @@ final class DiagnosticsEngine { case .error: severity = .error case .warning: severity = .warning case .note: severity = .note - case .remark: severity = .note // should we model this? + case .remark: severity = .note // should we model this? } return Diagnostic( severity: severity, location: Diagnostic.Location(location), category: nil, - message: message.message) + message: message.message + ) } /// Converts a lint finding into a diagnostic message that can be used by the `TSCBasic` @@ -138,6 +145,7 @@ final class DiagnosticsEngine { severity: severity, location: finding.location.map(Diagnostic.Location.init), category: "\(finding.category)", - message: "\(finding.message.text)") + message: "\(finding.message.text)" + ) } } diff --git a/Sources/swift-format/Utilities/FormatError.swift b/Sources/swift-format/Utilities/FormatError.swift index 5b325cc57..b922038ee 100644 --- a/Sources/swift-format/Utilities/FormatError.swift +++ b/Sources/swift-format/Utilities/FormatError.swift @@ -15,10 +15,9 @@ import Foundation struct FormatError: LocalizedError { var message: String var errorDescription: String? { message } - + static var exitWithDiagnosticErrors: FormatError { // The diagnostics engine has already printed errors to stderr. FormatError(message: "") } } - diff --git a/Sources/swift-format/Utilities/TTY.swift b/Sources/swift-format/Utilities/TTY.swift index 35fc35841..3097b1611 100644 --- a/Sources/swift-format/Utilities/TTY.swift +++ b/Sources/swift-format/Utilities/TTY.swift @@ -17,13 +17,13 @@ func isTTY(_ fileHandle: FileHandle) -> Bool { // The implementation of this function is adapted from `TerminalController.swift` in // swift-tools-support-core. #if os(Windows) - // The TSC implementation of this function only returns `.file` or `.dumb` for Windows, - // neither of which is a TTY. - return false + // The TSC implementation of this function only returns `.file` or `.dumb` for Windows, + // neither of which is a TTY. + return false #else - if ProcessInfo.processInfo.environment["TERM"] == "dumb" { - return false - } - return isatty(fileHandle.fileDescriptor) != 0 + if ProcessInfo.processInfo.environment["TERM"] == "dumb" { + return false + } + return isatty(fileHandle.fileDescriptor) != 0 #endif } diff --git a/Tests/SwiftFormatPerformanceTests/WhitespaceLinterPerformanceTests.swift b/Tests/SwiftFormatPerformanceTests/WhitespaceLinterPerformanceTests.swift index 960033604..b50b23aca 100644 --- a/Tests/SwiftFormatPerformanceTests/WhitespaceLinterPerformanceTests.swift +++ b/Tests/SwiftFormatPerformanceTests/WhitespaceLinterPerformanceTests.swift @@ -1,8 +1,7 @@ -import SwiftSyntax +@_spi(Testing) import SwiftFormat import SwiftParser +import SwiftSyntax import XCTest - -@_spi(Testing) import SwiftFormat @_spi(Testing) import _SwiftFormatTestSupport final class WhitespaceLinterPerformanceTests: DiagnosingTestCase { @@ -58,8 +57,11 @@ final class WhitespaceLinterPerformanceTests: DiagnosingTestCase { /// - expected: The formatted text. private func performWhitespaceLint(input: String, expected: String) { let sourceFileSyntax = Parser.parse(source: input) - let context = makeContext(sourceFileSyntax: sourceFileSyntax, selection: .infinite, - findingConsumer: { _ in }) + let context = makeContext( + sourceFileSyntax: sourceFileSyntax, + selection: .infinite, + findingConsumer: { _ in } + ) let linter = WhitespaceLinter(user: input, formatted: expected, context: context) linter.lint() } diff --git a/Tests/SwiftFormatTests/Core/DocumentationCommentTests.swift b/Tests/SwiftFormatTests/Core/DocumentationCommentTests.swift index 7094e5b1d..55af641ef 100644 --- a/Tests/SwiftFormatTests/Core/DocumentationCommentTests.swift +++ b/Tests/SwiftFormatTests/Core/DocumentationCommentTests.swift @@ -1,10 +1,9 @@ import Markdown +@_spi(Testing) import SwiftFormat import SwiftSyntax import SwiftSyntaxBuilder import XCTest -@_spi(Testing) import SwiftFormat - final class DocumentationCommentTests: XCTestCase { func testBriefSummaryOnly() throws { let decl: DeclSyntax = """ @@ -17,14 +16,15 @@ final class DocumentationCommentTests: XCTestCase { """ Paragraph └─ Text "A brief summary." - """) + """ + ) XCTAssertTrue(comment.bodyNodes.isEmpty) XCTAssertNil(comment.parameterLayout) XCTAssertTrue(comment.parameters.isEmpty) XCTAssertNil(comment.returns) XCTAssertNil(comment.throws) } - + func testBriefSummaryAndAdditionalParagraphs() throws { let decl: DeclSyntax = """ /// A brief summary. @@ -40,7 +40,8 @@ final class DocumentationCommentTests: XCTestCase { """ Paragraph └─ Text "A brief summary." - """) + """ + ) XCTAssertEqual( comment.bodyNodes.map { $0.debugDescription() }, [ @@ -59,7 +60,7 @@ final class DocumentationCommentTests: XCTestCase { XCTAssertNil(comment.returns) XCTAssertNil(comment.throws) } - + func testParameterOutline() throws { let decl: DeclSyntax = """ /// - Parameters: @@ -91,7 +92,7 @@ final class DocumentationCommentTests: XCTestCase { XCTAssertNil(comment.returns) XCTAssertNil(comment.throws) } - + func testSeparatedParameters() throws { let decl: DeclSyntax = """ /// - Parameter x: A value. @@ -122,7 +123,7 @@ final class DocumentationCommentTests: XCTestCase { XCTAssertNil(comment.returns) XCTAssertNil(comment.throws) } - + func testMalformedTagsGoIntoBodyNodes() throws { let decl: DeclSyntax = """ /// - Parameter: A value. @@ -165,7 +166,7 @@ final class DocumentationCommentTests: XCTestCase { XCTAssertNil(comment.parameterLayout) XCTAssertTrue(comment.parameters.isEmpty) } - + func testReturnsField() throws { let decl: DeclSyntax = """ /// - Returns: A value. @@ -187,7 +188,7 @@ final class DocumentationCommentTests: XCTestCase { ) XCTAssertNil(comment.throws) } - + func testThrowsField() throws { let decl: DeclSyntax = """ /// - Throws: An error. @@ -199,7 +200,7 @@ final class DocumentationCommentTests: XCTestCase { XCTAssertNil(comment.parameterLayout) XCTAssertTrue(comment.parameters.isEmpty) XCTAssertNil(comment.returns) - + let throwsField = try XCTUnwrap(comment.throws) XCTAssertEqual( throwsField.debugDescription(), @@ -209,7 +210,7 @@ final class DocumentationCommentTests: XCTestCase { """ ) } - + func testUnrecognizedFieldsGoIntoBodyNodes() throws { let decl: DeclSyntax = """ /// - Blahblah: Blah. diff --git a/Tests/SwiftFormatTests/Core/DocumentationCommentTextTests.swift b/Tests/SwiftFormatTests/Core/DocumentationCommentTextTests.swift index 4a1f8302f..a7a16e70d 100644 --- a/Tests/SwiftFormatTests/Core/DocumentationCommentTextTests.swift +++ b/Tests/SwiftFormatTests/Core/DocumentationCommentTextTests.swift @@ -1,9 +1,8 @@ +@_spi(Testing) import SwiftFormat import SwiftSyntax import SwiftSyntaxBuilder import XCTest -@_spi(Testing) import SwiftFormat - final class DocumentationCommentTextTests: XCTestCase { func testSimpleDocLineComment() throws { let decl: DeclSyntax = """ @@ -16,11 +15,11 @@ final class DocumentationCommentTextTests: XCTestCase { commentText.text, """ A simple doc comment. - + """ ) } - + func testOneLineDocBlockComment() throws { let decl: DeclSyntax = """ /** A simple doc comment. */ @@ -32,11 +31,11 @@ final class DocumentationCommentTextTests: XCTestCase { commentText.text, """ A simple doc comment.\u{0020} - + """ ) } - + func testDocBlockCommentWithASCIIArt() throws { let decl: DeclSyntax = """ /** @@ -50,7 +49,7 @@ final class DocumentationCommentTextTests: XCTestCase { commentText.text, """ A simple doc comment. - + """ ) } @@ -86,11 +85,11 @@ final class DocumentationCommentTextTests: XCTestCase { commentText.text, """ A simple doc comment. - + """ ) } - + func testMultilineDocLineComment() throws { let decl: DeclSyntax = """ /// A doc comment. @@ -108,21 +107,21 @@ final class DocumentationCommentTextTests: XCTestCase { commentText.text, """ A doc comment. - + This is a longer paragraph, containing more detail. - + - Parameter x: A parameter. - Returns: A value. - + """ ) } - + func testDocLineCommentStopsAtBlankLine() throws { let decl: DeclSyntax = """ /// This should not be part of the comment. - + /// A doc comment. func f(x: Int) -> Int {} """ @@ -132,15 +131,15 @@ final class DocumentationCommentTextTests: XCTestCase { commentText.text, """ A doc comment. - + """ ) } - + func testDocBlockCommentStopsAtBlankLine() throws { let decl: DeclSyntax = """ /** This should not be part of the comment. */ - + /** * This is part of the comment. */ @@ -154,7 +153,7 @@ final class DocumentationCommentTextTests: XCTestCase { """ This is part of the comment. so is this\u{0020} - + """ ) } diff --git a/Tests/SwiftFormatTests/Core/RuleMaskTests.swift b/Tests/SwiftFormatTests/Core/RuleMaskTests.swift index 0984b7f8a..4e46ac635 100644 --- a/Tests/SwiftFormatTests/Core/RuleMaskTests.swift +++ b/Tests/SwiftFormatTests/Core/RuleMaskTests.swift @@ -1,9 +1,8 @@ -import SwiftSyntax +@_spi(Testing) import SwiftFormat import SwiftParser +import SwiftSyntax import XCTest -@_spi(Testing) import SwiftFormat - final class RuleMaskTests: XCTestCase { /// The source converter for the text in the current test. This is implicitly unwrapped because /// each test case must prepare some source text before performing any assertions, otherwise diff --git a/Tests/SwiftFormatTests/PrettyPrint/ArrayDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ArrayDeclTests.swift index c65b3b7fe..389ce0853 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ArrayDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ArrayDeclTests.swift @@ -54,15 +54,15 @@ final class ArrayDeclTests: PrettyPrintTestCase { ] """ - // Ideally, this array would be left on 1 line without a trailing comma. We don't know if the - // comma is required when calculating the length of array elements, so the comma's length is - // always added to last element and that 1 character causes the newlines inside of the array. - + """ - let a = [ - 11111111, 2222222, 33333333, 444444, - ] + // Ideally, this array would be left on 1 line without a trailing comma. We don't know if the + // comma is required when calculating the length of array elements, so the comma's length is + // always added to last element and that 1 character causes the newlines inside of the array. + + """ + let a = [ + 11111111, 2222222, 33333333, 444444, + ] - """ + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 45) } @@ -278,15 +278,15 @@ final class ArrayDeclTests: PrettyPrintTestCase { ] """ - // Ideally, this array would be left on 1 line without a trailing comma. We don't know if the - // comma is required when calculating the length of array elements, so the comma's length is - // always added to last element and that 1 character causes the newlines inside of the array. - + """ - a = [ - ("az", "by"), ("cf", "de"), - ] + // Ideally, this array would be left on 1 line without a trailing comma. We don't know if the + // comma is required when calculating the length of array elements, so the comma's length is + // always added to last element and that 1 character causes the newlines inside of the array. + + """ + a = [ + ("az", "by"), ("cf", "de"), + ] - """ + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 32) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/AssignmentExprTests.swift b/Tests/SwiftFormatTests/PrettyPrint/AssignmentExprTests.swift index 77d505be6..2ab1b1d92 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/AssignmentExprTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/AssignmentExprTests.swift @@ -47,93 +47,101 @@ final class AssignmentExprTests: PrettyPrintTestCase { func testAssignmentOperatorFromSequenceWithFunctionCalls() { let input = - """ - result = firstOp + secondOp + someOpFetchingFunc(foo, bar: bar, baz: baz) - result = someOpFetchingFunc(foo, bar: bar, baz: baz) - result += someOpFetchingFunc(foo, bar: bar, baz: baz) - result = someOpFetchingFunc(foo, bar: bar, baz: baz) + someOtherOperand + andAThirdOneForReasons - result = firstOp + secondOp + thirdOp + someOpFetchingFunc(foo, bar, baz) + nextOp + lastOp - result += firstOp + secondOp + thirdOp + someOpFetchingFunc(foo, bar, baz) + nextOp + lastOp - """ - - let expectedWithArgBinPacking = - """ - result = - firstOp + secondOp - + someOpFetchingFunc( - foo, bar: bar, baz: baz) - result = someOpFetchingFunc( + """ + result = firstOp + secondOp + someOpFetchingFunc(foo, bar: bar, baz: baz) + result = someOpFetchingFunc(foo, bar: bar, baz: baz) + result += someOpFetchingFunc(foo, bar: bar, baz: baz) + result = someOpFetchingFunc(foo, bar: bar, baz: baz) + someOtherOperand + andAThirdOneForReasons + result = firstOp + secondOp + thirdOp + someOpFetchingFunc(foo, bar, baz) + nextOp + lastOp + result += firstOp + secondOp + thirdOp + someOpFetchingFunc(foo, bar, baz) + nextOp + lastOp + """ + + let expectedWithArgBinPacking = + """ + result = + firstOp + secondOp + + someOpFetchingFunc( foo, bar: bar, baz: baz) - result += someOpFetchingFunc( + result = someOpFetchingFunc( + foo, bar: bar, baz: baz) + result += someOpFetchingFunc( + foo, bar: bar, baz: baz) + result = + someOpFetchingFunc( foo, bar: bar, baz: baz) - result = - someOpFetchingFunc( - foo, bar: bar, baz: baz) - + someOtherOperand - + andAThirdOneForReasons - result = - firstOp + secondOp + thirdOp - + someOpFetchingFunc( - foo, bar, baz) + nextOp - + lastOp - result += - firstOp + secondOp + thirdOp - + someOpFetchingFunc( - foo, bar, baz) + nextOp - + lastOp - - """ - - var config = Configuration.forTesting - config.lineBreakBeforeEachArgument = false - assertPrettyPrintEqual( - input: input, expected: expectedWithArgBinPacking, linelength: 35, configuration: config) - - let expectedWithBreakBeforeEachArg = - """ - result = - firstOp + secondOp - + someOpFetchingFunc( - foo, - bar: bar, - baz: baz - ) - result = someOpFetchingFunc( + + someOtherOperand + + andAThirdOneForReasons + result = + firstOp + secondOp + thirdOp + + someOpFetchingFunc( + foo, bar, baz) + nextOp + + lastOp + result += + firstOp + secondOp + thirdOp + + someOpFetchingFunc( + foo, bar, baz) + nextOp + + lastOp + + """ + + var config = Configuration.forTesting + config.lineBreakBeforeEachArgument = false + assertPrettyPrintEqual( + input: input, + expected: expectedWithArgBinPacking, + linelength: 35, + configuration: config + ) + + let expectedWithBreakBeforeEachArg = + """ + result = + firstOp + secondOp + + someOpFetchingFunc( foo, bar: bar, baz: baz ) - result += someOpFetchingFunc( + result = someOpFetchingFunc( + foo, + bar: bar, + baz: baz + ) + result += someOpFetchingFunc( + foo, + bar: bar, + baz: baz + ) + result = + someOpFetchingFunc( foo, bar: bar, baz: baz - ) - result = - someOpFetchingFunc( - foo, - bar: bar, - baz: baz - ) + someOtherOperand - + andAThirdOneForReasons - result = - firstOp + secondOp + thirdOp - + someOpFetchingFunc( - foo, - bar, - baz - ) + nextOp + lastOp - result += - firstOp + secondOp + thirdOp - + someOpFetchingFunc( - foo, - bar, - baz - ) + nextOp + lastOp - - """ - config.lineBreakBeforeEachArgument = true - assertPrettyPrintEqual( - input: input, expected: expectedWithBreakBeforeEachArg, linelength: 35, configuration: config) + ) + someOtherOperand + + andAThirdOneForReasons + result = + firstOp + secondOp + thirdOp + + someOpFetchingFunc( + foo, + bar, + baz + ) + nextOp + lastOp + result += + firstOp + secondOp + thirdOp + + someOpFetchingFunc( + foo, + bar, + baz + ) + nextOp + lastOp + + """ + config.lineBreakBeforeEachArgument = true + assertPrettyPrintEqual( + input: input, + expected: expectedWithBreakBeforeEachArg, + linelength: 35, + configuration: config + ) } func testAssignmentPatternBindingFromSequenceWithFunctionCalls() { @@ -169,7 +177,11 @@ final class AssignmentExprTests: PrettyPrintTestCase { var config = Configuration.forTesting config.lineBreakBeforeEachArgument = false assertPrettyPrintEqual( - input: input, expected: expectedWithArgBinPacking, linelength: 35, configuration: config) + input: input, + expected: expectedWithArgBinPacking, + linelength: 35, + configuration: config + ) let expectedWithBreakBeforeEachArg = """ @@ -203,6 +215,10 @@ final class AssignmentExprTests: PrettyPrintTestCase { """ config.lineBreakBeforeEachArgument = true assertPrettyPrintEqual( - input: input, expected: expectedWithBreakBeforeEachArg, linelength: 35, configuration: config) + input: input, + expected: expectedWithBreakBeforeEachArg, + linelength: 35, + configuration: config + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift b/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift index 668df4de2..3776b10f7 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift @@ -127,7 +127,11 @@ final class AttributeTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakBeforeEachArgument = true assertPrettyPrintEqual( - input: input, expected: expected, linelength: 32, configuration: configuration) + input: input, + expected: expected, + linelength: 32, + configuration: configuration + ) } func testAttributeFormattingRespectsDiscretionaryLineBreaks() { @@ -203,7 +207,11 @@ final class AttributeTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakBeforeEachArgument = true assertPrettyPrintEqual( - input: input, expected: expected, linelength: 40, configuration: configuration) + input: input, + expected: expected, + linelength: 40, + configuration: configuration + ) } func testObjCBinPackedAttributes() { @@ -240,43 +248,47 @@ final class AttributeTests: PrettyPrintTestCase { } func testObjCAttributesPerLineBreaking() { - let input = - """ - @objc func f() {} - @objc(foo:bar:baz) - func f() {} - @objc(thisMethodHasAVeryLongName:foo:bar:) - func f() {} - @objc(thisMethodHasAVeryLongName:andThisArgumentHasANameToo:soDoesThisOne:bar:) - func f() {} - """ - - let expected = - """ - @objc func f() {} - @objc(foo:bar:baz) - func f() {} - @objc( - thisMethodHasAVeryLongName: - foo: - bar: - ) - func f() {} - @objc( - thisMethodHasAVeryLongName: - andThisArgumentHasANameToo: - soDoesThisOne: - bar: - ) - func f() {} - - """ - - var configuration = Configuration.forTesting - configuration.lineBreakBeforeEachArgument = true - assertPrettyPrintEqual( - input: input, expected: expected, linelength: 40, configuration: configuration) - } + let input = + """ + @objc func f() {} + @objc(foo:bar:baz) + func f() {} + @objc(thisMethodHasAVeryLongName:foo:bar:) + func f() {} + @objc(thisMethodHasAVeryLongName:andThisArgumentHasANameToo:soDoesThisOne:bar:) + func f() {} + """ + + let expected = + """ + @objc func f() {} + @objc(foo:bar:baz) + func f() {} + @objc( + thisMethodHasAVeryLongName: + foo: + bar: + ) + func f() {} + @objc( + thisMethodHasAVeryLongName: + andThisArgumentHasANameToo: + soDoesThisOne: + bar: + ) + func f() {} + + """ + + var configuration = Configuration.forTesting + configuration.lineBreakBeforeEachArgument = true + assertPrettyPrintEqual( + input: input, + expected: expected, + linelength: 40, + configuration: configuration + ) + } func testObjCAttributesDiscretionaryLineBreaking() { // The discretionary newlines in the 3rd function declaration are invalid, because new lines @@ -572,9 +584,9 @@ final class AttributeTests: PrettyPrintTestCase { } """ - var configuration = Configuration.forTesting - configuration.lineBreakBetweenDeclarationAttributes = true - assertPrettyPrintEqual(input: input, expected: expected, linelength: 80, configuration: configuration) + var configuration = Configuration.forTesting + configuration.lineBreakBetweenDeclarationAttributes = true + assertPrettyPrintEqual(input: input, expected: expected, linelength: 80, configuration: configuration) } func testAttributesStartWithPoundIf() { @@ -585,7 +597,7 @@ final class AttributeTests: PrettyPrintTestCase { @_spi(Foo) #endif public let myVar = "Test" - + """ let expected = """ @@ -594,9 +606,9 @@ final class AttributeTests: PrettyPrintTestCase { @_spi(Foo) #endif public let myVar = "Test" - + """ - + assertPrettyPrintEqual(input: input, expected: expected, linelength: 45) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/BinaryOperatorExprTests.swift b/Tests/SwiftFormatTests/PrettyPrint/BinaryOperatorExprTests.swift index 50b283bd6..1d2bd6492 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/BinaryOperatorExprTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/BinaryOperatorExprTests.swift @@ -53,7 +53,11 @@ final class BinaryOperatorExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.spacesAroundRangeFormationOperators = false assertPrettyPrintEqual( - input: input, expected: expected, linelength: 80, configuration: configuration) + input: input, + expected: expected, + linelength: 80, + configuration: configuration + ) } func testRangeFormationOperatorCompaction_spacesAroundRangeFormation() { @@ -81,7 +85,11 @@ final class BinaryOperatorExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.spacesAroundRangeFormationOperators = true assertPrettyPrintEqual( - input: input, expected: expected, linelength: 80, configuration: configuration) + input: input, + expected: expected, + linelength: 80, + configuration: configuration + ) } func testRangeFormationOperatorsAreNotCompactedWhenFollowingAPostfixOperator() { diff --git a/Tests/SwiftFormatTests/PrettyPrint/ClassDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ClassDeclTests.swift index a69ffa1f5..985d4db66 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ClassDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ClassDeclTests.swift @@ -228,7 +228,7 @@ final class ClassDeclTests: PrettyPrintTestCase { func testClassWhereClause_lineBreakAfterGenericWhereClause() { let input = - """ + """ class MyClass where S: Collection { let A: Int let B: Double @@ -244,7 +244,7 @@ final class ClassDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ class MyClass where S: Collection { let A: Int let B: Double @@ -304,7 +304,7 @@ final class ClassDeclTests: PrettyPrintTestCase { func testClassWhereClauseWithInheritance_lineBreakAfterGenericWhereClause() { let input = - """ + """ class MyClass: SuperOne where S: Collection { let A: Int let B: Double @@ -320,7 +320,7 @@ final class ClassDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ class MyClass: SuperOne where S: Collection { let A: Int let B: Double @@ -431,7 +431,7 @@ final class ClassDeclTests: PrettyPrintTestCase { func testClassFullWrap_lineBreakAfterGenericWhereClause() { let input = - """ + """ public class MyContainer: MyContainerSuperclass, MyContainerProtocol, SomeoneElsesContainerProtocol, SomeFrameworkContainerProtocol where BaseCollection: Collection, BaseCollection: P, BaseCollection.Element: Equatable, BaseCollection.Element: SomeOtherProtocol { let A: Int let B: Double @@ -440,7 +440,7 @@ final class ClassDeclTests: PrettyPrintTestCase { let expected = - """ + """ public class MyContainer< BaseCollection, SecondCollection >: MyContainerSuperclass, MyContainerProtocol, diff --git a/Tests/SwiftFormatTests/PrettyPrint/ClosureExprTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ClosureExprTests.swift index 089aee1ba..eb437c253 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ClosureExprTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ClosureExprTests.swift @@ -189,7 +189,7 @@ final class ClosureExprTests: PrettyPrintTestCase { func testClosuresWithIfs() { let input = - """ + """ let a = afunc() { if condition1 { return true @@ -209,7 +209,7 @@ final class ClosureExprTests: PrettyPrintTestCase { """ let expected = - """ + """ let a = afunc() { if condition1 { return true @@ -482,7 +482,11 @@ final class ClosureExprTests: PrettyPrintTestCase { var config = Configuration.forTesting config.prioritizeKeepingFunctionOutputTogether = true assertPrettyPrintEqual( - input: input, expected: expectedKeepingOutputTogether, linelength: 50, configuration: config) + input: input, + expected: expectedKeepingOutputTogether, + linelength: 50, + configuration: config + ) } func testClosureSignatureAttributes() { diff --git a/Tests/SwiftFormatTests/PrettyPrint/CommaTests.swift b/Tests/SwiftFormatTests/PrettyPrint/CommaTests.swift index 70c05dfa7..c3c7766e5 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/CommaTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/CommaTests.swift @@ -9,9 +9,9 @@ final class CommaTests: PrettyPrintTestCase { 2, 3 ] - + """ - + let expected = """ let MyCollection = [ @@ -19,14 +19,14 @@ final class CommaTests: PrettyPrintTestCase { 2, 3, ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testArrayCommasAbsentDisabled() { let input = """ @@ -35,9 +35,9 @@ final class CommaTests: PrettyPrintTestCase { 2, 3 ] - + """ - + let expected = """ let MyCollection = [ @@ -45,14 +45,14 @@ final class CommaTests: PrettyPrintTestCase { 2, 3 ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testArrayCommasPresentEnabled() { let input = """ @@ -61,9 +61,9 @@ final class CommaTests: PrettyPrintTestCase { 2, 3, ] - + """ - + let expected = """ let MyCollection = [ @@ -71,14 +71,14 @@ final class CommaTests: PrettyPrintTestCase { 2, 3, ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testArrayCommasPresentDisabled() { let input = """ @@ -87,9 +87,9 @@ final class CommaTests: PrettyPrintTestCase { 2, 3, ] - + """ - + let expected = """ let MyCollection = [ @@ -97,52 +97,52 @@ final class CommaTests: PrettyPrintTestCase { 2, 3 ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testArraySingleLineCommasPresentEnabled() { let input = """ let MyCollection = [1, 2, 3,] - + """ - + // no effect expected let expected = """ let MyCollection = [1, 2, 3] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) } - + func testArraySingleLineCommasPresentDisabled() { let input = """ let MyCollection = [1, 2, 3,] - + """ - + // no effect expected let expected = """ let MyCollection = [1, 2, 3] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) } - + func testArrayWithCommentCommasPresentEnabled() { let input = """ @@ -152,21 +152,21 @@ final class CommaTests: PrettyPrintTestCase { ] """ - + let expected = """ let MyCollection = [ 1, 2, // some comment ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) } - + func testArrayWithCommentCommasPresentDisabled() { let input = """ @@ -176,21 +176,21 @@ final class CommaTests: PrettyPrintTestCase { ] """ - + let expected = """ let MyCollection = [ 1, 2 // some comment ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) } - + func testArrayWithTernaryOperatorAndCommentCommasPresentEnabled() { let input = """ @@ -200,21 +200,21 @@ final class CommaTests: PrettyPrintTestCase { ] """ - + let expected = """ let MyCollection = [ 1, true ? 1 : 2, // some comment ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) } - + func testArrayWithTernaryOperatorAndCommentCommasPresentDisabled() { let input = """ @@ -224,16 +224,16 @@ final class CommaTests: PrettyPrintTestCase { ] """ - + let expected = """ let MyCollection = [ 1, true ? 1 : 2 // some comment ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) @@ -247,9 +247,9 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3 ] - + """ - + let expected = """ let MyCollection = [ @@ -257,14 +257,14 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3, ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testDictionaryCommasAbsentDisabled() { let input = """ @@ -273,9 +273,9 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3 ] - + """ - + let expected = """ let MyCollection = [ @@ -283,14 +283,14 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3 ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testDictionaryCommasPresentEnabled() { let input = """ @@ -299,9 +299,9 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3, ] - + """ - + let expected = """ let MyCollection = [ @@ -309,14 +309,14 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3, ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testDictionaryCommasPresentDisabled() { let input = """ @@ -325,9 +325,9 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3, ] - + """ - + let expected = """ let MyCollection = [ @@ -335,49 +335,49 @@ final class CommaTests: PrettyPrintTestCase { "b": 2, "c": 3 ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 20, configuration: configuration) } - + func testDictionarySingleLineCommasPresentDisabled() { let input = """ let MyCollection = ["a": 1, "b": 2, "c": 3,] - + """ - + let expected = """ let MyCollection = [ "a": 1, "b": 2, "c": 3, ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) } - + func testDictionarySingleLineCommasPresentEnabled() { let input = """ let MyCollection = ["a": 1, "b": 2, "c": 3,] - + """ - + let expected = """ let MyCollection = [ "a": 1, "b": 2, "c": 3 ] - + """ - + var configuration = Configuration.forTesting configuration.multiElementCollectionTrailingCommas = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: configuration) diff --git a/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift b/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift index 52226bed5..99b2259e2 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift @@ -1,5 +1,5 @@ -import _SwiftFormatTestSupport import SwiftFormat +import _SwiftFormatTestSupport final class CommentTests: PrettyPrintTestCase { func testDocumentationComments() { @@ -202,141 +202,141 @@ final class CommentTests: PrettyPrintTestCase { func testLineCommentsWithCustomLeadingSpaces() { let pairs: [(String, String)] = [ - ( - """ - // Line Comment0 - - // Line Comment1 - // Line Comment2 - let a = 123 - let b = "456" // End of line comment - let c = "More content" - - """, - """ - // Line Comment0 - - // Line Comment1 - // Line Comment2 - let a = 123 - let b = "456" // End of line comment - let c = "More content" - - """ - ), - ( - """ - // Comment 3 - // Comment 4 - - let reallyLongVariableName = 123 // This comment should not wrap - // and should not combine with this comment - - func MyFun() { - // just a comment - } - """, - """ - // Comment 3 - // Comment 4 + ( + """ + // Line Comment0 - let reallyLongVariableName = 123 // This comment should not wrap - // and should not combine with this comment + // Line Comment1 + // Line Comment2 + let a = 123 + let b = "456" // End of line comment + let c = "More content" - func MyFun() { - // just a comment - } + """, + """ + // Line Comment0 - """ - ), - ( - """ - func MyFun() { - // Comment 1 - // Comment 2 - let a = 123 + // Line Comment1 + // Line Comment2 + let a = 123 + let b = "456" // End of line comment + let c = "More content" - let b = 456 // Comment 3 - } + """ + ), + ( + """ + // Comment 3 + // Comment 4 - func MyFun() { - let c = 789 // Comment 4 - // Comment 5 - } - """, - """ - func MyFun() { - // Comment 1 - // Comment 2 - let a = 123 - - let b = 456 // Comment 3 - } + let reallyLongVariableName = 123 // This comment should not wrap + // and should not combine with this comment - func MyFun() { - let c = 789 // Comment 4 - // Comment 5 - } + func MyFun() { + // just a comment + } + """, + """ + // Comment 3 + // Comment 4 - """ - ), - ( - """ - let a = myfun(123 // Cmt 7 - ) - let a = myfun(var1: 123 // Cmt 7 - ) + let reallyLongVariableName = 123 // This comment should not wrap + // and should not combine with this comment - guard condition else { return // Cmt 6 - } + func MyFun() { + // just a comment + } - switch myvar { - case .one, .two, // three - .four: - dostuff() - default: () - } + """ + ), + ( + """ + func MyFun() { + // Comment 1 + // Comment 2 + let a = 123 - """, - """ - let a = myfun( - 123 // Cmt 7 - ) - let a = myfun( - var1: 123 // Cmt 7 - ) - - guard condition else { - return // Cmt 6 - } + let b = 456 // Comment 3 + } - switch myvar { - case .one, .two, // three - .four: - dostuff() - default: () - } + func MyFun() { + let c = 789 // Comment 4 + // Comment 5 + } + """, + """ + func MyFun() { + // Comment 1 + // Comment 2 + let a = 123 + + let b = 456 // Comment 3 + } + + func MyFun() { + let c = 789 // Comment 4 + // Comment 5 + } + + """ + ), + ( + """ + let a = myfun(123 // Cmt 7 + ) + let a = myfun(var1: 123 // Cmt 7 + ) + + guard condition else { return // Cmt 6 + } + + switch myvar { + case .one, .two, // three + .four: + dostuff() + default: () + } - """ - ), - ( - """ - let a = 123 + // comment - b + c - - let d = 123 - // Trailing Comment - """, - """ - let a = - 123 // comment - + b + c - - let d = 123 - // Trailing Comment - - """ - ), + """, + """ + let a = myfun( + 123 // Cmt 7 + ) + let a = myfun( + var1: 123 // Cmt 7 + ) + + guard condition else { + return // Cmt 6 + } + + switch myvar { + case .one, .two, // three + .four: + dostuff() + default: () + } + + """ + ), + ( + """ + let a = 123 + // comment + b + c + + let d = 123 + // Trailing Comment + """, + """ + let a = + 123 // comment + + b + c + + let d = 123 + // Trailing Comment + + """ + ), ] var config = Configuration.forTesting @@ -1004,7 +1004,7 @@ final class CommentTests: PrettyPrintTestCase { linelength: 45, whitespaceOnly: true, findings: [ - FindingSpec("1️⃣", message: "move end-of-line comment that exceeds the line length"), + FindingSpec("1️⃣", message: "move end-of-line comment that exceeds the line length") ] ) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/ConsumeExprTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ConsumeExprTests.swift index 30a1b6a1c..dfe64d414 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ConsumeExprTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ConsumeExprTests.swift @@ -9,6 +9,7 @@ final class ConsumeExprTests: PrettyPrintTestCase { consume y """, - linelength: 16) + linelength: 16 + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/CopyExprSyntax.swift b/Tests/SwiftFormatTests/PrettyPrint/CopyExprSyntax.swift index 188121eef..5b6a65e95 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/CopyExprSyntax.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/CopyExprSyntax.swift @@ -9,6 +9,7 @@ final class CopyExprTests: PrettyPrintTestCase { copy y """, - linelength: 13) + linelength: 13 + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/DeclNameArgumentTests.swift b/Tests/SwiftFormatTests/PrettyPrint/DeclNameArgumentTests.swift index ea7dd2c4a..0d02ae3a5 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/DeclNameArgumentTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/DeclNameArgumentTests.swift @@ -148,4 +148,3 @@ final class DeclNameArgumentTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } } - diff --git a/Tests/SwiftFormatTests/PrettyPrint/DeinitializerDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/DeinitializerDeclTests.swift index fc4d3fc36..4c219eb6b 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/DeinitializerDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/DeinitializerDeclTests.swift @@ -83,7 +83,7 @@ final class DeinitializerDeclTests: PrettyPrintTestCase { } """ assertPrettyPrintEqual(input: input, expected: input + "\n", linelength: 50) - + let wrapped = """ class X { // diff --git a/Tests/SwiftFormatTests/PrettyPrint/DictionaryDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/DictionaryDeclTests.swift index d0df7747a..f903b9018 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/DictionaryDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/DictionaryDeclTests.swift @@ -59,16 +59,16 @@ final class DictionaryDeclTests: PrettyPrintTestCase { ] """ - // Ideally, this dictionary would be left on 1 line without a trailing comma. We don't know if - // the comma is required when calculating the length of elements, so the comma's length is - // always added to last element and that 1 character causes the newlines inside of the - // dictionary. - + """ - let a = [ - 10000: "abc", 20000: "def", 30000: "ghi", - ] + // Ideally, this dictionary would be left on 1 line without a trailing comma. We don't know if + // the comma is required when calculating the length of elements, so the comma's length is + // always added to last element and that 1 character causes the newlines inside of the + // dictionary. + + """ + let a = [ + 10000: "abc", 20000: "def", 30000: "ghi", + ] - """ + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 50) } @@ -277,16 +277,16 @@ final class DictionaryDeclTests: PrettyPrintTestCase { ] """ - // Ideally, this dictionary would be left on 1 line without a trailing comma. We don't know if - // the comma is required when calculating the length of elements, so the comma's length is - // always added to last element and that 1 character causes the newlines inside of the - // dictionary. - + """ - a = [ - k1: ("ab", "z"), k2: ("bc", "y"), - ] + // Ideally, this dictionary would be left on 1 line without a trailing comma. We don't know if + // the comma is required when calculating the length of elements, so the comma's length is + // always added to last element and that 1 character causes the newlines inside of the + // dictionary. + + """ + a = [ + k1: ("ab", "z"), k2: ("bc", "y"), + ] - """ + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 38) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/DiscardStmtTests.swift b/Tests/SwiftFormatTests/PrettyPrint/DiscardStmtTests.swift index 63637da85..172f04ea4 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/DiscardStmtTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/DiscardStmtTests.swift @@ -8,6 +8,7 @@ final class DiscardStmtTests: PrettyPrintTestCase { discard self """, - linelength: 9) + linelength: 9 + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/DoStmtTests.swift b/Tests/SwiftFormatTests/PrettyPrint/DoStmtTests.swift index ddeb3ea6a..2bda1fc27 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/DoStmtTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/DoStmtTests.swift @@ -66,21 +66,28 @@ final class DoStmtTests: PrettyPrintTestCase { } """ - assertPrettyPrintEqual(input: input, expected: - """ - do - throws(FooError) { - foo() - } + assertPrettyPrintEqual( + input: input, + expected: + """ + do + throws(FooError) { + foo() + } - """, linelength: 18) - assertPrettyPrintEqual(input: input, expected: - """ - do throws(FooError) { - foo() - } + """, + linelength: 18 + ) + assertPrettyPrintEqual( + input: input, + expected: + """ + do throws(FooError) { + foo() + } - """, linelength: 25) + """, + linelength: 25 + ) } } - diff --git a/Tests/SwiftFormatTests/PrettyPrint/EnumDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/EnumDeclTests.swift index 1561d8e8d..d51fbeae4 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/EnumDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/EnumDeclTests.swift @@ -285,7 +285,7 @@ final class EnumDeclTests: PrettyPrintTestCase { func testEnumWhereClause_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ enum MyEnum where S: Collection { case firstCase let B: Double @@ -301,7 +301,7 @@ final class EnumDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ enum MyEnum where S: Collection { case firstCase let B: Double @@ -373,7 +373,7 @@ final class EnumDeclTests: PrettyPrintTestCase { func testEnumWhereClauseWithInheritance_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ enum MyEnum: ProtoOne where S: Collection { case firstCase let B: Double @@ -389,7 +389,7 @@ final class EnumDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ enum MyEnum: ProtoOne where S: Collection { case firstCase let B: Double @@ -501,7 +501,7 @@ final class EnumDeclTests: PrettyPrintTestCase { func testEnumFullWrap_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ public enum MyEnum: MyContainerProtocolOne, MyContainerProtocolTwo, SomeoneElsesContainerProtocol, SomeFrameworkContainerProtocol where BaseCollection: Collection, BaseCollection: P, BaseCollection.Element: Equatable, BaseCollection.Element: SomeOtherProtocol { case firstCase let B: Double @@ -510,7 +510,7 @@ final class EnumDeclTests: PrettyPrintTestCase { let expected = - """ + """ public enum MyEnum< BaseCollection, SecondCollection >: MyContainerProtocolOne, MyContainerProtocolTwo, diff --git a/Tests/SwiftFormatTests/PrettyPrint/ExtensionDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ExtensionDeclTests.swift index f11a1eb5b..d9b2bbe62 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ExtensionDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ExtensionDeclTests.swift @@ -122,7 +122,7 @@ final class ExtensionDeclTests: PrettyPrintTestCase { func testExtensionWhereClause_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ extension MyExtension where S: Collection { let A: Int let B: Double @@ -138,7 +138,7 @@ final class ExtensionDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ extension MyExtension where S: Collection { let A: Int let B: Double @@ -210,7 +210,7 @@ final class ExtensionDeclTests: PrettyPrintTestCase { func testExtensionWhereClauseWithInheritance_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ extension MyExtension: ProtoOne where S: Collection { let A: Int let B: Double @@ -226,7 +226,7 @@ final class ExtensionDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ extension MyExtension: ProtoOne where S: Collection { let A: Int let B: Double @@ -336,7 +336,7 @@ final class ExtensionDeclTests: PrettyPrintTestCase { func testExtensionFullWrap_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ public extension MyContainer: MyContainerProtocolOne, MyContainerProtocolTwo, SomeoneElsesContainerProtocol, SomeFrameworkContainerProtocol where BaseCollection: Collection, BaseCollection: P, BaseCollection.Element: Equatable, BaseCollection.Element: SomeOtherProtocol { let A: Int let B: Double @@ -345,7 +345,7 @@ final class ExtensionDeclTests: PrettyPrintTestCase { let expected = - """ + """ public extension MyContainer: MyContainerProtocolOne, MyContainerProtocolTwo, SomeoneElsesContainerProtocol, diff --git a/Tests/SwiftFormatTests/PrettyPrint/FunctionDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/FunctionDeclTests.swift index 5d94fa5f2..743f11dca 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/FunctionDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/FunctionDeclTests.swift @@ -359,7 +359,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testFunctionWhereClause_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ public func index( of element: Element, in collection: Elements ) -> Elements.Index? where Elements.Element == Element { @@ -385,7 +385,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ public func index( of element: Element, in collection: Elements ) -> Elements.Index? @@ -447,7 +447,6 @@ final class FunctionDeclTests: PrettyPrintTestCase { } """ - let expected = """ func myFun() { @@ -556,67 +555,67 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testFunctionFullWrap() { let input = - """ - @discardableResult @objc - public func index(of element: Element, in collection: Elements) -> Elements.Index? where Element: Foo, Element: Bar, Elements.Element == Element { - let a = 123 - let b = "abc" - } - """ + """ + @discardableResult @objc + public func index(of element: Element, in collection: Elements) -> Elements.Index? where Element: Foo, Element: Bar, Elements.Element == Element { + let a = 123 + let b = "abc" + } + """ let expected = - """ - @discardableResult @objc - public func index< - Elements: Collection, - Element - >( - of element: Element, - in collection: Elements - ) -> Elements.Index? - where - Element: Foo, Element: Bar, - Elements.Element == Element - { - let a = 123 - let b = "abc" - } - - """ + """ + @discardableResult @objc + public func index< + Elements: Collection, + Element + >( + of element: Element, + in collection: Elements + ) -> Elements.Index? + where + Element: Foo, Element: Bar, + Elements.Element == Element + { + let a = 123 + let b = "abc" + } + + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 30) } func testFunctionFullWrap_lineBreakBeforeEachGenericRequirement() { let input = - """ - @discardableResult @objc - public func index(of element: Element, in collection: Elements) -> Elements.Index? where Element: Foo, Element: Bar, Elements.Element == Element { - let a = 123 - let b = "abc" - } - """ + """ + @discardableResult @objc + public func index(of element: Element, in collection: Elements) -> Elements.Index? where Element: Foo, Element: Bar, Elements.Element == Element { + let a = 123 + let b = "abc" + } + """ let expected = - """ - @discardableResult @objc - public func index< - Elements: Collection, - Element - >( - of element: Element, - in collection: Elements - ) -> Elements.Index? - where - Element: Foo, - Element: Bar, - Elements.Element == Element - { - let a = 123 - let b = "abc" - } - - """ + """ + @discardableResult @objc + public func index< + Elements: Collection, + Element + >( + of element: Element, + in collection: Elements + ) -> Elements.Index? + where + Element: Foo, + Element: Bar, + Elements.Element == Element + { + let a = 123 + let b = "abc" + } + + """ var config = Configuration.forTesting config.lineBreakBeforeEachGenericRequirement = true @@ -626,7 +625,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testEmptyFunction() { let input = "func foo() {}" assertPrettyPrintEqual(input: input, expected: input + "\n", linelength: 50) - + let wrapped = """ func foo() { } @@ -703,7 +702,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 23) expected = - """ + """ func name(_ x: Int) throws -> R @@ -721,7 +720,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testBreaksBeforeOrInsideOutput_prioritizingKeepingOutputTogether() { let input = - """ + """ func name(_ x: Int) throws -> R func name(_ x: Int) throws -> R { @@ -731,7 +730,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { """ var expected = - """ + """ func name( _ x: Int ) throws -> R @@ -749,19 +748,19 @@ final class FunctionDeclTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 23, configuration: config) expected = - """ - func name( - _ x: Int - ) throws -> R - - func name( - _ x: Int - ) throws -> R { - statement - statement - } + """ + func name( + _ x: Int + ) throws -> R + + func name( + _ x: Int + ) throws -> R { + statement + statement + } - """ + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 30, configuration: config) assertPrettyPrintEqual(input: input, expected: expected, linelength: 33, configuration: config) } @@ -801,7 +800,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testBreaksBeforeOrInsideOutputWithAttributes_prioritizingKeepingOutputTogether() { let input = - """ + """ @objc @discardableResult func name(_ x: Int) throws -> R @@ -813,7 +812,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ @objc @discardableResult func name( @@ -894,7 +893,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testBreaksBeforeOrInsideOutputWithWhereClause_prioritizingKeepingOutputTogether() { var input = - """ + """ func name(_ x: Int) throws -> R where Foo == Bar func name(_ x: Int) throws -> R where Foo == Bar { @@ -904,7 +903,7 @@ final class FunctionDeclTests: PrettyPrintTestCase { """ var expected = - """ + """ func name( _ x: Int ) throws -> R @@ -924,34 +923,34 @@ final class FunctionDeclTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 23, configuration: config) input = - """ - func name(_ x: Int) throws -> R where Fooooooo == Barrrrr - - func name(_ x: Int) throws -> R where Fooooooo == Barrrrr { - statement - statement - } - """ + """ + func name(_ x: Int) throws -> R where Fooooooo == Barrrrr - expected = - """ - func name( - _ x: Int - ) throws -> R - where - Fooooooo == Barrrrr - - func name( - _ x: Int - ) throws -> R - where - Fooooooo == Barrrrr - { + func name(_ x: Int) throws -> R where Fooooooo == Barrrrr { statement statement - } + } + """ - """ + expected = + """ + func name( + _ x: Int + ) throws -> R + where + Fooooooo == Barrrrr + + func name( + _ x: Int + ) throws -> R + where + Fooooooo == Barrrrr + { + statement + statement + } + + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 23, configuration: config) } @@ -1016,24 +1015,24 @@ final class FunctionDeclTests: PrettyPrintTestCase { func testDoesNotCollapseFunctionParameterAttributes() { let input = - """ - func foo(@ViewBuilder bar: () -> View) { - bar() - } + """ + func foo(@ViewBuilder bar: () -> View) { + bar() + } - """ + """ assertPrettyPrintEqual(input: input, expected: input, linelength: 60) } func testDoesNotCollapseStackedFunctionParameterAttributes() { let input = - """ - func foo(@FakeAttr @ViewBuilder bar: () -> View) { - bar() - } + """ + func foo(@FakeAttr @ViewBuilder bar: () -> View) { + bar() + } - """ + """ assertPrettyPrintEqual(input: input, expected: input, linelength: 80) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/IfConfigTests.swift b/Tests/SwiftFormatTests/PrettyPrint/IfConfigTests.swift index 4f4a85b3b..1b725a94b 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/IfConfigTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/IfConfigTests.swift @@ -551,7 +551,7 @@ final class IfConfigTests: PrettyPrintTestCase { default: return nil } - + """ var configuration = Configuration.forTesting configuration.indentConditionalCompilationBlocks = false diff --git a/Tests/SwiftFormatTests/PrettyPrint/IgnoreNodeTests.swift b/Tests/SwiftFormatTests/PrettyPrint/IgnoreNodeTests.swift index 3153ccd80..46fa3f467 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/IgnoreNodeTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/IgnoreNodeTests.swift @@ -227,7 +227,7 @@ final class IgnoreNodeTests: PrettyPrintTestCase { """ - assertPrettyPrintEqual(input: input, expected: expected, linelength: 50) + assertPrettyPrintEqual(input: input, expected: expected, linelength: 50) } func testValidComment() { diff --git a/Tests/SwiftFormatTests/PrettyPrint/InitializerDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/InitializerDeclTests.swift index d1227605a..6c15ff53f 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/InitializerDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/InitializerDeclTests.swift @@ -92,7 +92,7 @@ final class InitializerDeclTests: PrettyPrintTestCase { func testInitializerOptionality() { let input = - """ + """ struct Struct { init? (var1: Int, var2: Double) { print("Hello World") @@ -106,9 +106,9 @@ final class InitializerDeclTests: PrettyPrintTestCase { init!() { let a = "AAAA BBBB CCCC DDDD EEEE FFFF" } } """ - + let expected = - """ + """ struct Struct { init?(var1: Int, var2: Double) { print("Hello World") @@ -128,7 +128,7 @@ final class InitializerDeclTests: PrettyPrintTestCase { } """ - + var config = Configuration.forTesting config.lineBreakBeforeEachArgument = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 50, configuration: config) @@ -170,80 +170,80 @@ final class InitializerDeclTests: PrettyPrintTestCase { func testInitializerGenericParameters() { let input = - """ - struct Struct { - init(var1: S, var2: T) { - let a = 123 - print("Hello World") - } - init(var1: ReallyLongTypeName, var2: TypeName) { - let a = 123 - let b = 456 + """ + struct Struct { + init(var1: S, var2: T) { + let a = 123 + print("Hello World") + } + init(var1: ReallyLongTypeName, var2: TypeName) { + let a = 123 + let b = 456 + } } - } - """ + """ let expected = - """ - struct Struct { - init(var1: S, var2: T) { - let a = 123 - print("Hello World") - } - init< - ReallyLongTypeName: Conform, - TypeName - >( - var1: ReallyLongTypeName, - var2: TypeName - ) { - let a = 123 - let b = 456 + """ + struct Struct { + init(var1: S, var2: T) { + let a = 123 + print("Hello World") + } + init< + ReallyLongTypeName: Conform, + TypeName + >( + var1: ReallyLongTypeName, + var2: TypeName + ) { + let a = 123 + let b = 456 + } } - } - """ + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } func testInitializerWhereClause() { let input = - """ - struct Struct { - public init(element: Element, in collection: Elements) where Elements.Element == Element { - let a = 123 - let b = "abc" - } - public init(element: Element, in collection: Elements) where Elements.Element == Element, Element: P, Element: Equatable { - let a = 123 - let b = "abc" + """ + struct Struct { + public init(element: Element, in collection: Elements) where Elements.Element == Element { + let a = 123 + let b = "abc" + } + public init(element: Element, in collection: Elements) where Elements.Element == Element, Element: P, Element: Equatable { + let a = 123 + let b = "abc" + } } - } - """ + """ let expected = - """ - struct Struct { - public init( - element: Element, in collection: Elements - ) where Elements.Element == Element { - let a = 123 - let b = "abc" - } - public init( - element: Element, in collection: Elements - ) - where - Elements.Element == Element, Element: P, - Element: Equatable - { - let a = 123 - let b = "abc" + """ + struct Struct { + public init( + element: Element, in collection: Elements + ) where Elements.Element == Element { + let a = 123 + let b = "abc" + } + public init( + element: Element, in collection: Elements + ) + where + Elements.Element == Element, Element: P, + Element: Equatable + { + let a = 123 + let b = "abc" + } } - } - """ + """ var config = Configuration.forTesting config.lineBreakBeforeEachArgument = false @@ -252,42 +252,42 @@ final class InitializerDeclTests: PrettyPrintTestCase { func testInitializerWhereClause_lineBreakBeforeEachGenericRequirement() { let input = - """ - struct Struct { - public init(element: Element, in collection: Elements) where Elements.Element == Element { - let a = 123 - let b = "abc" - } - public init(element: Element, in collection: Elements) where Elements.Element == Element, Element: P, Element: Equatable { - let a = 123 - let b = "abc" + """ + struct Struct { + public init(element: Element, in collection: Elements) where Elements.Element == Element { + let a = 123 + let b = "abc" + } + public init(element: Element, in collection: Elements) where Elements.Element == Element, Element: P, Element: Equatable { + let a = 123 + let b = "abc" + } } - } - """ + """ let expected = - """ - struct Struct { - public init( - element: Element, in collection: Elements - ) where Elements.Element == Element { - let a = 123 - let b = "abc" - } - public init( - element: Element, in collection: Elements - ) - where - Elements.Element == Element, - Element: P, - Element: Equatable - { - let a = 123 - let b = "abc" + """ + struct Struct { + public init( + element: Element, in collection: Elements + ) where Elements.Element == Element { + let a = 123 + let b = "abc" + } + public init( + element: Element, in collection: Elements + ) + where + Elements.Element == Element, + Element: P, + Element: Equatable + { + let a = 123 + let b = "abc" + } } - } - """ + """ var config = Configuration.forTesting config.lineBreakBeforeEachArgument = false @@ -376,7 +376,7 @@ final class InitializerDeclTests: PrettyPrintTestCase { func testInitializerFullWrap_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ struct Struct { @objc @inlinable public init(element: Element, in collection: Elements) where Elements.Element == Element, Element: Equatable, Element: P { let a = 123 @@ -386,7 +386,7 @@ final class InitializerDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ struct Struct { @objc @inlinable public init< @@ -422,7 +422,7 @@ final class InitializerDeclTests: PrettyPrintTestCase { } """ assertPrettyPrintEqual(input: input, expected: input + "\n", linelength: 50) - + let wrapped = """ struct X { // diff --git a/Tests/SwiftFormatTests/PrettyPrint/MacroCallTests.swift b/Tests/SwiftFormatTests/PrettyPrint/MacroCallTests.swift index 0616c66e3..0da0718ce 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/MacroCallTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/MacroCallTests.swift @@ -122,7 +122,7 @@ final class MacroCallTests: PrettyPrintTestCase { #Preview("Name") { EmptyView() } - + """ assertPrettyPrintEqual(input: input, expected: input, linelength: 45) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/MemberAccessExprTests.swift b/Tests/SwiftFormatTests/PrettyPrint/MemberAccessExprTests.swift index 6b0ed8cf5..8ab588c04 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/MemberAccessExprTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/MemberAccessExprTests.swift @@ -121,8 +121,11 @@ final class MemberAccessExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakAroundMultilineExpressionChainComponents = true assertPrettyPrintEqual( - input: input, expected: expectedWithForcedBreaks, linelength: 20, - configuration: configuration) + input: input, + expected: expectedWithForcedBreaks, + linelength: 20, + configuration: configuration + ) } func testContinuationRestorationAfterGroup() { @@ -238,8 +241,11 @@ final class MemberAccessExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakAroundMultilineExpressionChainComponents = true assertPrettyPrintEqual( - input: input, expected: expectedWithForcedBreaking, linelength: 35, - configuration: configuration) + input: input, + expected: expectedWithForcedBreaking, + linelength: 35, + configuration: configuration + ) } func testMemberItemClosureChaining() { @@ -332,30 +338,33 @@ final class MemberAccessExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakAroundMultilineExpressionChainComponents = true assertPrettyPrintEqual( - input: input, expected: expectedWithForcedBreaks, linelength: 50, - configuration: configuration) + input: input, + expected: expectedWithForcedBreaks, + linelength: 50, + configuration: configuration + ) } func testChainedTrailingClosureMethods() { let input = """ - var button = View.Button { Text("ABC") }.action { presentAction() }.background(.red).text(.blue).text(.red).font(.appleSans) - var button = View.Button { - // comment #0 - Text("ABC") - }.action { presentAction() }.background(.red).text(.blue).text(.red).font(.appleSans) - var button = View.Button { Text("ABC") } - .action { presentAction() }.background(.red).text(.blue) .text(.red).font(.appleSans) - var button = View.Button { Text("ABC") } - .action { - // comment #1 - presentAction() // comment #2 - }.background(.red).text(.blue) .text(.red).font(.appleSans) /* trailing comment */ - var button = View.Button { Text("ABC") }.action { presentAction() }.background(.red).text(.blue).text(.red).font(.appleSans).foo { - abc in - return abc.foo.bar - } - """ + var button = View.Button { Text("ABC") }.action { presentAction() }.background(.red).text(.blue).text(.red).font(.appleSans) + var button = View.Button { + // comment #0 + Text("ABC") + }.action { presentAction() }.background(.red).text(.blue).text(.red).font(.appleSans) + var button = View.Button { Text("ABC") } + .action { presentAction() }.background(.red).text(.blue) .text(.red).font(.appleSans) + var button = View.Button { Text("ABC") } + .action { + // comment #1 + presentAction() // comment #2 + }.background(.red).text(.blue) .text(.red).font(.appleSans) /* trailing comment */ + var button = View.Button { Text("ABC") }.action { presentAction() }.background(.red).text(.blue).text(.red).font(.appleSans).foo { + abc in + return abc.foo.bar + } + """ let expectedNoForcedBreaks = """ @@ -425,8 +434,11 @@ final class MemberAccessExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakAroundMultilineExpressionChainComponents = true assertPrettyPrintEqual( - input: input, expected: expectedWithForcedBreaks, linelength: 50, - configuration: configuration) + input: input, + expected: expectedWithForcedBreaks, + linelength: 50, + configuration: configuration + ) } func testChainedSubscriptExprs() { @@ -514,7 +526,10 @@ final class MemberAccessExprTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.lineBreakAroundMultilineExpressionChainComponents = true assertPrettyPrintEqual( - input: input, expected: expectedWithForcedBreaks, linelength: 50, - configuration: configuration) + input: input, + expected: expectedWithForcedBreaks, + linelength: 50, + configuration: configuration + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/ParameterPackTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ParameterPackTests.swift index c4615dfab..0e666e041 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ParameterPackTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ParameterPackTests.swift @@ -14,7 +14,8 @@ final class ParameterPackTests: PrettyPrintTestCase { > {} """, - linelength: 22) + linelength: 22 + ) } func testPackExpansionsAndElements() { @@ -27,7 +28,8 @@ final class ParameterPackTests: PrettyPrintTestCase { of: each value) """, - linelength: 25) + linelength: 25 + ) assertPrettyPrintEqual( input: """ @@ -41,6 +43,7 @@ final class ParameterPackTests: PrettyPrintTestCase { ) """, - linelength: 7) + linelength: 7 + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/PrettyPrintTestCase.swift b/Tests/SwiftFormatTests/PrettyPrint/PrettyPrintTestCase.swift index eaa33ac3a..abe0400b7 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/PrettyPrintTestCase.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/PrettyPrintTestCase.swift @@ -1,10 +1,9 @@ import SwiftFormat +@_spi(Rules) @_spi(Testing) import SwiftFormat import SwiftOperators -import SwiftSyntax import SwiftParser +import SwiftSyntax import XCTest - -@_spi(Rules) @_spi(Testing) import SwiftFormat @_spi(Testing) import _SwiftFormatTestSupport class PrettyPrintTestCase: DiagnosingTestCase { @@ -45,11 +44,15 @@ class PrettyPrintTestCase: DiagnosingTestCase { configuration: configuration, selection: markedInput.selection, whitespaceOnly: whitespaceOnly, - findingConsumer: { emittedFindings.append($0) }) + findingConsumer: { emittedFindings.append($0) } + ) assertStringsEqualWithDiff( - formatted, expected, + formatted, + expected, "Pretty-printed result was not what was expected", - file: file, line: line) + file: file, + line: line + ) // FIXME: It would be nice to check findings when whitespaceOnly == false, but their locations // are wrong. @@ -60,7 +63,8 @@ class PrettyPrintTestCase: DiagnosingTestCase { emittedFindings: emittedFindings, context: context, file: file, - line: line) + line: line + ) } // Idempotency check: Running the formatter multiple times should not change the outcome. @@ -75,7 +79,12 @@ class PrettyPrintTestCase: DiagnosingTestCase { findingConsumer: { _ in } // Ignore findings during the idempotence check. ) assertStringsEqualWithDiff( - reformatted, formatted, "Pretty printer is not idempotent", file: file, line: line) + reformatted, + formatted, + "Pretty printer is not idempotent", + file: file, + line: line + ) } } @@ -98,18 +107,20 @@ class PrettyPrintTestCase: DiagnosingTestCase { // Ignore folding errors for unrecognized operators so that we fallback to a reasonable default. let sourceFileSyntax = OperatorTable.standardOperators.foldAll(Parser.parse(source: source)) { _ in } - .as(SourceFileSyntax.self)! + .as(SourceFileSyntax.self)! let context = makeContext( sourceFileSyntax: sourceFileSyntax, configuration: configuration, selection: selection, - findingConsumer: findingConsumer) + findingConsumer: findingConsumer + ) let printer = PrettyPrinter( context: context, source: source, node: Syntax(sourceFileSyntax), printTokenStream: false, - whitespaceOnly: whitespaceOnly) + whitespaceOnly: whitespaceOnly + ) return (printer.prettyPrint(), context) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/ProtocolDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/ProtocolDeclTests.swift index d10db6c93..2bad29363 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/ProtocolDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/ProtocolDeclTests.swift @@ -89,7 +89,6 @@ final class ProtocolDeclTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 50) } - func testProtocolAttributes() { let input = """ @@ -152,7 +151,7 @@ final class ProtocolDeclTests: PrettyPrintTestCase { func doStuff(firstArg: Foo, second second: Bar, third third: Baz) -> Output } """ - + let expected = """ protocol MyProtocol { @@ -177,7 +176,7 @@ final class ProtocolDeclTests: PrettyPrintTestCase { } """ - + assertPrettyPrintEqual(input: input, expected: expected, linelength: 30) } @@ -189,7 +188,7 @@ final class ProtocolDeclTests: PrettyPrintTestCase { init(reallyLongLabel: Int, anotherLongLabel: Bool) } """ - + let expected = """ protocol MyProtocol { @@ -200,7 +199,7 @@ final class ProtocolDeclTests: PrettyPrintTestCase { } """ - + assertPrettyPrintEqual(input: input, expected: expected, linelength: 30) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/RespectsExistingLineBreaksTests.swift b/Tests/SwiftFormatTests/PrettyPrint/RespectsExistingLineBreaksTests.swift index 65226cf5e..fadbc59fe 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/RespectsExistingLineBreaksTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/RespectsExistingLineBreaksTests.swift @@ -24,8 +24,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { """ assertPrettyPrintEqual( - input: input, expected: expectedRespecting, linelength: 12, - configuration: configuration(respectingExistingLineBreaks: true)) + input: input, + expected: expectedRespecting, + linelength: 12, + configuration: configuration(respectingExistingLineBreaks: true) + ) let expectedNotRespecting = """ @@ -36,8 +39,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { """ assertPrettyPrintEqual( - input: input, expected: expectedNotRespecting, linelength: 25, - configuration: configuration(respectingExistingLineBreaks: false)) + input: input, + expected: expectedNotRespecting, + linelength: 25, + configuration: configuration(respectingExistingLineBreaks: false) + ) } func testCodeBlocksAndMemberDecls() { @@ -82,8 +88,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { // No changes expected when respecting existing newlines. assertPrettyPrintEqual( - input: input, expected: input + "\n", linelength: 80, - configuration: configuration(respectingExistingLineBreaks: true)) + input: input, + expected: input + "\n", + linelength: 80, + configuration: configuration(respectingExistingLineBreaks: true) + ) let expectedNotRespecting = """ @@ -110,8 +119,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { """ assertPrettyPrintEqual( - input: input, expected: expectedNotRespecting, linelength: 80, - configuration: configuration(respectingExistingLineBreaks: false)) + input: input, + expected: expectedNotRespecting, + linelength: 80, + configuration: configuration(respectingExistingLineBreaks: false) + ) } func testSemicolons() { @@ -130,8 +142,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { // the same line if they were originally like that and likewise preserve newlines after // semicolons if present. assertPrettyPrintEqual( - input: input, expected: input + "\n", linelength: 80, - configuration: configuration(respectingExistingLineBreaks: true)) + input: input, + expected: input + "\n", + linelength: 80, + configuration: configuration(respectingExistingLineBreaks: true) + ) let expectedNotRespecting = """ @@ -150,8 +165,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { // When not respecting newlines every semicolon-delimited statement or declaration should end up // on its own line. assertPrettyPrintEqual( - input: input, expected: expectedNotRespecting, linelength: 80, - configuration: configuration(respectingExistingLineBreaks: false)) + input: input, + expected: expectedNotRespecting, + linelength: 80, + configuration: configuration(respectingExistingLineBreaks: false) + ) } func testInvalidBreaksAreAlwaysRejected() { @@ -176,8 +194,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { """ assertPrettyPrintEqual( - input: input, expected: expectedRespecting, linelength: 80, - configuration: configuration(respectingExistingLineBreaks: true)) + input: input, + expected: expectedRespecting, + linelength: 80, + configuration: configuration(respectingExistingLineBreaks: true) + ) let expectedNotRespecting = """ @@ -186,8 +207,11 @@ final class RespectsExistingLineBreaksTests: PrettyPrintTestCase { """ assertPrettyPrintEqual( - input: input, expected: expectedNotRespecting, linelength: 80, - configuration: configuration(respectingExistingLineBreaks: false)) + input: input, + expected: expectedNotRespecting, + linelength: 80, + configuration: configuration(respectingExistingLineBreaks: false) + ) } /// Creates a new configuration with the given value for `respectsExistingLineBreaks` and default diff --git a/Tests/SwiftFormatTests/PrettyPrint/SemicolonTests.swift b/Tests/SwiftFormatTests/PrettyPrint/SemicolonTests.swift index 80b746152..68f0420f8 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/SemicolonTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/SemicolonTests.swift @@ -12,20 +12,20 @@ final class SemiColonTypeTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: input + "\n", linelength: 50) } - + func testNoSemicolon() { let input = """ - var foo = false - guard !foo else { return } - defer { foo = true } + var foo = false + guard !foo else { return } + defer { foo = true } - struct Foo { - var foo = false - var bar = true - var baz = false - } - """ + struct Foo { + var foo = false + var bar = true + var baz = false + } + """ assertPrettyPrintEqual(input: input, expected: input + "\n", linelength: 50) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/StringTests.swift b/Tests/SwiftFormatTests/PrettyPrint/StringTests.swift index 3c9f937e7..d97d3e0a0 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/StringTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/StringTests.swift @@ -50,7 +50,8 @@ final class StringTests: PrettyPrintTestCase { input: input, expected: expected, linelength: 30, - configuration: config) + configuration: config + ) } func testMultilineStringIsNotReformattedWithIgnore() { @@ -109,32 +110,32 @@ final class StringTests: PrettyPrintTestCase { func testMultilineStringWithInterpolations() { let input = - #""" - if true { - guard let opt else { - functionCall(""" - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero \(2) \(testVariable) ids risus placerat imperdiet. Praesent fringilla vel nisi sed fermentum. In vitae purus feugiat, euismod nulla in, rhoncus leo. Suspendisse feugiat sapien lobortis facilisis malesuada. Aliquam feugiat suscipit accumsan. Praesent tempus fermentum est, vel blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt efficitur ante id fermentum. - """) - } + #""" + if true { + guard let opt else { + functionCall(""" + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero \(2) \(testVariable) ids risus placerat imperdiet. Praesent fringilla vel nisi sed fermentum. In vitae purus feugiat, euismod nulla in, rhoncus leo. Suspendisse feugiat sapien lobortis facilisis malesuada. Aliquam feugiat suscipit accumsan. Praesent tempus fermentum est, vel blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt efficitur ante id fermentum. + """) } - """# + } + """# let expected = - #""" - if true { - guard let opt else { - functionCall( - """ - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero \(2) \ - \(testVariable) ids risus placerat imperdiet. Praesent fringilla vel nisi sed fermentum. In \ - vitae purus feugiat, euismod nulla in, rhoncus leo. Suspendisse feugiat sapien lobortis \ - facilisis malesuada. Aliquam feugiat suscipit accumsan. Praesent tempus fermentum est, vel \ - blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt efficitur ante id fermentum. - """) - } + #""" + if true { + guard let opt else { + functionCall( + """ + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero \(2) \ + \(testVariable) ids risus placerat imperdiet. Praesent fringilla vel nisi sed fermentum. In \ + vitae purus feugiat, euismod nulla in, rhoncus leo. Suspendisse feugiat sapien lobortis \ + facilisis malesuada. Aliquam feugiat suscipit accumsan. Praesent tempus fermentum est, vel \ + blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt efficitur ante id fermentum. + """) } + } - """# + """# var config = Configuration() config.reflowMultilineStringLiterals = .onlyLinesOverLength @@ -143,25 +144,25 @@ final class StringTests: PrettyPrintTestCase { func testMutlilineStringsRespectsHardLineBreaks() { let input = - #""" - """ - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero ids risus placerat imperdiet. Praesent fringilla vel nisi sed fermentum. In vitae purus feugiat, euismod nulla in, rhoncus leo. - Suspendisse feugiat sapien lobortis facilisis malesuada. Aliquam feugiat suscipit accumsan. Praesent tempus fermentum est, vel blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt efficitur ante id fermentum. - """ - """# + #""" + """ + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero ids risus placerat imperdiet. Praesent fringilla vel nisi sed fermentum. In vitae purus feugiat, euismod nulla in, rhoncus leo. + Suspendisse feugiat sapien lobortis facilisis malesuada. Aliquam feugiat suscipit accumsan. Praesent tempus fermentum est, vel blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt efficitur ante id fermentum. + """ + """# let expected = - #""" - """ - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero ids risus placerat \ - imperdiet. Praesent fringilla vel nisi sed fermentum. In vitae purus feugiat, euismod nulla in, \ - rhoncus leo. - Suspendisse feugiat sapien lobortis facilisis malesuada. Aliquam feugiat suscipit accumsan. \ - Praesent tempus fermentum est, vel blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt \ - efficitur ante id fermentum. - """ + #""" + """ + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum libero ids risus placerat \ + imperdiet. Praesent fringilla vel nisi sed fermentum. In vitae purus feugiat, euismod nulla in, \ + rhoncus leo. + Suspendisse feugiat sapien lobortis facilisis malesuada. Aliquam feugiat suscipit accumsan. \ + Praesent tempus fermentum est, vel blandit mi pretium a. Proin in posuere sapien. Nunc tincidunt \ + efficitur ante id fermentum. + """ - """# + """# var config = Configuration() config.reflowMultilineStringLiterals = .onlyLinesOverLength @@ -273,19 +274,19 @@ final class StringTests: PrettyPrintTestCase { func testMultilineStringWithWordLongerThanLineLength() { let input = - #""" - """ - there isn't an opportunity to break up this long url: https://www.cool-math-games.org/games/id?=01913310-b7c3-77d8-898e-300ccd451ea8 - """ - """# + #""" + """ + there isn't an opportunity to break up this long url: https://www.cool-math-games.org/games/id?=01913310-b7c3-77d8-898e-300ccd451ea8 + """ + """# let expected = - #""" - """ - there isn't an opportunity to break up this long url: \ - https://www.cool-math-games.org/games/id?=01913310-b7c3-77d8-898e-300ccd451ea8 - """ + #""" + """ + there isn't an opportunity to break up this long url: \ + https://www.cool-math-games.org/games/id?=01913310-b7c3-77d8-898e-300ccd451ea8 + """ - """# + """# var config = Configuration() config.reflowMultilineStringLiterals = .onlyLinesOverLength diff --git a/Tests/SwiftFormatTests/PrettyPrint/StructDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/StructDeclTests.swift index 664fc59d6..b05e203df 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/StructDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/StructDeclTests.swift @@ -208,7 +208,7 @@ final class StructDeclTests: PrettyPrintTestCase { func testStructWhereClause_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ struct MyStruct where S: Collection { let A: Int let B: Double @@ -224,7 +224,7 @@ final class StructDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ struct MyStruct where S: Collection { let A: Int let B: Double @@ -295,7 +295,7 @@ final class StructDeclTests: PrettyPrintTestCase { func testStructWhereClauseWithInheritance_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ struct MyStruct: ProtoOne where S: Collection { let A: Int let B: Double @@ -311,7 +311,7 @@ final class StructDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ struct MyStruct: ProtoOne where S: Collection { let A: Int let B: Double diff --git a/Tests/SwiftFormatTests/PrettyPrint/SubscriptDeclTests.swift b/Tests/SwiftFormatTests/PrettyPrint/SubscriptDeclTests.swift index 9a06c0bab..f7dae1118 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/SubscriptDeclTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/SubscriptDeclTests.swift @@ -166,7 +166,7 @@ final class SubscriptDeclTests: PrettyPrintTestCase { func testSubscriptGenericWhere_lineBreakBeforeEachGenericRequirement() { let input = - """ + """ struct MyStruct { subscript(var1: Element, var2: Elements) -> Double where Elements.Element == Element { return 1.23 @@ -178,7 +178,7 @@ final class SubscriptDeclTests: PrettyPrintTestCase { """ let expected = - """ + """ struct MyStruct { subscript( var1: Element, var2: Elements @@ -262,7 +262,7 @@ final class SubscriptDeclTests: PrettyPrintTestCase { func testBreaksBeforeOrInsideOutput() { let input = - """ + """ protocol MyProtocol { subscript(index: Int) -> R } @@ -276,7 +276,7 @@ final class SubscriptDeclTests: PrettyPrintTestCase { """ var expected = - """ + """ protocol MyProtocol { subscript(index: Int) -> R @@ -295,29 +295,29 @@ final class SubscriptDeclTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 26) expected = - """ - protocol MyProtocol { - subscript(index: Int) - -> R - } - - struct MyStruct { - subscript(index: Int) - -> R - { - statement - statement - } - } - - """ + """ + protocol MyProtocol { + subscript(index: Int) + -> R + } + + struct MyStruct { + subscript(index: Int) + -> R + { + statement + statement + } + } + + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 27) assertPrettyPrintEqual(input: input, expected: expected, linelength: 30) } func testBreaksBeforeOrInsideOutput_prioritizingKeepingOutputTogether() { let input = - """ + """ protocol MyProtocol { subscript(index: Int) -> R } @@ -331,7 +331,7 @@ final class SubscriptDeclTests: PrettyPrintTestCase { """ var expected = - """ + """ protocol MyProtocol { subscript( index: Int @@ -353,124 +353,124 @@ final class SubscriptDeclTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 26, configuration: config) expected = - """ - protocol MyProtocol { - subscript( - index: Int - ) -> R - } - - struct MyStruct { - subscript( - index: Int - ) -> R { - statement - statement - } - } - - """ + """ + protocol MyProtocol { + subscript( + index: Int + ) -> R + } + + struct MyStruct { + subscript( + index: Int + ) -> R { + statement + statement + } + } + + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 27, configuration: config) assertPrettyPrintEqual(input: input, expected: expected, linelength: 30, configuration: config) } func testSubscriptFullWrap() { let input = - """ - struct MyStruct { - @discardableResult @objc - subscript(var1: Element, var2: ManyElements) -> ManyElements.Index? where Element: Foo, Element: Bar, ManyElements.Element == Element { - get { - let out = vals[var1][var2] - return out - } - set(newValue) { - let tmp = compute(newValue) - vals[var1][var2] = tmp + """ + struct MyStruct { + @discardableResult @objc + subscript(var1: Element, var2: ManyElements) -> ManyElements.Index? where Element: Foo, Element: Bar, ManyElements.Element == Element { + get { + let out = vals[var1][var2] + return out + } + set(newValue) { + let tmp = compute(newValue) + vals[var1][var2] = tmp + } } } - } - """ + """ let expected = - """ - struct MyStruct { - @discardableResult @objc - subscript< - ManyElements: Collection, - Element - >( - var1: Element, - var2: ManyElements - ) -> ManyElements.Index? - where - Element: Foo, Element: Bar, - ManyElements.Element - == Element - { - get { - let out = vals[var1][var2] - return out - } - set(newValue) { - let tmp = compute(newValue) - vals[var1][var2] = tmp - } - } - } - - """ + """ + struct MyStruct { + @discardableResult @objc + subscript< + ManyElements: Collection, + Element + >( + var1: Element, + var2: ManyElements + ) -> ManyElements.Index? + where + Element: Foo, Element: Bar, + ManyElements.Element + == Element + { + get { + let out = vals[var1][var2] + return out + } + set(newValue) { + let tmp = compute(newValue) + vals[var1][var2] = tmp + } + } + } + + """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 34) } func testSubscriptFullWrap_lineBreakBeforeEachGenericRequirement() { let input = - """ - struct MyStruct { - @discardableResult @objc - subscript(var1: Element, var2: ManyElements) -> ManyElements.Index? where Element: Foo, Element: Bar, ManyElements.Element == Element { - get { - let out = vals[var1][var2] - return out - } - set(newValue) { - let tmp = compute(newValue) - vals[var1][var2] = tmp + """ + struct MyStruct { + @discardableResult @objc + subscript(var1: Element, var2: ManyElements) -> ManyElements.Index? where Element: Foo, Element: Bar, ManyElements.Element == Element { + get { + let out = vals[var1][var2] + return out + } + set(newValue) { + let tmp = compute(newValue) + vals[var1][var2] = tmp + } } } - } - """ + """ let expected = - """ - struct MyStruct { - @discardableResult @objc - subscript< - ManyElements: Collection, - Element - >( - var1: Element, - var2: ManyElements - ) -> ManyElements.Index? - where - Element: Foo, - Element: Bar, - ManyElements.Element - == Element - { - get { - let out = vals[var1][var2] - return out - } - set(newValue) { - let tmp = compute(newValue) - vals[var1][var2] = tmp - } - } - } - - """ + """ + struct MyStruct { + @discardableResult @objc + subscript< + ManyElements: Collection, + Element + >( + var1: Element, + var2: ManyElements + ) -> ManyElements.Index? + where + Element: Foo, + Element: Bar, + ManyElements.Element + == Element + { + get { + let out = vals[var1][var2] + return out + } + set(newValue) { + let tmp = compute(newValue) + vals[var1][var2] = tmp + } + } + } + + """ var config = Configuration.forTesting config.lineBreakBeforeEachGenericRequirement = true @@ -486,7 +486,7 @@ final class SubscriptDeclTests: PrettyPrintTestCase { } """ assertPrettyPrintEqual(input: input, expected: input + "\n", linelength: 50) - + let wrapped = """ struct X { // diff --git a/Tests/SwiftFormatTests/PrettyPrint/SubscriptExprTests.swift b/Tests/SwiftFormatTests/PrettyPrint/SubscriptExprTests.swift index b832120df..fe9bc36cf 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/SubscriptExprTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/SubscriptExprTests.swift @@ -65,14 +65,14 @@ final class SubscriptExprTests: PrettyPrintTestCase { func testSubscriptSettersWithTrailingClosures() { let input = - """ + """ myCollection[index] { $0 < $1 } = someValue myCollection[label: index] { arg1, arg2 in foo() } = someValue myCollection[index, default: someDefaultValue] { arg1, arg2 in foo() } = someValue """ let expected = - """ + """ myCollection[index] { $0 < $1 } = someValue myCollection[label: index] { arg1, arg2 in foo() diff --git a/Tests/SwiftFormatTests/PrettyPrint/SwitchStmtTests.swift b/Tests/SwiftFormatTests/PrettyPrint/SwitchStmtTests.swift index 6928defd5..4c02f4a3f 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/SwitchStmtTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/SwitchStmtTests.swift @@ -277,7 +277,6 @@ final class SwitchStmtTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 35) } - func testSwitchExpression2() { let input = """ @@ -555,6 +554,10 @@ final class SwitchStmtTests: PrettyPrintTestCase { var configuration = Configuration.forTesting configuration.indentSwitchCaseLabels = true assertPrettyPrintEqual( - input: input, expected: expected, linelength: 40, configuration: configuration) + input: input, + expected: expected, + linelength: 40, + configuration: configuration + ) } } diff --git a/Tests/SwiftFormatTests/PrettyPrint/WhitespaceLintTests.swift b/Tests/SwiftFormatTests/PrettyPrint/WhitespaceLintTests.swift index 0000be6ac..7fa561816 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/WhitespaceLintTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/WhitespaceLintTests.swift @@ -35,7 +35,7 @@ final class WhitespaceLintTests: WhitespaceTestCase { """, findings: [ - FindingSpec("1️⃣", message: "use spaces for spacing"), + FindingSpec("1️⃣", message: "use spaces for spacing") ] ) } diff --git a/Tests/SwiftFormatTests/PrettyPrint/WhitespaceTestCase.swift b/Tests/SwiftFormatTests/PrettyPrint/WhitespaceTestCase.swift index 78c49752e..4a707e779 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/WhitespaceTestCase.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/WhitespaceTestCase.swift @@ -1,9 +1,8 @@ import SwiftFormat -import SwiftSyntax +@_spi(Testing) import SwiftFormat import SwiftParser +import SwiftSyntax import XCTest - -@_spi(Testing) import SwiftFormat @_spi(Testing) import _SwiftFormatTestSupport class WhitespaceTestCase: DiagnosingTestCase { @@ -40,9 +39,13 @@ class WhitespaceTestCase: DiagnosingTestCase { sourceFileSyntax: sourceFileSyntax, configuration: configuration, selection: .infinite, - findingConsumer: { emittedFindings.append($0) }) + findingConsumer: { emittedFindings.append($0) } + ) let linter = WhitespaceLinter( - user: markedText.textWithoutMarkers, formatted: expected, context: context) + user: markedText.textWithoutMarkers, + formatted: expected, + context: context + ) linter.lint() assertFindings( @@ -51,6 +54,7 @@ class WhitespaceTestCase: DiagnosingTestCase { emittedFindings: emittedFindings, context: context, file: file, - line: line) + line: line + ) } } diff --git a/Tests/SwiftFormatTests/Rules/AllPublicDeclarationsHaveDocumentationTests.swift b/Tests/SwiftFormatTests/Rules/AllPublicDeclarationsHaveDocumentationTests.swift index 81965c38c..b3fabac22 100644 --- a/Tests/SwiftFormatTests/Rules/AllPublicDeclarationsHaveDocumentationTests.swift +++ b/Tests/SwiftFormatTests/Rules/AllPublicDeclarationsHaveDocumentationTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCase { func testPublicDeclsWithoutDocs() { @@ -21,22 +20,22 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas /// Comment. public struct Foo {} struct Foo {} - + 4️⃣public actor Bar {} /// Comment. public actor Bar {} actor Bar {} - + 5️⃣public class Baz {} /// Comment. public class Baz {} class Baz {} - + 6️⃣public enum Qux {} /// Comment. public enum Qux {} enum Qux {} - + 7️⃣public typealias MyType = Int /// Comment. public typealias MyType = Int @@ -56,7 +55,7 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas FindingSpec("4️⃣", message: "add a documentation comment for 'Bar'"), FindingSpec("5️⃣", message: "add a documentation comment for 'Baz'"), FindingSpec("6️⃣", message: "add a documentation comment for 'Qux'"), - FindingSpec("7️⃣", message: "add a documentation comment for 'MyType'") + FindingSpec("7️⃣", message: "add a documentation comment for 'MyType'"), ] ) } @@ -111,7 +110,7 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas FindingSpec("4️⃣", message: "add a documentation comment for 'Bar'"), FindingSpec("5️⃣", message: "add a documentation comment for 'Baz'"), FindingSpec("6️⃣", message: "add a documentation comment for 'Qux'"), - FindingSpec("7️⃣", message: "add a documentation comment for 'MyType'") + FindingSpec("7️⃣", message: "add a documentation comment for 'MyType'"), ] ) } @@ -129,7 +128,7 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas } """, findings: [ - FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'"), + FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'") ] ) } @@ -147,7 +146,7 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas } """, findings: [ - FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'"), + FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'") ] ) } @@ -165,7 +164,7 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas } """, findings: [ - FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'"), + FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'") ] ) } @@ -183,7 +182,7 @@ final class AllPublicDeclarationsHaveDocumentationTests: LintOrFormatRuleTestCas } """, findings: [ - FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'"), + FindingSpec("1️⃣", message: "add a documentation comment for 'MyType'") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/AlwaysUseLiteralForEmptyCollectionInitTests.swift b/Tests/SwiftFormatTests/Rules/AlwaysUseLiteralForEmptyCollectionInitTests.swift index c6b6267ce..acb3535da 100644 --- a/Tests/SwiftFormatTests/Rules/AlwaysUseLiteralForEmptyCollectionInitTests.swift +++ b/Tests/SwiftFormatTests/Rules/AlwaysUseLiteralForEmptyCollectionInitTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class AlwaysUseLiteralForEmptyCollectionInitTests: LintOrFormatRuleTestCase { func testArray() { diff --git a/Tests/SwiftFormatTests/Rules/AlwaysUseLowerCamelCaseTests.swift b/Tests/SwiftFormatTests/Rules/AlwaysUseLowerCamelCaseTests.swift index 1dbca2191..5d8ffe3db 100644 --- a/Tests/SwiftFormatTests/Rules/AlwaysUseLowerCamelCaseTests.swift +++ b/Tests/SwiftFormatTests/Rules/AlwaysUseLowerCamelCaseTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class AlwaysUseLowerCamelCaseTests: LintOrFormatRuleTestCase { func testInvalidVariableCasing() { @@ -57,7 +56,7 @@ final class AlwaysUseLowerCamelCaseTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "rename the enum case 'UpperCamelCase' using lowerCamelCase"), + FindingSpec("1️⃣", message: "rename the enum case 'UpperCamelCase' using lowerCamelCase") ] ) @@ -229,7 +228,10 @@ final class AlwaysUseLowerCamelCaseTests: LintOrFormatRuleTestCase { findings: [ FindingSpec("1️⃣", message: "rename the function 'function_Without_Test_Attribute' using lowerCamelCase"), FindingSpec("2️⃣", message: "rename the function 'function_With_Non_Test_Attribute' using lowerCamelCase"), - FindingSpec("3️⃣", message: "rename the function 'function_With_Test_Attribute_From_Foo_Module' using lowerCamelCase"), + FindingSpec( + "3️⃣", + message: "rename the function 'function_With_Test_Attribute_From_Foo_Module' using lowerCamelCase" + ), ] ) } diff --git a/Tests/SwiftFormatTests/Rules/AmbiguousTrailingClosureOverloadTests.swift b/Tests/SwiftFormatTests/Rules/AmbiguousTrailingClosureOverloadTests.swift index b50bb8411..185fe92f4 100644 --- a/Tests/SwiftFormatTests/Rules/AmbiguousTrailingClosureOverloadTests.swift +++ b/Tests/SwiftFormatTests/Rules/AmbiguousTrailingClosureOverloadTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class AmbiguousTrailingClosureOverloadTests: LintOrFormatRuleTestCase { func testAmbiguousOverloads() { @@ -29,29 +28,33 @@ final class AmbiguousTrailingClosureOverloadTests: LintOrFormatRuleTestCase { """, findings: [ FindingSpec( - "1️⃣", message: "rename 'strong(mad:)' so it is no longer ambiguous when called with a trailing closure", + "1️⃣", + message: "rename 'strong(mad:)' so it is no longer ambiguous when called with a trailing closure", notes: [ NoteSpec("2️⃣", message: "ambiguous overload 'strong(bad:)' is here"), NoteSpec("3️⃣", message: "ambiguous overload 'strong(sad:)' is here"), ] ), FindingSpec( - "4️⃣", message: "rename 'the(cheat:)' so it is no longer ambiguous when called with a trailing closure", + "4️⃣", + message: "rename 'the(cheat:)' so it is no longer ambiguous when called with a trailing closure", notes: [ - NoteSpec("5️⃣", message: "ambiguous overload 'the(sneak:)' is here"), + NoteSpec("5️⃣", message: "ambiguous overload 'the(sneak:)' is here") ] ), FindingSpec( - "6️⃣", message: "rename 'the(kingOfTown:)' so it is no longer ambiguous when called with a trailing closure", + "6️⃣", + message: "rename 'the(kingOfTown:)' so it is no longer ambiguous when called with a trailing closure", notes: [ NoteSpec("7️⃣", message: "ambiguous overload 'the(cheatCommandos:)' is here"), NoteSpec("8️⃣", message: "ambiguous overload 'the(brothersStrong:)' is here"), ] ), FindingSpec( - "9️⃣", message: "rename 'hom(estar:)' so it is no longer ambiguous when called with a trailing closure", + "9️⃣", + message: "rename 'hom(estar:)' so it is no longer ambiguous when called with a trailing closure", notes: [ - NoteSpec("🔟", message: "ambiguous overload 'hom(sar:)' is here"), + NoteSpec("🔟", message: "ambiguous overload 'hom(sar:)' is here") ] ), ] diff --git a/Tests/SwiftFormatTests/Rules/AvoidRetroactiveConformancesTests.swift b/Tests/SwiftFormatTests/Rules/AvoidRetroactiveConformancesTests.swift index 2616d2581..4e6d45239 100644 --- a/Tests/SwiftFormatTests/Rules/AvoidRetroactiveConformancesTests.swift +++ b/Tests/SwiftFormatTests/Rules/AvoidRetroactiveConformancesTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class AvoidRetroactiveConformancesTests: LintOrFormatRuleTestCase { func testRetroactiveConformanceIsDiagnosed() { @@ -10,7 +9,7 @@ final class AvoidRetroactiveConformancesTests: LintOrFormatRuleTestCase { extension Int: 1️⃣@retroactive Identifiable {} """, findings: [ - FindingSpec("1️⃣", message: "do not declare retroactive conformances"), + FindingSpec("1️⃣", message: "do not declare retroactive conformances") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/BeginDocumentationCommentWithOneLineSummaryTests.swift b/Tests/SwiftFormatTests/Rules/BeginDocumentationCommentWithOneLineSummaryTests.swift index 6c96f6d8a..a297a1b3a 100644 --- a/Tests/SwiftFormatTests/Rules/BeginDocumentationCommentWithOneLineSummaryTests.swift +++ b/Tests/SwiftFormatTests/Rules/BeginDocumentationCommentWithOneLineSummaryTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport // FIXME: We should place the diagnostic somewhere in the comment, not on the declaration. final class BeginDocumentationCommentWithOneLineSummaryTests: LintOrFormatRuleTestCase { @@ -45,7 +44,10 @@ final class BeginDocumentationCommentWithOneLineSummaryTests: LintOrFormatRuleTe findings: [ FindingSpec("1️⃣", message: #"add a blank comment line after this sentence: "This docline should not succeed.""#), FindingSpec("2️⃣", message: #"add a blank comment line after this sentence: "This docline should not succeed.""#), - FindingSpec("3️⃣", message: #"terminate this sentence with a period: "Should fail because it doesn't have a period""#), + FindingSpec( + "3️⃣", + message: #"terminate this sentence with a period: "Should fail because it doesn't have a period""# + ), ] ) } @@ -86,83 +88,98 @@ final class BeginDocumentationCommentWithOneLineSummaryTests: LintOrFormatRuleTe 4️⃣public class testNoPeriod {} """, findings: [ - FindingSpec("1️⃣", message: #"add a blank comment line after this sentence: "This block comment should not succeed, struct.""#), - FindingSpec("2️⃣", message: #"add a blank comment line after this sentence: "This block comment should not succeed, class.""#), - FindingSpec("3️⃣", message: #"add a blank comment line after this sentence: "This block comment should not succeed, enum.""#), - FindingSpec("4️⃣", message: #"terminate this sentence with a period: "Should fail because it doesn't have a period""#), + FindingSpec( + "1️⃣", + message: #"add a blank comment line after this sentence: "This block comment should not succeed, struct.""# + ), + FindingSpec( + "2️⃣", + message: #"add a blank comment line after this sentence: "This block comment should not succeed, class.""# + ), + FindingSpec( + "3️⃣", + message: #"add a blank comment line after this sentence: "This block comment should not succeed, enum.""# + ), + FindingSpec( + "4️⃣", + message: #"terminate this sentence with a period: "Should fail because it doesn't have a period""# + ), ] ) } func testApproximationsOnMacOS() { #if os(macOS) - // Let macOS also verify that the fallback mode works, which gives us signal about whether it - // will also succeed on Linux (where the linguistic APIs are not currently available). - BeginDocumentationCommentWithOneLineSummary._forcesFallbackModeForTesting = true - - assertLint( - BeginDocumentationCommentWithOneLineSummary.self, - """ - /// Returns a bottle of Dr Pepper from the vending machine. - public func drPepper(from vendingMachine: VendingMachine) -> Soda {} - - /// Contains a comment as description that needs a sentence - /// of two lines of code. - public var twoLinesForOneSentence = "test" - - /// The background color of the view. - var backgroundColor: UIColor + // Let macOS also verify that the fallback mode works, which gives us signal about whether it + // will also succeed on Linux (where the linguistic APIs are not currently available). + BeginDocumentationCommentWithOneLineSummary._forcesFallbackModeForTesting = true - /// Returns the sum of the numbers. - /// - /// - Parameter numbers: The numbers to sum. - /// - Returns: The sum of the numbers. - func sum(_ numbers: [Int]) -> Int { - // ... - } + assertLint( + BeginDocumentationCommentWithOneLineSummary.self, + """ + /// Returns a bottle of Dr Pepper from the vending machine. + public func drPepper(from vendingMachine: VendingMachine) -> Soda {} + + /// Contains a comment as description that needs a sentence + /// of two lines of code. + public var twoLinesForOneSentence = "test" + + /// The background color of the view. + var backgroundColor: UIColor + + /// Returns the sum of the numbers. + /// + /// - Parameter numbers: The numbers to sum. + /// - Returns: The sum of the numbers. + func sum(_ numbers: [Int]) -> Int { + // ... + } - /// This docline should not succeed. - /// There are two sentences without a blank line between them. - 1️⃣struct Test {} + /// This docline should not succeed. + /// There are two sentences without a blank line between them. + 1️⃣struct Test {} - /// This docline should not succeed. There are two sentences. - 2️⃣public enum Token { case comma, semicolon, identifier } + /// This docline should not succeed. There are two sentences. + 2️⃣public enum Token { case comma, semicolon, identifier } - /// Should fail because it doesn't have a period - 3️⃣public class testNoPeriod {} - """, - findings: [ - FindingSpec("1️⃣", message: #"add a blank comment line after this sentence: "This docline should not succeed.""#), - FindingSpec("2️⃣", message: #"add a blank comment line after this sentence: "This docline should not succeed.""#), - FindingSpec("3️⃣", message: #"terminate this sentence with a period: "Should fail because it doesn't have a period""#), - ] - ) + /// Should fail because it doesn't have a period + 3️⃣public class testNoPeriod {} + """, + findings: [ + FindingSpec("1️⃣", message: #"add a blank comment line after this sentence: "This docline should not succeed.""#), + FindingSpec("2️⃣", message: #"add a blank comment line after this sentence: "This docline should not succeed.""#), + FindingSpec( + "3️⃣", + message: #"terminate this sentence with a period: "Should fail because it doesn't have a period""# + ), + ] + ) #endif } - + func testSentenceTerminationInsideQuotes() { assertLint( BeginDocumentationCommentWithOneLineSummary.self, """ /// Creates an instance with the same raw value as `x` failing iff `x.kind != Subject.kind`. struct TestBackTick {} - + /// A set of `Diagnostic` that can answer the question ‘was there an error?’ in O(1). struct TestSingleSmartQuotes {} - + /// A set of `Diagnostic` that can answer the question 'was there an error?' in O(1). struct TestSingleStraightQuotes {} - + /// A set of `Diagnostic` that can answer the question “was there an error?” in O(1). struct TestDoubleSmartQuotes {} - + /// A set of `Diagnostic` that can answer the question "was there an error?" in O(1). struct TestDoubleStraightQuotes {} - + /// A set of `Diagnostic` that can answer the question “was there /// an error?” in O(1). struct TestTwoLinesDoubleSmartQuotes {} - + /// A set of `Diagnostic` that can answer the question "was there /// an error?" in O(1). struct TestTwoLinesDoubleStraightQuotes {} diff --git a/Tests/SwiftFormatTests/Rules/DoNotUseSemicolonsTests.swift b/Tests/SwiftFormatTests/Rules/DoNotUseSemicolonsTests.swift index 55a174d3d..3804701ae 100644 --- a/Tests/SwiftFormatTests/Rules/DoNotUseSemicolonsTests.swift +++ b/Tests/SwiftFormatTests/Rules/DoNotUseSemicolonsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { func testSemicolonUse() { @@ -120,7 +119,7 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { ] ) } - + func testBlockCommentAtEndOfBlock() { assertFormatting( DoNotUseSemicolons.self, @@ -131,7 +130,7 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { print("hello") /* block comment */ """, findings: [ - FindingSpec("1️⃣", message: "remove ';'"), + FindingSpec("1️⃣", message: "remove ';'") ] ) @@ -148,7 +147,7 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove ';'"), + FindingSpec("1️⃣", message: "remove ';'") ] ) } @@ -164,7 +163,7 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { /* block comment */ print("world") """, findings: [ - FindingSpec("1️⃣", message: "remove ';' and move the next statement to a new line"), + FindingSpec("1️⃣", message: "remove ';' and move the next statement to a new line") ] ) @@ -181,7 +180,7 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove ';'"), + FindingSpec("1️⃣", message: "remove ';'") ] ) } @@ -222,7 +221,7 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase { for _ in 0..<10 { g() } """, findings: [ - FindingSpec("1️⃣", message: "remove ';'"), + FindingSpec("1️⃣", message: "remove ';'") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/DontRepeatTypeInStaticPropertiesTests.swift b/Tests/SwiftFormatTests/Rules/DontRepeatTypeInStaticPropertiesTests.swift index 801a89a8c..2eb12dd82 100644 --- a/Tests/SwiftFormatTests/Rules/DontRepeatTypeInStaticPropertiesTests.swift +++ b/Tests/SwiftFormatTests/Rules/DontRepeatTypeInStaticPropertiesTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class DontRepeatTypeInStaticPropertiesTests: LintOrFormatRuleTestCase { func testRepetitiveProperties() { @@ -71,24 +70,23 @@ final class DontRepeatTypeInStaticPropertiesTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove the suffix 'Thing' from the name of the variable 'defaultThing'"), + FindingSpec("1️⃣", message: "remove the suffix 'Thing' from the name of the variable 'defaultThing'") ] ) } - func testIgnoreSingleDecl() { assertLint( DontRepeatTypeInStaticProperties.self, - """ - struct Foo { - // swift-format-ignore: DontRepeatTypeInStaticProperties - static let defaultFoo: Int - static let 1️⃣alternateFoo: Int - } - """, + """ + struct Foo { + // swift-format-ignore: DontRepeatTypeInStaticProperties + static let defaultFoo: Int + static let 1️⃣alternateFoo: Int + } + """, findings: [ - FindingSpec("1️⃣", message: "remove the suffix 'Foo' from the name of the variable 'alternateFoo'"), + FindingSpec("1️⃣", message: "remove the suffix 'Foo' from the name of the variable 'alternateFoo'") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/FileScopedDeclarationPrivacyTests.swift b/Tests/SwiftFormatTests/Rules/FileScopedDeclarationPrivacyTests.swift index e41130251..88e425ac6 100644 --- a/Tests/SwiftFormatTests/Rules/FileScopedDeclarationPrivacyTests.swift +++ b/Tests/SwiftFormatTests/Rules/FileScopedDeclarationPrivacyTests.swift @@ -1,9 +1,8 @@ import SwiftFormat +@_spi(Rules) import SwiftFormat import SwiftSyntax import _SwiftFormatTestSupport -@_spi(Rules) import SwiftFormat - private typealias TestConfiguration = ( original: String, desired: FileScopedDeclarationPrivacyConfiguration.AccessLevel, @@ -154,7 +153,7 @@ final class FileScopedDeclarationPrivacyTests: LintOrFormatRuleTestCase { testConfigurations: changingTestConfigurations ) { original, expected in [ - FindingSpec("1️⃣", message: "replace '\(original)' with '\(expected)' on file-scoped declarations"), + FindingSpec("1️⃣", message: "replace '\(original)' with '\(expected)' on file-scoped declarations") ] } } @@ -175,7 +174,9 @@ final class FileScopedDeclarationPrivacyTests: LintOrFormatRuleTestCase { let markedSource = MarkedText(textWithMarkers: source) let substitutedExpected = markedSource.textWithoutMarkers.replacingOccurrences( - of: "$access$", with: testConfig.expected) + of: "$access$", + with: testConfig.expected + ) // Only use the findings if the output was expected to change. If it didn't change, then the // rule wouldn't have emitted anything. @@ -193,7 +194,8 @@ final class FileScopedDeclarationPrivacyTests: LintOrFormatRuleTestCase { findings: findingSpecs, configuration: configuration, file: file, - line: line) + line: line + ) } } } diff --git a/Tests/SwiftFormatTests/Rules/FullyIndirectEnumTests.swift b/Tests/SwiftFormatTests/Rules/FullyIndirectEnumTests.swift index a1eff743d..8b9a7d985 100644 --- a/Tests/SwiftFormatTests/Rules/FullyIndirectEnumTests.swift +++ b/Tests/SwiftFormatTests/Rules/FullyIndirectEnumTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport class FullyIndirectEnumTests: LintOrFormatRuleTestCase { func testAllIndirectCases() { @@ -35,7 +34,7 @@ class FullyIndirectEnumTests: LintOrFormatRuleTestCase { NoteSpec("3️⃣", message: "remove 'indirect' here"), NoteSpec("4️⃣", message: "remove 'indirect' here"), ] - ), + ) ] ) } @@ -72,7 +71,7 @@ class FullyIndirectEnumTests: LintOrFormatRuleTestCase { NoteSpec("3️⃣", message: "remove 'indirect' here"), NoteSpec("4️⃣", message: "remove 'indirect' here"), ] - ), + ) ] ) } diff --git a/Tests/SwiftFormatTests/Rules/GroupNumericLiteralsTests.swift b/Tests/SwiftFormatTests/Rules/GroupNumericLiteralsTests.swift index 01c32b0ef..abb8c148b 100644 --- a/Tests/SwiftFormatTests/Rules/GroupNumericLiteralsTests.swift +++ b/Tests/SwiftFormatTests/Rules/GroupNumericLiteralsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class GroupNumericLiteralsTests: LintOrFormatRuleTestCase { func testNumericGrouping() { diff --git a/Tests/SwiftFormatTests/Rules/IdentifiersMustBeASCIITests.swift b/Tests/SwiftFormatTests/Rules/IdentifiersMustBeASCIITests.swift index 902438c96..6c4545dba 100644 --- a/Tests/SwiftFormatTests/Rules/IdentifiersMustBeASCIITests.swift +++ b/Tests/SwiftFormatTests/Rules/IdentifiersMustBeASCIITests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class IdentifiersMustBeASCIITests: LintOrFormatRuleTestCase { func testInvalidIdentifiers() { diff --git a/Tests/SwiftFormatTests/Rules/ImportsXCTestVisitorTests.swift b/Tests/SwiftFormatTests/Rules/ImportsXCTestVisitorTests.swift index 7e28f0958..f4d8cb26f 100644 --- a/Tests/SwiftFormatTests/Rules/ImportsXCTestVisitorTests.swift +++ b/Tests/SwiftFormatTests/Rules/ImportsXCTestVisitorTests.swift @@ -1,47 +1,54 @@ import SwiftFormat +@_spi(Rules) @_spi(Testing) import SwiftFormat import SwiftParser import XCTest -@_spi(Rules) @_spi(Testing) import SwiftFormat - class ImportsXCTestVisitorTests: XCTestCase { func testDoesNotImportXCTest() throws { XCTAssertEqual( - try makeContextAndSetImportsXCTest(source: """ - import Foundation - """), + try makeContextAndSetImportsXCTest( + source: """ + import Foundation + """ + ), .doesNotImportXCTest ) } func testImportsXCTest() throws { XCTAssertEqual( - try makeContextAndSetImportsXCTest(source: """ - import Foundation - import XCTest - """), + try makeContextAndSetImportsXCTest( + source: """ + import Foundation + import XCTest + """ + ), .importsXCTest ) } func testImportsSpecificXCTestDecl() throws { XCTAssertEqual( - try makeContextAndSetImportsXCTest(source: """ - import Foundation - import class XCTest.XCTestCase - """), + try makeContextAndSetImportsXCTest( + source: """ + import Foundation + import class XCTest.XCTestCase + """ + ), .importsXCTest ) } func testImportsXCTestInsideConditional() throws { XCTAssertEqual( - try makeContextAndSetImportsXCTest(source: """ - import Foundation - #if SOME_FEATURE_FLAG - import XCTest - #endif - """), + try makeContextAndSetImportsXCTest( + source: """ + import Foundation + #if SOME_FEATURE_FLAG + import XCTest + #endif + """ + ), .importsXCTest ) } @@ -56,7 +63,8 @@ class ImportsXCTestVisitorTests: XCTestCase { findingConsumer: { _ in }, fileURL: URL(fileURLWithPath: "/tmp/test.swift"), sourceFileSyntax: sourceFile, - ruleNameCache: ruleNameCache) + ruleNameCache: ruleNameCache + ) setImportsXCTest(context: context, sourceFile: sourceFile) return context.importsXCTest } diff --git a/Tests/SwiftFormatTests/Rules/LintOrFormatRuleTestCase.swift b/Tests/SwiftFormatTests/Rules/LintOrFormatRuleTestCase.swift index 953f1e254..49c26bd1f 100644 --- a/Tests/SwiftFormatTests/Rules/LintOrFormatRuleTestCase.swift +++ b/Tests/SwiftFormatTests/Rules/LintOrFormatRuleTestCase.swift @@ -1,10 +1,9 @@ import SwiftFormat +@_spi(Rules) @_spi(Testing) import SwiftFormat import SwiftOperators import SwiftParser import SwiftSyntax import XCTest - -@_spi(Rules) @_spi(Testing) import SwiftFormat @_spi(Testing) import _SwiftFormatTestSupport class LintOrFormatRuleTestCase: DiagnosingTestCase { @@ -41,20 +40,23 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase { sourceFileSyntax: sourceFileSyntax, configuration: configuration, selection: .infinite, - findingConsumer: { emittedFindings.append($0) }) + findingConsumer: { emittedFindings.append($0) } + ) var emittedPipelineFindings = [Finding]() // Disable default rules, so only select rule runs in pipeline configuration.rules = [type.ruleName: true] let pipeline = SwiftLinter( configuration: configuration, - findingConsumer: { emittedPipelineFindings.append($0) }) + findingConsumer: { emittedPipelineFindings.append($0) } + ) pipeline.debugOptions.insert(.disablePrettyPrint) try! pipeline.lint( syntax: sourceFileSyntax, source: unmarkedSource, operatorTable: OperatorTable.standardOperators, - assumingFileURL: URL(string: file.description)!) + assumingFileURL: URL(string: file.description)! + ) // Check that pipeline produces the expected findings assertFindings( @@ -63,7 +65,8 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase { emittedFindings: emittedPipelineFindings, context: context, file: file, - line: line) + line: line + ) } /// Asserts that the result of applying a formatter to the provided input code yields the output. @@ -103,7 +106,8 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase { sourceFileSyntax: sourceFileSyntax, configuration: configuration, selection: .infinite, - findingConsumer: { emittedFindings.append($0) }) + findingConsumer: { emittedFindings.append($0) } + ) let formatter = formatType.init(context: context) let actual = formatter.visit(sourceFileSyntax) @@ -115,7 +119,8 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase { emittedFindings: emittedFindings, context: context, file: file, - line: line) + line: line + ) // Verify that the pretty printer can consume the transformed tree (e.g., it does not contain // any unfolded `SequenceExpr`s). Then do a whitespace-insensitive comparison of the two trees @@ -134,22 +139,36 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase { whitespaceInsensitiveText(of: actual), whitespaceInsensitiveText(of: prettyPrintedTree), "After pretty-printing and removing fluid whitespace, the files did not match", - file: file, line: line) + file: file, + line: line + ) var emittedPipelineFindings = [Finding]() // Disable default rules, so only select rule runs in pipeline configuration.rules = [formatType.ruleName: true] let pipeline = SwiftFormatter( - configuration: configuration, findingConsumer: { emittedPipelineFindings.append($0) }) + configuration: configuration, + findingConsumer: { emittedPipelineFindings.append($0) } + ) pipeline.debugOptions.insert(.disablePrettyPrint) var pipelineActual = "" try! pipeline.format( - syntax: sourceFileSyntax, source: originalSource, operatorTable: OperatorTable.standardOperators, - assumingFileURL: nil, selection: .infinite, to: &pipelineActual) + syntax: sourceFileSyntax, + source: originalSource, + operatorTable: OperatorTable.standardOperators, + assumingFileURL: nil, + selection: .infinite, + to: &pipelineActual + ) assertStringsEqualWithDiff(pipelineActual, expected) assertFindings( - expected: findings, markerLocations: markedInput.markers, - emittedFindings: emittedPipelineFindings, context: context, file: file, line: line) + expected: findings, + markerLocations: markedInput.markers, + emittedFindings: emittedPipelineFindings, + context: context, + file: file, + line: line + ) } } diff --git a/Tests/SwiftFormatTests/Rules/NeverForceUnwrapTests.swift b/Tests/SwiftFormatTests/Rules/NeverForceUnwrapTests.swift index 7ce22b686..9d4d61f4b 100644 --- a/Tests/SwiftFormatTests/Rules/NeverForceUnwrapTests.swift +++ b/Tests/SwiftFormatTests/Rules/NeverForceUnwrapTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NeverForceUnwrapTests: LintOrFormatRuleTestCase { func testUnsafeUnwrap() { diff --git a/Tests/SwiftFormatTests/Rules/NeverUseForceTryTests.swift b/Tests/SwiftFormatTests/Rules/NeverUseForceTryTests.swift index 0fd51be28..907264222 100644 --- a/Tests/SwiftFormatTests/Rules/NeverUseForceTryTests.swift +++ b/Tests/SwiftFormatTests/Rules/NeverUseForceTryTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NeverUseForceTryTests: LintOrFormatRuleTestCase { func testInvalidTryExpression() { @@ -38,7 +37,7 @@ final class NeverUseForceTryTests: LintOrFormatRuleTestCase { findings: [] ) } - + func testAllowForceTryInTestAttributeFunction() { assertLint( NeverUseForceTry.self, diff --git a/Tests/SwiftFormatTests/Rules/NeverUseImplicitlyUnwrappedOptionalsTests.swift b/Tests/SwiftFormatTests/Rules/NeverUseImplicitlyUnwrappedOptionalsTests.swift index c79ee3db0..2de8f4ee3 100644 --- a/Tests/SwiftFormatTests/Rules/NeverUseImplicitlyUnwrappedOptionalsTests.swift +++ b/Tests/SwiftFormatTests/Rules/NeverUseImplicitlyUnwrappedOptionalsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NeverUseImplicitlyUnwrappedOptionalsTests: LintOrFormatRuleTestCase { func testInvalidVariableUnwrapping() { diff --git a/Tests/SwiftFormatTests/Rules/NoAccessLevelOnExtensionDeclarationTests.swift b/Tests/SwiftFormatTests/Rules/NoAccessLevelOnExtensionDeclarationTests.swift index f020059cb..6735b8861 100644 --- a/Tests/SwiftFormatTests/Rules/NoAccessLevelOnExtensionDeclarationTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoAccessLevelOnExtensionDeclarationTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { func testExtensionDeclarationAccessLevel() { @@ -55,7 +54,7 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { NoteSpec("9️⃣", message: "add 'public' access modifier to this declaration"), NoteSpec("🔟", message: "add 'public' access modifier to this declaration"), ] - ), + ) ] ) } @@ -76,7 +75,7 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this redundant 'internal' access modifier from this extension"), + FindingSpec("1️⃣", message: "remove this redundant 'internal' access modifier from this extension") ] ) } @@ -146,9 +145,9 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { "1️⃣", message: "move this 'package' access modifier to precede each member inside this extension", notes: [ - NoteSpec("2️⃣", message: "add 'package' access modifier to this declaration"), + NoteSpec("2️⃣", message: "add 'package' access modifier to this declaration") ] - ), + ) ] ) } @@ -169,11 +168,12 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { findings: [ FindingSpec( "1️⃣", - message: "remove this 'private' access modifier and declare each member inside this extension as 'fileprivate'", + message: + "remove this 'private' access modifier and declare each member inside this extension as 'fileprivate'", notes: [ - NoteSpec("2️⃣", message: "add 'fileprivate' access modifier to this declaration"), + NoteSpec("2️⃣", message: "add 'fileprivate' access modifier to this declaration") ] - ), + ) ] ) } @@ -192,7 +192,7 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this 'public' access modifier to precede each member inside this extension"), + FindingSpec("1️⃣", message: "move this 'public' access modifier to precede each member inside this extension") ] ) } @@ -250,7 +250,7 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { NoteSpec("8️⃣", message: "add 'public' access modifier to this declaration"), NoteSpec("9️⃣", message: "add 'public' access modifier to this declaration"), ] - ), + ) ] ) } @@ -340,7 +340,7 @@ final class NoAccessLevelOnExtensionDeclarationTests: LintOrFormatRuleTestCase { NoteSpec("8️⃣", message: "add 'public' access modifier to this declaration"), NoteSpec("9️⃣", message: "add 'public' access modifier to this declaration"), ] - ), + ) ] ) } diff --git a/Tests/SwiftFormatTests/Rules/NoAssignmentInExpressionsTests.swift b/Tests/SwiftFormatTests/Rules/NoAssignmentInExpressionsTests.swift index 83cb939c3..9ac022653 100644 --- a/Tests/SwiftFormatTests/Rules/NoAssignmentInExpressionsTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoAssignmentInExpressionsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { func testAssignmentInExpressionContextIsDiagnosed() { @@ -13,7 +12,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { foo(bar, baz = quux, a + b) """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -69,7 +68,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -89,7 +88,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -111,7 +110,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -131,7 +130,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -151,7 +150,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -171,7 +170,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } @@ -221,7 +220,7 @@ final class NoAssignmentInExpressionsTests: LintOrFormatRuleTestCase { someRegularFunction(a = b) """, findings: [ - FindingSpec("1️⃣", message: "move this assignment expression into its own statement"), + FindingSpec("1️⃣", message: "move this assignment expression into its own statement") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/NoBlockCommentsTests.swift b/Tests/SwiftFormatTests/Rules/NoBlockCommentsTests.swift index bc2fe31c7..afd82e297 100644 --- a/Tests/SwiftFormatTests/Rules/NoBlockCommentsTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoBlockCommentsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoBlockCommentsTests: LintOrFormatRuleTestCase { func testDiagnoseBlockComments() { diff --git a/Tests/SwiftFormatTests/Rules/NoCasesWithOnlyFallthroughTests.swift b/Tests/SwiftFormatTests/Rules/NoCasesWithOnlyFallthroughTests.swift index 873b60797..66e7da94a 100644 --- a/Tests/SwiftFormatTests/Rules/NoCasesWithOnlyFallthroughTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoCasesWithOnlyFallthroughTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoCasesWithOnlyFallthroughTests: LintOrFormatRuleTestCase { func testFallthroughCases() { @@ -330,7 +329,7 @@ final class NoCasesWithOnlyFallthroughTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "combine this fallthrough-only 'case' and the following 'case' into a single 'case'"), + FindingSpec("1️⃣", message: "combine this fallthrough-only 'case' and the following 'case' into a single 'case'") ] ) } @@ -352,7 +351,7 @@ final class NoCasesWithOnlyFallthroughTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "combine this fallthrough-only 'case' and the following 'case' into a single 'case'"), + FindingSpec("1️⃣", message: "combine this fallthrough-only 'case' and the following 'case' into a single 'case'") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/NoEmptyLinesOpeningClosingBracesTests.swift b/Tests/SwiftFormatTests/Rules/NoEmptyLinesOpeningClosingBracesTests.swift index 294a38210..30f9471fc 100644 --- a/Tests/SwiftFormatTests/Rules/NoEmptyLinesOpeningClosingBracesTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoEmptyLinesOpeningClosingBracesTests.swift @@ -1,106 +1,105 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoEmptyLinesOpeningClosingBracesTests: LintOrFormatRuleTestCase { func testNoEmptyLinesOpeningClosingBracesInCodeBlock() { assertFormatting( NoEmptyLinesOpeningClosingBraces.self, input: """ - func f() {1️⃣ - - // - return - - - 2️⃣} - """, + func f() {1️⃣ + + // + return + + + 2️⃣} + """, expected: """ - func f() { - // - return - } - """, + func f() { + // + return + } + """, findings: [ FindingSpec("1️⃣", message: "remove empty line after '{'"), FindingSpec("2️⃣", message: "remove empty lines before '}'"), ] ) } - + func testNoEmptyLinesOpeningClosingBracesInMemberBlock() { assertFormatting( NoEmptyLinesOpeningClosingBraces.self, input: """ - struct {1️⃣ - - let x: Int - - let y: Int + struct {1️⃣ - 2️⃣} - """, + let x: Int + + let y: Int + + 2️⃣} + """, expected: """ - struct { - let x: Int - - let y: Int - } - """, + struct { + let x: Int + + let y: Int + } + """, findings: [ FindingSpec("1️⃣", message: "remove empty line after '{'"), FindingSpec("2️⃣", message: "remove empty line before '}'"), ] ) } - + func testNoEmptyLinesOpeningClosingBracesInAccessorBlock() { assertFormatting( NoEmptyLinesOpeningClosingBraces.self, input: """ - var x: Int {1️⃣ - - // - return _x - - 2️⃣} - - var y: Int {3️⃣ - - get 5️⃣{ - - // - return _y + var x: Int {1️⃣ - 6️⃣ } - - set 7️⃣{ - - // - _x = newValue - - 8️⃣ } + // + return _x + + 2️⃣} + + var y: Int {3️⃣ + + get 5️⃣{ - 4️⃣} - """, + // + return _y + + 6️⃣ } + + set 7️⃣{ + + // + _x = newValue + + 8️⃣ } + + 4️⃣} + """, expected: """ - var x: Int { + var x: Int { + // + return _x + } + + var y: Int { + get { // - return _x + return _y } - - var y: Int { - get { - // - return _y - } - - set { - // - _x = newValue - } + + set { + // + _x = newValue } - """, + } + """, findings: [ FindingSpec("1️⃣", message: "remove empty line after '{'"), FindingSpec("2️⃣", message: "remove empty line before '}'"), @@ -118,19 +117,19 @@ final class NoEmptyLinesOpeningClosingBracesTests: LintOrFormatRuleTestCase { assertFormatting( NoEmptyLinesOpeningClosingBraces.self, input: """ - let closure = {1️⃣ - - // - return - - 2️⃣} - """, + let closure = {1️⃣ + + // + return + + 2️⃣} + """, expected: """ - let closure = { - // - return - } - """, + let closure = { + // + return + } + """, findings: [ FindingSpec("1️⃣", message: "remove empty line after '{'"), FindingSpec("2️⃣", message: "remove empty line before '}'"), diff --git a/Tests/SwiftFormatTests/Rules/NoEmptyTrailingClosureParenthesesTests.swift b/Tests/SwiftFormatTests/Rules/NoEmptyTrailingClosureParenthesesTests.swift index d5b6275a7..0e11de115 100644 --- a/Tests/SwiftFormatTests/Rules/NoEmptyTrailingClosureParenthesesTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoEmptyTrailingClosureParenthesesTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoEmptyTrailingClosureParenthesesTests: LintOrFormatRuleTestCase { func testInvalidEmptyParenTrailingClosure() { diff --git a/Tests/SwiftFormatTests/Rules/NoLabelsInCasePatternsTests.swift b/Tests/SwiftFormatTests/Rules/NoLabelsInCasePatternsTests.swift index e4cbf1450..ab95fb2ec 100644 --- a/Tests/SwiftFormatTests/Rules/NoLabelsInCasePatternsTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoLabelsInCasePatternsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoLabelsInCasePatternsTests: LintOrFormatRuleTestCase { func testRedundantCaseLabels() { diff --git a/Tests/SwiftFormatTests/Rules/NoLeadingUnderscoresTests.swift b/Tests/SwiftFormatTests/Rules/NoLeadingUnderscoresTests.swift index 704680f2f..8339bed9a 100644 --- a/Tests/SwiftFormatTests/Rules/NoLeadingUnderscoresTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoLeadingUnderscoresTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoLeadingUnderscoresTests: LintOrFormatRuleTestCase { func testVars() { @@ -135,7 +134,7 @@ final class NoLeadingUnderscoresTests: LintOrFormatRuleTestCase { infix operator <> : _BazPrecedence """, findings: [ - FindingSpec("1️⃣", message: "remove the leading '_' from the name '_FooPrecedence'"), + FindingSpec("1️⃣", message: "remove the leading '_' from the name '_FooPrecedence'") ] ) } @@ -148,7 +147,7 @@ final class NoLeadingUnderscoresTests: LintOrFormatRuleTestCase { typealias 1️⃣_Bar = Bar """, findings: [ - FindingSpec("1️⃣", message: "remove the leading '_' from the name '_Bar'"), + FindingSpec("1️⃣", message: "remove the leading '_' from the name '_Bar'") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/NoParensAroundConditionsTests.swift b/Tests/SwiftFormatTests/Rules/NoParensAroundConditionsTests.swift index 7f87043ed..7925b57cf 100644 --- a/Tests/SwiftFormatTests/Rules/NoParensAroundConditionsTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoParensAroundConditionsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoParensAroundConditionsTests: LintOrFormatRuleTestCase { func testParensAroundConditions() { diff --git a/Tests/SwiftFormatTests/Rules/NoPlaygroundLiteralsTests.swift b/Tests/SwiftFormatTests/Rules/NoPlaygroundLiteralsTests.swift index 91d659053..3cc205fde 100644 --- a/Tests/SwiftFormatTests/Rules/NoPlaygroundLiteralsTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoPlaygroundLiteralsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoPlaygroundLiteralsTests: LintOrFormatRuleTestCase { func testColorLiterals() { @@ -40,9 +39,18 @@ final class NoPlaygroundLiteralsTests: LintOrFormatRuleTestCase { _ = #fileLiteral(resourceName: "secrets.json") """, findings: [ - FindingSpec("1️⃣", message: "replace '#fileLiteral' with a call to a method such as 'Bundle.url(forResource:withExtension:)'"), - FindingSpec("2️⃣", message: "replace '#fileLiteral' with a call to a method such as 'Bundle.url(forResource:withExtension:)'"), - FindingSpec("3️⃣", message: "replace '#fileLiteral' with a call to a method such as 'Bundle.url(forResource:withExtension:)'"), + FindingSpec( + "1️⃣", + message: "replace '#fileLiteral' with a call to a method such as 'Bundle.url(forResource:withExtension:)'" + ), + FindingSpec( + "2️⃣", + message: "replace '#fileLiteral' with a call to a method such as 'Bundle.url(forResource:withExtension:)'" + ), + FindingSpec( + "3️⃣", + message: "replace '#fileLiteral' with a call to a method such as 'Bundle.url(forResource:withExtension:)'" + ), ] ) } diff --git a/Tests/SwiftFormatTests/Rules/NoVoidReturnOnFunctionSignatureTests.swift b/Tests/SwiftFormatTests/Rules/NoVoidReturnOnFunctionSignatureTests.swift index 7c0c5a88d..20247a289 100644 --- a/Tests/SwiftFormatTests/Rules/NoVoidReturnOnFunctionSignatureTests.swift +++ b/Tests/SwiftFormatTests/Rules/NoVoidReturnOnFunctionSignatureTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class NoVoidReturnOnFunctionSignatureTests: LintOrFormatRuleTestCase { func testVoidReturns() { diff --git a/Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift b/Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift index b5c2f9449..ae0d84188 100644 --- a/Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift +++ b/Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift @@ -1,119 +1,122 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class OmitReturnsTests: LintOrFormatRuleTestCase { func testOmitReturnInFunction() { assertFormatting( OmitExplicitReturns.self, input: """ - func test() -> Bool { - 1️⃣return false - } - """, + func test() -> Bool { + 1️⃣return false + } + """, expected: """ - func test() -> Bool { - false - } - """, + func test() -> Bool { + false + } + """, findings: [ FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression") - ]) + ] + ) } func testOmitReturnInClosure() { assertFormatting( OmitExplicitReturns.self, input: """ - vals.filter { - 1️⃣return $0.count == 1 - } - """, + vals.filter { + 1️⃣return $0.count == 1 + } + """, expected: """ - vals.filter { - $0.count == 1 - } - """, + vals.filter { + $0.count == 1 + } + """, findings: [ FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression") - ]) + ] + ) } func testOmitReturnInSubscript() { assertFormatting( OmitExplicitReturns.self, input: """ - struct Test { - subscript(x: Int) -> Bool { - 1️⃣return false + struct Test { + subscript(x: Int) -> Bool { + 1️⃣return false + } } - } - struct Test { - subscript(x: Int) -> Bool { - get { - 2️⃣return false + struct Test { + subscript(x: Int) -> Bool { + get { + 2️⃣return false + } + set { } } - set { } } - } - """, + """, expected: """ - struct Test { - subscript(x: Int) -> Bool { - false + struct Test { + subscript(x: Int) -> Bool { + false + } } - } - struct Test { - subscript(x: Int) -> Bool { - get { - false + struct Test { + subscript(x: Int) -> Bool { + get { + false + } + set { } } - set { } } - } - """, + """, findings: [ FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression"), - FindingSpec("2️⃣", message: "'return' can be omitted because body consists of a single expression") - ]) + FindingSpec("2️⃣", message: "'return' can be omitted because body consists of a single expression"), + ] + ) } func testOmitReturnInComputedVars() { assertFormatting( OmitExplicitReturns.self, input: """ - var x: Int { - 1️⃣return 42 - } - - struct Test { var x: Int { - get { - 2️⃣return 42 + 1️⃣return 42 + } + + struct Test { + var x: Int { + get { + 2️⃣return 42 + } + set { } } - set { } } - } - """, + """, expected: """ - var x: Int { - 42 - } - - struct Test { var x: Int { - get { - 42 + 42 + } + + struct Test { + var x: Int { + get { + 42 + } + set { } } - set { } } - } - """, + """, findings: [ FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression"), - FindingSpec("2️⃣", message: "'return' can be omitted because body consists of a single expression") - ]) + FindingSpec("2️⃣", message: "'return' can be omitted because body consists of a single expression"), + ] + ) } } diff --git a/Tests/SwiftFormatTests/Rules/OneCasePerLineTests.swift b/Tests/SwiftFormatTests/Rules/OneCasePerLineTests.swift index 623418884..23c809a8d 100644 --- a/Tests/SwiftFormatTests/Rules/OneCasePerLineTests.swift +++ b/Tests/SwiftFormatTests/Rules/OneCasePerLineTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class OneCasePerLineTests: LintOrFormatRuleTestCase { @@ -68,7 +67,7 @@ final class OneCasePerLineTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move 'a' to its own 'case' declaration"), + FindingSpec("1️⃣", message: "move 'a' to its own 'case' declaration") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/OneVariableDeclarationPerLineTests.swift b/Tests/SwiftFormatTests/Rules/OneVariableDeclarationPerLineTests.swift index cb951bbd5..3b84e467d 100644 --- a/Tests/SwiftFormatTests/Rules/OneVariableDeclarationPerLineTests.swift +++ b/Tests/SwiftFormatTests/Rules/OneVariableDeclarationPerLineTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class OneVariableDeclarationPerLineTests: LintOrFormatRuleTestCase { func testMultipleVariableBindings() { @@ -157,7 +156,7 @@ final class OneVariableDeclarationPerLineTests: LintOrFormatRuleTestCase { let c: Int """, findings: [ - FindingSpec("1️⃣", message: "split this variable declaration to introduce only one variable per 'let'"), + FindingSpec("1️⃣", message: "split this variable declaration to introduce only one variable per 'let'") ] ) } @@ -174,7 +173,7 @@ final class OneVariableDeclarationPerLineTests: LintOrFormatRuleTestCase { let /* c */ c: Int """, findings: [ - FindingSpec("1️⃣", message: "split this variable declaration to introduce only one variable per 'let'"), + FindingSpec("1️⃣", message: "split this variable declaration to introduce only one variable per 'let'") ] ) } @@ -220,7 +219,7 @@ final class OneVariableDeclarationPerLineTests: LintOrFormatRuleTestCase { var y = "foo" { didSet { print("changed") } } """, findings: [ - FindingSpec("1️⃣", message: "split this variable declaration to introduce only one variable per 'var'"), + FindingSpec("1️⃣", message: "split this variable declaration to introduce only one variable per 'var'") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/OnlyOneTrailingClosureArgumentTests.swift b/Tests/SwiftFormatTests/Rules/OnlyOneTrailingClosureArgumentTests.swift index b36a01afb..d18d03061 100644 --- a/Tests/SwiftFormatTests/Rules/OnlyOneTrailingClosureArgumentTests.swift +++ b/Tests/SwiftFormatTests/Rules/OnlyOneTrailingClosureArgumentTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class OnlyOneTrailingClosureArgumentTests: LintOrFormatRuleTestCase { func testInvalidTrailingClosureCall() { @@ -16,7 +15,10 @@ final class OnlyOneTrailingClosureArgumentTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "revise this function call to avoid using both closure arguments and a trailing closure"), + FindingSpec( + "1️⃣", + message: "revise this function call to avoid using both closure arguments and a trailing closure" + ) ] ) } diff --git a/Tests/SwiftFormatTests/Rules/OrderedImportsTests.swift b/Tests/SwiftFormatTests/Rules/OrderedImportsTests.swift index a61a07539..73d33aa77 100644 --- a/Tests/SwiftFormatTests/Rules/OrderedImportsTests.swift +++ b/Tests/SwiftFormatTests/Rules/OrderedImportsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class OrderedImportsTests: LintOrFormatRuleTestCase { func testInvalidImportsOrder() { @@ -55,7 +54,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { ] ) } - + func testImportsOrderWithoutModuleType() { assertFormatting( OrderedImports.self, @@ -84,7 +83,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { ] ) } - + func testImportsOrderWithDocComment() { assertFormatting( OrderedImports.self, @@ -119,11 +118,11 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { let a = 3 """, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } - + func testValidOrderedImport() { assertFormatting( OrderedImports.self, @@ -214,7 +213,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { input: input, expected: expected, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } @@ -235,7 +234,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { foo();bar();baz();quxxe(); """, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } @@ -255,7 +254,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { foo();bar();baz();quxxe(); """, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } @@ -390,7 +389,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { zeta """, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } @@ -413,7 +412,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { bar() """, findings: [ - FindingSpec("1️⃣", message: "remove this duplicate import"), + FindingSpec("1️⃣", message: "remove this duplicate import") ] ) } @@ -614,7 +613,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { baz() """, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } @@ -648,7 +647,7 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase { bar() // calls the bar """, findings: [ - FindingSpec("1️⃣", message: "sort import statements lexicographically"), + FindingSpec("1️⃣", message: "sort import statements lexicographically") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/ReplaceForEachWithForLoopTests.swift b/Tests/SwiftFormatTests/Rules/ReplaceForEachWithForLoopTests.swift index 295f3bfe1..6f225b249 100644 --- a/Tests/SwiftFormatTests/Rules/ReplaceForEachWithForLoopTests.swift +++ b/Tests/SwiftFormatTests/Rules/ReplaceForEachWithForLoopTests.swift @@ -1,7 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat - +import _SwiftFormatTestSupport final class ReplaceForEachWithForLoopTests: LintOrFormatRuleTestCase { func test() { @@ -27,7 +25,7 @@ final class ReplaceForEachWithForLoopTests: LintOrFormatRuleTestCase { findings: [ FindingSpec("1️⃣", message: "replace use of '.forEach { ... }' with for-in loop"), FindingSpec("2️⃣", message: "replace use of '.forEach { ... }' with for-in loop"), - FindingSpec("3️⃣", message: "replace use of '.forEach { ... }' with for-in loop") + FindingSpec("3️⃣", message: "replace use of '.forEach { ... }' with for-in loop"), ] ) } diff --git a/Tests/SwiftFormatTests/Rules/ReturnVoidInsteadOfEmptyTupleTests.swift b/Tests/SwiftFormatTests/Rules/ReturnVoidInsteadOfEmptyTupleTests.swift index 67a1837e1..17e76607f 100644 --- a/Tests/SwiftFormatTests/Rules/ReturnVoidInsteadOfEmptyTupleTests.swift +++ b/Tests/SwiftFormatTests/Rules/ReturnVoidInsteadOfEmptyTupleTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class ReturnVoidInsteadOfEmptyTupleTests: LintOrFormatRuleTestCase { func testBasic() { diff --git a/Tests/SwiftFormatTests/Rules/TypeNamesShouldBeCapitalizedTests.swift b/Tests/SwiftFormatTests/Rules/TypeNamesShouldBeCapitalizedTests.swift index f44ea743d..fa30409e4 100644 --- a/Tests/SwiftFormatTests/Rules/TypeNamesShouldBeCapitalizedTests.swift +++ b/Tests/SwiftFormatTests/Rules/TypeNamesShouldBeCapitalizedTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class TypeNamesShouldBeCapitalizedTests: LintOrFormatRuleTestCase { func testConstruction() { @@ -112,7 +111,10 @@ final class TypeNamesShouldBeCapitalizedTests: LintOrFormatRuleTestCase { FindingSpec("2️⃣", message: "rename the associated type '_value' using UpperCamelCase; for example, '_Value'"), FindingSpec("3️⃣", message: "rename the struct '_data' using UpperCamelCase; for example, '_Data'"), FindingSpec("4️⃣", message: "rename the type alias '_x' using UpperCamelCase; for example, '_X'"), - FindingSpec("5️⃣", message: "rename the actor '_internalActor' using UpperCamelCase; for example, '_InternalActor'"), + FindingSpec( + "5️⃣", + message: "rename the actor '_internalActor' using UpperCamelCase; for example, '_InternalActor'" + ), FindingSpec("6️⃣", message: "rename the enum '__e' using UpperCamelCase; for example, '__E'"), FindingSpec("7️⃣", message: "rename the class '_myClass' using UpperCamelCase; for example, '_MyClass'"), FindingSpec("8️⃣", message: "rename the actor '__greeter' using UpperCamelCase; for example, '__Greeter'"), diff --git a/Tests/SwiftFormatTests/Rules/UseEarlyExitsTests.swift b/Tests/SwiftFormatTests/Rules/UseEarlyExitsTests.swift index f9d54d2fc..b488bdcd1 100644 --- a/Tests/SwiftFormatTests/Rules/UseEarlyExitsTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseEarlyExitsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseEarlyExitsTests: LintOrFormatRuleTestCase { func testBasicIfElse() { @@ -25,7 +24,7 @@ final class UseEarlyExitsTests: LintOrFormatRuleTestCase { trueBlock() """, findings: [ - FindingSpec("1️⃣", message: "replace this 'if/else' block with a 'guard' statement containing the early exit"), + FindingSpec("1️⃣", message: "replace this 'if/else' block with a 'guard' statement containing the early exit") ] ) } @@ -51,7 +50,7 @@ final class UseEarlyExitsTests: LintOrFormatRuleTestCase { return """, findings: [ - FindingSpec("1️⃣", message: "replace this 'if/else' block with a 'guard' statement containing the early exit"), + FindingSpec("1️⃣", message: "replace this 'if/else' block with a 'guard' statement containing the early exit") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/UseExplicitNilCheckInConditionsTests.swift b/Tests/SwiftFormatTests/Rules/UseExplicitNilCheckInConditionsTests.swift index d15c6acfa..062de9927 100644 --- a/Tests/SwiftFormatTests/Rules/UseExplicitNilCheckInConditionsTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseExplicitNilCheckInConditionsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseExplicitNilCheckInConditionsTests: LintOrFormatRuleTestCase { func testIfExpressions() { @@ -124,7 +123,7 @@ final class UseExplicitNilCheckInConditionsTests: LintOrFormatRuleTestCase { if (x ? y : z) != nil {} """, findings: [ - FindingSpec("1️⃣", message: "compare this value using `!= nil` instead of binding and discarding it"), + FindingSpec("1️⃣", message: "compare this value using `!= nil` instead of binding and discarding it") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/UseLetInEveryBoundCaseVariableTests.swift b/Tests/SwiftFormatTests/Rules/UseLetInEveryBoundCaseVariableTests.swift index 3748173e7..bf6912635 100644 --- a/Tests/SwiftFormatTests/Rules/UseLetInEveryBoundCaseVariableTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseLetInEveryBoundCaseVariableTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseLetInEveryBoundCaseVariableTests: LintOrFormatRuleTestCase { func testSwitchCase() { @@ -19,11 +18,26 @@ final class UseLetInEveryBoundCaseVariableTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("2️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("3️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("4️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("5️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), + FindingSpec( + "1️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "2️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "3️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "4️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "5️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), ] ) } @@ -42,11 +56,26 @@ final class UseLetInEveryBoundCaseVariableTests: LintOrFormatRuleTestCase { if case let x as SomeType = someValue {} """, findings: [ - FindingSpec("1️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("2️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("3️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("4️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("5️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), + FindingSpec( + "1️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "2️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "3️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "4️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "5️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), ] ) } @@ -65,11 +94,26 @@ final class UseLetInEveryBoundCaseVariableTests: LintOrFormatRuleTestCase { guard case let x as SomeType = someValue else {} """, findings: [ - FindingSpec("1️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("2️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("3️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("4️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("5️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), + FindingSpec( + "1️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "2️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "3️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "4️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "5️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), ] ) } @@ -88,11 +132,26 @@ final class UseLetInEveryBoundCaseVariableTests: LintOrFormatRuleTestCase { for case let x as SomeType in {} """, findings: [ - FindingSpec("1️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("2️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("3️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("4️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("5️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), + FindingSpec( + "1️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "2️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "3️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "4️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "5️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), ] ) } @@ -111,11 +170,26 @@ final class UseLetInEveryBoundCaseVariableTests: LintOrFormatRuleTestCase { while case let x as SomeType = iter.next() {} """, findings: [ - FindingSpec("1️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("2️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("3️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("4️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), - FindingSpec("5️⃣", message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables"), + FindingSpec( + "1️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "2️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "3️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "4️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), + FindingSpec( + "5️⃣", + message: "move this 'let' keyword inside the 'case' pattern, before each of the bound variables" + ), ] ) } diff --git a/Tests/SwiftFormatTests/Rules/UseShorthandTypeNamesTests.swift b/Tests/SwiftFormatTests/Rules/UseShorthandTypeNamesTests.swift index ce1f3d797..188c7e4f8 100644 --- a/Tests/SwiftFormatTests/Rules/UseShorthandTypeNamesTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseShorthandTypeNamesTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseShorthandTypeNamesTests: LintOrFormatRuleTestCase { func testNamesInTypeContextsAreShortened() { @@ -560,7 +559,7 @@ final class UseShorthandTypeNamesTests: LintOrFormatRuleTestCase { let c: Int? """, findings: [ - FindingSpec("1️⃣", message: "use shorthand syntax for this 'Optional' type"), + FindingSpec("1️⃣", message: "use shorthand syntax for this 'Optional' type") ] ) } diff --git a/Tests/SwiftFormatTests/Rules/UseSingleLinePropertyGetterTests.swift b/Tests/SwiftFormatTests/Rules/UseSingleLinePropertyGetterTests.swift index c5086c0d6..0d66e4654 100644 --- a/Tests/SwiftFormatTests/Rules/UseSingleLinePropertyGetterTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseSingleLinePropertyGetterTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseSingleLinePropertyGetterTests: LintOrFormatRuleTestCase { func testMultiLinePropertyGetter() { @@ -65,7 +64,10 @@ final class UseSingleLinePropertyGetterTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove 'get {...}' around the accessor and move its body directly into the computed property"), + FindingSpec( + "1️⃣", + message: "remove 'get {...}' around the accessor and move its body directly into the computed property" + ) ] ) } diff --git a/Tests/SwiftFormatTests/Rules/UseSynthesizedInitializerTests.swift b/Tests/SwiftFormatTests/Rules/UseSynthesizedInitializerTests.swift index a21c99ba8..858393acd 100644 --- a/Tests/SwiftFormatTests/Rules/UseSynthesizedInitializerTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseSynthesizedInitializerTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { func testMemberwiseInitializerIsDiagnosed() { @@ -21,7 +20,10 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ) ] ) } @@ -41,7 +43,10 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ) ] ) } @@ -64,7 +69,10 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ) ] ) } @@ -87,7 +95,10 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ) ] ) } @@ -353,7 +364,10 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ) ] ) } @@ -376,7 +390,10 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ) ] ) } @@ -428,9 +445,18 @@ final class UseSynthesizedInitializerTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), - FindingSpec("2️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), - FindingSpec("3️⃣", message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer"), + FindingSpec( + "1️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ), + FindingSpec( + "2️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ), + FindingSpec( + "3️⃣", + message: "remove this explicit initializer, which is identical to the compiler-synthesized initializer" + ), ] ) } diff --git a/Tests/SwiftFormatTests/Rules/UseTripleSlashForDocumentationCommentsTests.swift b/Tests/SwiftFormatTests/Rules/UseTripleSlashForDocumentationCommentsTests.swift index d5c460c72..1691e3c0b 100644 --- a/Tests/SwiftFormatTests/Rules/UseTripleSlashForDocumentationCommentsTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseTripleSlashForDocumentationCommentsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseTripleSlashForDocumentationCommentsTests: LintOrFormatRuleTestCase { func testRemoveDocBlockComments() { @@ -37,7 +36,7 @@ final class UseTripleSlashForDocumentationCommentsTests: LintOrFormatRuleTestCas ] ) } - + func testRemoveDocBlockCommentsWithoutStars() { assertFormatting( UseTripleSlashForDocumentationComments.self, diff --git a/Tests/SwiftFormatTests/Rules/UseWhereClausesInForLoopsTests.swift b/Tests/SwiftFormatTests/Rules/UseWhereClausesInForLoopsTests.swift index c4660673d..1110e63ca 100644 --- a/Tests/SwiftFormatTests/Rules/UseWhereClausesInForLoopsTests.swift +++ b/Tests/SwiftFormatTests/Rules/UseWhereClausesInForLoopsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport final class UseWhereClausesInForLoopsTests: LintOrFormatRuleTestCase { func testForLoopWhereClauses() { diff --git a/Tests/SwiftFormatTests/Rules/ValidateDocumentationCommentsTests.swift b/Tests/SwiftFormatTests/Rules/ValidateDocumentationCommentsTests.swift index 2b1fcbeb2..38e41c1d3 100644 --- a/Tests/SwiftFormatTests/Rules/ValidateDocumentationCommentsTests.swift +++ b/Tests/SwiftFormatTests/Rules/ValidateDocumentationCommentsTests.swift @@ -1,6 +1,5 @@ -import _SwiftFormatTestSupport - @_spi(Rules) import SwiftFormat +import _SwiftFormatTestSupport // FIXME: Diagnostics should be emitted inside the comment, not at the beginning of the declaration. final class ValidateDocumentationCommentsTests: LintOrFormatRuleTestCase { @@ -26,8 +25,15 @@ final class ValidateDocumentationCommentsTests: LintOrFormatRuleTestCase { 2️⃣func testInvalidParameterDesc(command: String, stdin: String) -> String {} """, findings: [ - FindingSpec("1️⃣", message: "replace the plural 'Parameters:' section with a singular inline 'Parameter' section"), - FindingSpec("2️⃣", message: "replace the singular inline 'Parameter' section with a plural 'Parameters:' section that has the parameters nested inside it"), + FindingSpec( + "1️⃣", + message: "replace the plural 'Parameters:' section with a singular inline 'Parameter' section" + ), + FindingSpec( + "2️⃣", + message: + "replace the singular inline 'Parameter' section with a plural 'Parameters:' section that has the parameters nested inside it" + ), ] ) } @@ -216,7 +222,10 @@ final class ValidateDocumentationCommentsTests: LintOrFormatRuleTestCase { } """, findings: [ - FindingSpec("1️⃣", message: "change the parameters of the documentation of 'incorrectParam' to match its parameters"), + FindingSpec( + "1️⃣", + message: "change the parameters of the documentation of 'incorrectParam' to match its parameters" + ) ] ) } diff --git a/Tests/SwiftFormatTests/Utilities/FileIteratorTests.swift b/Tests/SwiftFormatTests/Utilities/FileIteratorTests.swift index 2f556e629..965c90fe3 100644 --- a/Tests/SwiftFormatTests/Utilities/FileIteratorTests.swift +++ b/Tests/SwiftFormatTests/Utilities/FileIteratorTests.swift @@ -1,6 +1,5 @@ -import XCTest - @_spi(Internal) import SwiftFormat +import XCTest final class FileIteratorTests: XCTestCase { private var tmpdir: URL! @@ -10,7 +9,8 @@ final class FileIteratorTests: XCTestCase { for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: FileManager.default.temporaryDirectory, - create: true) + create: true + ) // Create a simple file tree used by the tests below. try touch("project/real1.swift") @@ -43,7 +43,8 @@ final class FileIteratorTests: XCTestCase { func testTraversesHiddenFilesIfExplicitlySpecified() { let seen = allFilesSeen( iteratingOver: [tmpURL("project/.build"), tmpURL("project/.hidden.swift")], - followSymlinks: false) + followSymlinks: false + ) XCTAssertEqual(seen.count, 2) XCTAssertTrue(seen.contains { $0.hasSuffix("project/.build/generated.swift") }) XCTAssertTrue(seen.contains { $0.hasSuffix("project/.hidden.swift") }) @@ -69,7 +70,9 @@ extension FileIteratorTests { private func touch(_ path: String) throws { let fileURL = tmpURL(path) try FileManager.default.createDirectory( - at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true) + at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) struct FailedToCreateFileError: Error { let url: URL } @@ -81,7 +84,9 @@ extension FileIteratorTests { /// Create a symlink between files or directories in the test's temporary space. private func symlink(_ source: String, to target: String) throws { try FileManager.default.createSymbolicLink( - at: tmpURL(source), withDestinationURL: tmpURL(target)) + at: tmpURL(source), + withDestinationURL: tmpURL(target) + ) } /// Computes the list of all files seen by using `FileIterator` to iterate over the given URLs. From 40d3f3e9c106335eecf1904be2a59f17dba54a73 Mon Sep 17 00:00:00 2001 From: Tony Allevato Date: Tue, 1 Oct 2024 08:29:04 -0400 Subject: [PATCH 3/3] Re-enable format check (the default behavior). --- .github/workflows/pull_request.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index b95dcd4fa..d49113a87 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -12,6 +12,5 @@ jobs: name: Soundness uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main with: - format_check_enabled: false license_header_check_enabled: false license_header_check_project_name: "Swift.org"