From aea4ba665040ec19f548ce985db545638ef929e1 Mon Sep 17 00:00:00 2001 From: Natik Gadzhi Date: Fri, 8 Sep 2023 11:16:22 -0700 Subject: [PATCH] Formatting: omit explicit returns where possible This commit sets up `.swift-format` rule to omit returns. --- .swift-format | 1 + .../Sources/SyntaxSupport/Child.swift | 4 +- .../Sources/SyntaxSupport/Node.swift | 8 +- .../SyntaxSupport/SyntaxNodeKind.swift | 6 +- .../Sources/SyntaxSupport/TokenSpec.swift | 6 +- .../Sources/Utils/CodeGenerationFormat.swift | 2 +- .../Sources/Utils/SyntaxBuildableChild.swift | 2 +- .../Sources/Utils/SyntaxBuildableType.swift | 4 +- CodeGeneration/Sources/Utils/Utils.swift | 4 +- .../GenerateSwiftSyntax.swift | 4 +- .../templates/Array+Child.swift | 2 +- .../swiftsyntax/RawSyntaxNodesFile.swift | 2 +- .../swiftsyntax/TriviaPiecesFile.swift | 2 +- .../ValidateSyntaxNodes.swift | 2 +- .../CommandDiscovery.swift | 6 +- .../SourceEditorExtension.swift | 2 +- Examples/Sources/ExamplePlugin/Macros.swift | 2 +- .../Implementation/CodableKey.swift | 2 +- .../Implementation/OptionSetMacro.swift | 2 +- .../WrapStoredPropertiesMacro.swift | 2 +- .../MacroExamples/Playground/main.swift | 2 +- Sources/SwiftBasicFormat/BasicFormat.swift | 14 +-- .../SyntaxProtocol+Formatted.swift | 2 +- .../CompilerPluginMessageHandler.swift | 2 +- Sources/SwiftDiagnostics/Convenience.swift | 2 +- Sources/SwiftDiagnostics/Diagnostic.swift | 6 +- .../DiagnosticsFormatter.swift | 6 +- .../SwiftDiagnostics/GroupedDiagnostics.swift | 2 +- Sources/SwiftDiagnostics/Note.swift | 4 +- .../SwiftIDEUtilsCompatibility.swift | 12 +- .../Syntax+Classifications.swift | 2 +- Sources/SwiftIDEUtils/SyntaxClassifier.swift | 6 +- .../OperatorTable+Folding.swift | 2 +- .../OperatorTable+Semantics.swift | 8 +- Sources/SwiftOperators/OperatorTable.swift | 6 +- Sources/SwiftOperators/PrecedenceGraph.swift | 2 +- Sources/SwiftOperators/PrecedenceGroup.swift | 4 +- Sources/SwiftParser/Attributes.swift | 34 +++--- Sources/SwiftParser/CharacterInfo.swift | 2 +- .../CollectionNodes+Parsable.swift | 18 +-- Sources/SwiftParser/Declarations.swift | 2 +- Sources/SwiftParser/Expressions.swift | 2 +- .../IncrementalParseTransition.swift | 8 +- Sources/SwiftParser/Lexer/Cursor.swift | 10 +- Sources/SwiftParser/Lexer/Lexeme.swift | 6 +- .../SwiftParser/Lexer/LexemeSequence.swift | 4 +- .../Lexer/UnicodeScalarExtensions.swift | 4 +- Sources/SwiftParser/Lookahead.swift | 12 +- .../SwiftParser/LoopProgressCondition.swift | 4 +- Sources/SwiftParser/Names.swift | 4 +- Sources/SwiftParser/Nominals.swift | 10 +- Sources/SwiftParser/Parser.swift | 12 +- Sources/SwiftParser/Recovery.swift | 8 +- Sources/SwiftParser/Specifiers.swift | 10 +- .../SwiftParserCompatibility.swift | 4 +- Sources/SwiftParser/SyntaxUtils.swift | 6 +- Sources/SwiftParser/TokenConsumer.swift | 8 +- Sources/SwiftParser/TokenPrecedence.swift | 2 +- Sources/SwiftParser/TokenSpec.swift | 10 +- Sources/SwiftParser/TokenSpecSet.swift | 6 +- Sources/SwiftParser/TopLevel.swift | 2 +- Sources/SwiftParser/Types.swift | 4 +- .../DiagnosticExtensions.swift | 4 +- .../LexerDiagnosticMessages.swift | 8 +- .../MissingNodesError.swift | 8 +- .../ParseDiagnosticsGenerator.swift | 18 +-- .../ParserDiagnosticMessages.swift | 52 ++++----- .../SyntaxExtensions.swift | 8 +- .../CallToTrailingClosures.swift | 2 +- .../ExpandEditorPlaceholder.swift | 6 +- .../SwiftRefactor/RefactoringProvider.swift | 14 +-- Sources/SwiftSyntax/AbsolutePosition.swift | 4 +- Sources/SwiftSyntax/AbsoluteSyntaxInfo.swift | 10 +- Sources/SwiftSyntax/BumpPtrAllocator.swift | 2 +- Sources/SwiftSyntax/Raw/RawSyntax.swift | 4 +- .../SwiftSyntax/Raw/RawSyntaxLayoutView.swift | 4 +- .../Raw/RawSyntaxNodeProtocol.swift | 22 ++-- .../SwiftSyntax/Raw/RawSyntaxTokenView.swift | 8 +- Sources/SwiftSyntax/SourceLength.swift | 2 +- Sources/SwiftSyntax/SourceLocation.swift | 16 +-- .../SwiftSyntaxCompatibility.swift | 74 ++++++------- Sources/SwiftSyntax/Syntax.swift | 20 ++-- Sources/SwiftSyntax/SyntaxArena.swift | 12 +- Sources/SwiftSyntax/SyntaxChildren.swift | 24 ++-- Sources/SwiftSyntax/SyntaxCollection.swift | 20 ++-- Sources/SwiftSyntax/SyntaxHashable.swift | 4 +- Sources/SwiftSyntax/SyntaxIdentifier.swift | 4 +- Sources/SwiftSyntax/SyntaxProtocol.swift | 104 +++++++++--------- Sources/SwiftSyntax/SyntaxText.swift | 4 +- Sources/SwiftSyntax/TokenDiagnostic.swift | 2 +- Sources/SwiftSyntax/TokenSequence.swift | 12 +- Sources/SwiftSyntax/TokenSyntax.swift | 30 ++--- Sources/SwiftSyntax/Trivia.swift | 14 +-- Sources/SwiftSyntax/Utils.swift | 20 ++-- .../ConvenienceInitializers.swift | 2 +- Sources/SwiftSyntaxBuilder/Indenter.swift | 4 +- .../ResultBuilderExtensions.swift | 16 +-- .../Syntax+StringInterpolation.swift | 2 +- .../IndentationUtils.swift | 2 +- .../MacroReplacement.swift | 2 +- .../MacroSystem.swift | 46 ++++---- .../MacroExpansionContext.swift | 2 +- .../MacroProtocols/Macro+Format.swift | 2 +- .../MacroProtocols/MemberMacro.swift | 4 +- .../String+TrimmingTrailingWhitespace.swift | 2 +- .../SyntaxProtocol+Initializer.swift | 2 +- Sources/swift-parser-cli/ParseCommand.swift | 2 +- Sources/swift-parser-cli/TerminalUtils.swift | 4 +- .../commands/Build.swift | 2 +- .../commands/GenerateSourceCode.swift | 2 +- .../commands/Test.swift | 4 +- .../commands/VerifySourceCode.swift | 2 +- .../common/BuildCommand.swift | 2 +- .../swift-syntax-dev-utils/common/Paths.swift | 10 +- .../ParsingPerformanceTests.swift | 2 +- .../SyntaxClassifierPerformanceTests.swift | 2 +- .../VisitorPerformanceTests.swift | 2 +- .../OperatorTableTests.swift | 2 +- Tests/SwiftParserTest/Assertions.swift | 4 +- Tests/SwiftParserTest/LinkageTests.swift | 16 +-- .../SwiftParserTest/ThenStatementTests.swift | 2 +- .../AccessorMacroTests.swift | 2 +- .../MemberAttributeMacroTests.swift | 4 +- .../MemberMacroTests.swift | 4 +- .../MultiRoleMacroTests.swift | 8 +- .../PeerMacroTests.swift | 2 +- .../DebugDescriptionTests.swift | 2 +- Tests/SwiftSyntaxTest/RawSyntaxTests.swift | 2 +- .../SwiftSyntaxTest/SyntaxVisitorTests.swift | 4 +- .../SyntaxComparisonTests.swift | 2 +- 130 files changed, 525 insertions(+), 524 deletions(-) diff --git a/.swift-format b/.swift-format index 6c125bef6ee..9e7a97499de 100644 --- a/.swift-format +++ b/.swift-format @@ -10,6 +10,7 @@ "AlwaysUseLowerCamelCase": false, "AmbiguousTrailingClosureOverload": false, "NoBlockComments": false, + "OmitExplicitReturns": true, "OrderedImports": true, "UseLetInEveryBoundCaseVariable": false, "UseSynthesizedInitializer": false diff --git a/CodeGeneration/Sources/SyntaxSupport/Child.swift b/CodeGeneration/Sources/SyntaxSupport/Child.swift index c9a4eef565c..49bd2c943ea 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Child.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Child.swift @@ -108,7 +108,7 @@ public class Child { /// A name of this child that's suitable to be used for variable or enum case names. public var varOrCaseName: TokenSyntax { - return .identifier(lowercaseFirstWord(name: name)) + .identifier(lowercaseFirstWord(name: name)) } /// If this child has node choices, the type that the nested `SyntaxChildChoices` type should get. @@ -137,7 +137,7 @@ public class Child { /// Determines if this child has a deprecated name public var hasDeprecatedName: Bool { - return deprecatedName != nil + deprecatedName != nil } /// If the child ends with "token" in the kind, it's considered a token node. diff --git a/CodeGeneration/Sources/SyntaxSupport/Node.swift b/CodeGeneration/Sources/SyntaxSupport/Node.swift index 36bd7830db6..ff4f57e2989 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Node.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Node.swift @@ -60,7 +60,7 @@ public class Node { /// A name for this node that is suitable to be used as a variables or enum /// case's name. public var varOrCaseName: TokenSyntax { - return kind.varOrCaseName + kind.varOrCaseName } /// If this is a layout node, return a view of the node that provides access @@ -264,7 +264,7 @@ public struct LayoutNode { /// Allow transparent accesss to the properties of the underlying `Node`. public subscript(dynamicMember keyPath: KeyPath) -> T { - return node[keyPath: keyPath] + node[keyPath: keyPath] } /// The children of the layout node. @@ -281,7 +281,7 @@ public struct LayoutNode { /// All children in the node that are not unexpected. public var nonUnexpectedChildren: [Child] { - return children.filter { !$0.isUnexpectedNodes } + children.filter { !$0.isUnexpectedNodes } } /// Traits that the node conforms to. @@ -328,7 +328,7 @@ public struct CollectionNode { /// Allow transparent access to the properties of the underlying `Node`. public subscript(dynamicMember keyPath: KeyPath) -> T { - return node[keyPath: keyPath] + node[keyPath: keyPath] } /// The kinds the elements can have. diff --git a/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift b/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift index d8e35377a5f..441b5460db1 100644 --- a/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift +++ b/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift @@ -333,7 +333,7 @@ public enum SyntaxNodeKind: String, CaseIterable { /// A name for this node that is suitable to be used as a variables or enum /// case's name. public var varOrCaseName: TokenSyntax { - return .identifier(rawValue) + .identifier(rawValue) } /// The type name of this node in the SwiftSyntax module. @@ -351,12 +351,12 @@ public enum SyntaxNodeKind: String, CaseIterable { /// For base nodes, the name of the corresponding protocol to which all the /// concrete nodes that have this base kind, conform. public var protocolType: TypeSyntax { - return "\(syntaxType)Protocol" + "\(syntaxType)Protocol" } /// The name of this node at the `RawSyntax` level. public var rawType: TypeSyntax { - return "Raw\(syntaxType)" + "Raw\(syntaxType)" } /// For base nodes, the name of the corresponding raw protocol to which all the diff --git a/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift b/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift index 2667854a716..5df4e9ee05d 100644 --- a/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift +++ b/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift @@ -75,7 +75,7 @@ public struct TokenSpec { /// - name: A name of the token. /// - text: An actual text of the punctuation token. static func punctuator(name: String, text: String) -> TokenSpec { - return TokenSpec( + TokenSpec( name: name, nameForDiagnostics: text, text: text, @@ -89,7 +89,7 @@ public struct TokenSpec { /// - name: A name of the token. /// - text: An actual text of the pound keyword token. static func poundKeyword(name: String, text: String) -> TokenSpec { - return TokenSpec( + TokenSpec( name: name, nameForDiagnostics: text, text: text, @@ -104,7 +104,7 @@ public struct TokenSpec { /// - nameForDiagnostics: A name of the token that can be shown in diagnostics. /// - text: An actual text of the token, if available. static func other(name: String, nameForDiagnostics: String, text: String? = nil) -> TokenSpec { - return TokenSpec( + TokenSpec( name: name, nameForDiagnostics: nameForDiagnostics, text: text, diff --git a/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift b/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift index 36b5d970264..1a4bec8c61c 100644 --- a/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift +++ b/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift @@ -99,7 +99,7 @@ public class CodeGenerationFormat: BasicFormat { private func shouldBeSeparatedByTwoNewlines(node: CodeBlockItemSyntax) -> Bool { // First item in the ``CodeBlockItemListSyntax`` don't need a newline or indentation if the parent is a ``SourceFileSyntax``. // We want to group imports so newline between them should be omitted - return node.parent?.as(CodeBlockItemListSyntax.self)?.first == node || node.item.is(ImportDeclSyntax.self) + node.parent?.as(CodeBlockItemListSyntax.self)?.first == node || node.item.is(ImportDeclSyntax.self) } private func ensuringTwoLeadingNewlines(node: NodeType) -> NodeType { diff --git a/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift b/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift index 6899dd5785f..32277b50390 100644 --- a/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift +++ b/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift @@ -54,7 +54,7 @@ public extension Child { } var parameterType: TypeSyntax { - return self.buildableType.optionalWrapped(type: parameterBaseType) + self.buildableType.optionalWrapped(type: parameterBaseType) } var defaultValue: ExprSyntax? { diff --git a/CodeGeneration/Sources/Utils/SyntaxBuildableType.swift b/CodeGeneration/Sources/Utils/SyntaxBuildableType.swift index 8b138ab9874..a6e69776b41 100644 --- a/CodeGeneration/Sources/Utils/SyntaxBuildableType.swift +++ b/CodeGeneration/Sources/Utils/SyntaxBuildableType.swift @@ -133,7 +133,7 @@ public struct SyntaxBuildableType: Hashable { /// which will eventually get built from `SwiftSyntaxBuilder`. If the type /// is optional, this terminates with a `?`. public var syntax: TypeSyntax { - return optionalWrapped(type: syntaxBaseName) + optionalWrapped(type: syntaxBaseName) } /// The type that is used for parameters in SwiftSyntaxBuilder that take this @@ -147,7 +147,7 @@ public struct SyntaxBuildableType: Hashable { } public var parameterType: TypeSyntax { - return optionalWrapped(type: parameterBaseType) + optionalWrapped(type: parameterBaseType) } /// Assuming that this is a collection type, the non-optional type of the result builder diff --git a/CodeGeneration/Sources/Utils/Utils.swift b/CodeGeneration/Sources/Utils/Utils.swift index a9f2fdf7853..58e077cc334 100644 --- a/CodeGeneration/Sources/Utils/Utils.swift +++ b/CodeGeneration/Sources/Utils/Utils.swift @@ -21,8 +21,8 @@ extension String { /// Removes all empty lines from a multi-line string. public var removingEmptyLines: String { - return - self + + self .split(whereSeparator: \.isNewline) .filter { !$0.allSatisfy(\.isWhitespace) } .joined(separator: "\n") diff --git a/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift b/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift index 3384273d1c1..5204a258767 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift @@ -39,7 +39,7 @@ struct GeneratedFileSpec { let pathComponents: [String] private let contentsGenerator: () -> String var contents: String { - return self.contentsGenerator() + self.contentsGenerator() } init(_ pathComponents: [String], _ contents: @escaping @autoclosure () -> String) { @@ -55,7 +55,7 @@ struct GeneratedFileSpec { struct TemplateSpec { let sourceFileGenerator: () -> SourceFileSyntax var sourceFile: SourceFileSyntax { - return self.sourceFileGenerator() + self.sourceFileGenerator() } let module: String let filename: String diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/Array+Child.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/Array+Child.swift index 3f13cf3f33c..285bba54b34 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/Array+Child.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/Array+Child.swift @@ -14,6 +14,6 @@ import SyntaxSupport extension Array where Element == Child { var hasDeprecatedChild: Bool { - return self.contains(where: { $0.hasDeprecatedName }) + self.contains(where: { $0.hasDeprecatedName }) } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift index a374e56fbc8..c9372a84502 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift @@ -39,7 +39,7 @@ fileprivate extension Node { } func rawSyntaxNodesFile(nodesStartingWith: [Character]) -> SourceFileSyntax { - return SourceFileSyntax { + SourceFileSyntax { for node in SYNTAX_NODES where node.kind.isBase && nodesStartingWith.contains(node.kind.syntaxType.description.first!) { DeclSyntax( """ diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TriviaPiecesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TriviaPiecesFile.swift index 6b1c97f8aa7..f54397450e6 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TriviaPiecesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TriviaPiecesFile.swift @@ -271,7 +271,7 @@ let triviaPiecesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { } fileprivate func generateIsHelpers(for pieceName: TokenSyntax) throws -> ExtensionDeclSyntax { - return try ExtensionDeclSyntax("extension \(pieceName)") { + try ExtensionDeclSyntax("extension \(pieceName)") { DeclSyntax( """ /// Returns `true` if this piece is a newline, space or tab. diff --git a/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift b/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift index 179c4a30e77..0435237f72b 100644 --- a/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift +++ b/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift @@ -80,7 +80,7 @@ fileprivate extension ChildKind { fileprivate extension Child { func hasSameType(as other: Child) -> Bool { - return varOrCaseName.description == other.varOrCaseName.description && kind.hasSameType(as: other.kind) && isOptional == other.isOptional + varOrCaseName.description == other.varOrCaseName.description && kind.hasSameType(as: other.kind) && isOptional == other.isOptional } func isFollowedByColonToken(in node: LayoutNode) -> Bool { diff --git a/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift b/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift index ab7095fbdfb..0efe33fbd2a 100644 --- a/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift +++ b/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift @@ -82,7 +82,7 @@ struct Context: Hashable { var rawValue: UInt32 var kind: Context.Kind? { - return Context.Kind(rawValue: UInt8(self.rawValue & 0x1F)) + Context.Kind(rawValue: UInt8(self.rawValue & 0x1F)) } } @@ -156,7 +156,7 @@ struct ModuleContext { extension ModuleContext { var isSwiftRefactorModule: Bool { - return self.name == "SwiftRefactor" + self.name == "SwiftRefactor" } } @@ -164,7 +164,7 @@ struct RelativeDirectPointer { var offset: Int32 func address(from pointer: UnsafeRawPointer) -> UnsafeRawPointer { - return pointer + UnsafeRawPointer.Stride(self.offset) + pointer + UnsafeRawPointer.Stride(self.offset) } } diff --git a/EditorExtension/SwiftRefactorExtension/SourceEditorExtension.swift b/EditorExtension/SwiftRefactorExtension/SourceEditorExtension.swift index a96467ce7ce..f4aad988748 100644 --- a/EditorExtension/SwiftRefactorExtension/SourceEditorExtension.swift +++ b/EditorExtension/SwiftRefactorExtension/SourceEditorExtension.swift @@ -22,7 +22,7 @@ final class SourceEditorExtension: NSObject, XCSourceEditorExtension { } var commandDefinitions: [[XCSourceEditorCommandDefinitionKey: Any]] { - return RefactoringRegistry.shared.providers.map { provider in + RefactoringRegistry.shared.providers.map { provider in return [ .classNameKey: SourceEditorCommand.className(), .identifierKey: String(describing: provider), diff --git a/Examples/Sources/ExamplePlugin/Macros.swift b/Examples/Sources/ExamplePlugin/Macros.swift index 35e9b6baaff..f0d3dfd5c79 100644 --- a/Examples/Sources/ExamplePlugin/Macros.swift +++ b/Examples/Sources/ExamplePlugin/Macros.swift @@ -71,7 +71,7 @@ struct MemberDeprecatedMacro: MemberAttributeMacro { providingAttributesFor member: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext ) throws -> [SwiftSyntax.AttributeSyntax] { - return ["@available(*, deprecated)"] + ["@available(*, deprecated)"] } } diff --git a/Examples/Sources/MacroExamples/Implementation/CodableKey.swift b/Examples/Sources/MacroExamples/Implementation/CodableKey.swift index e29397f268d..c56ae98267e 100644 --- a/Examples/Sources/MacroExamples/Implementation/CodableKey.swift +++ b/Examples/Sources/MacroExamples/Implementation/CodableKey.swift @@ -20,6 +20,6 @@ public struct CodableKey: PeerMacro { in context: some MacroExpansionContext ) throws -> [DeclSyntax] { // Does nothing, used only to decorate members with data - return [] + [] } } diff --git a/Examples/Sources/MacroExamples/Implementation/OptionSetMacro.swift b/Examples/Sources/MacroExamples/Implementation/OptionSetMacro.swift index 5d2e0c866ad..b7b27ab8057 100644 --- a/Examples/Sources/MacroExamples/Implementation/OptionSetMacro.swift +++ b/Examples/Sources/MacroExamples/Implementation/OptionSetMacro.swift @@ -61,7 +61,7 @@ private let defaultOptionsEnumName = "Options" extension LabeledExprListSyntax { /// Retrieve the first element with the given label. func first(labeled name: String) -> Element? { - return first { element in + first { element in if let label = element.label, label.text == name { return true } diff --git a/Examples/Sources/MacroExamples/Implementation/WrapStoredPropertiesMacro.swift b/Examples/Sources/MacroExamples/Implementation/WrapStoredPropertiesMacro.swift index d885331400f..9ff7fce913d 100644 --- a/Examples/Sources/MacroExamples/Implementation/WrapStoredPropertiesMacro.swift +++ b/Examples/Sources/MacroExamples/Implementation/WrapStoredPropertiesMacro.swift @@ -97,7 +97,7 @@ extension DeclGroupSyntax { /// Enumerate the stored properties that syntactically occur in this /// declaration. func storedProperties() -> [VariableDeclSyntax] { - return memberBlock.members.compactMap { member in + memberBlock.members.compactMap { member in guard let variable = member.decl.as(VariableDeclSyntax.self), variable.isStoredProperty else { diff --git a/Examples/Sources/MacroExamples/Playground/main.swift b/Examples/Sources/MacroExamples/Playground/main.swift index 6df22c096d6..a766953ded7 100644 --- a/Examples/Sources/MacroExamples/Playground/main.swift +++ b/Examples/Sources/MacroExamples/Playground/main.swift @@ -134,7 +134,7 @@ print("password: description=\(password) hashValue=\(password.hashValue)") struct MyStruct { @AddCompletionHandler func f(a: Int, for b: String, _ value: Double) async -> String { - return b + b } @AddAsync diff --git a/Sources/SwiftBasicFormat/BasicFormat.swift b/Sources/SwiftBasicFormat/BasicFormat.swift index a433d133b52..42119c11c20 100644 --- a/Sources/SwiftBasicFormat/BasicFormat.swift +++ b/Sources/SwiftBasicFormat/BasicFormat.swift @@ -34,7 +34,7 @@ open class BasicFormat: SyntaxRewriter { /// The trivia by which tokens should currently be indented. public var currentIndentationLevel: Trivia { // `decreaseIndentationLevel` guarantees that there is always one item on the stack. - return indentationStack.last!.indentation + indentationStack.last!.indentation } /// For every token that is being put on a new line but did not have @@ -53,7 +53,7 @@ open class BasicFormat: SyntaxRewriter { /// Whether we are currently visiting the subtree of a `StringLiteralExprSyntax`. private var isInsideStringLiteral: Bool { - return stringLiteralNestingLevel > 0 + stringLiteralNestingLevel > 0 } public init( @@ -90,7 +90,7 @@ open class BasicFormat: SyntaxRewriter { open override func visit(_ node: UnexpectedNodesSyntax) -> UnexpectedNodesSyntax { // Do not perform any formatting on unexpected nodes, the result won't make any // sense as we rely on layout nodes to know what formatting to perform. - return node + node } open override func visitPre(_ node: Syntax) { @@ -123,7 +123,7 @@ open class BasicFormat: SyntaxRewriter { // MARK: - Helper functions private func isInsideStringInterpolation(_ token: TokenSyntax) -> Bool { - return token.ancestorOrSelf { $0.as(ExpressionSegmentSyntax.self) } != nil + token.ancestorOrSelf { $0.as(ExpressionSegmentSyntax.self) } != nil } private func childrenSeparatedByNewline(_ node: Syntax) -> Bool { @@ -383,7 +383,7 @@ open class BasicFormat: SyntaxRewriter { /// will be mutated. Thus, if two tokens need to be separated by a space, it /// will not be assumed that the space is added to an immutable previous node. open func isMutable(_ token: TokenSyntax) -> Bool { - return true + true } /// Change the text of a token during formatting. @@ -393,7 +393,7 @@ open class BasicFormat: SyntaxRewriter { /// - Parameter token: The token whose text should be changed /// - Returns: The new text or `nil` if the text should not be changed open func transformTokenText(_ token: TokenSyntax) -> String? { - return nil + nil } /// Change the presence of a token during formatting. @@ -403,7 +403,7 @@ open class BasicFormat: SyntaxRewriter { /// - Parameter token: The token whose presence should be changed /// - Returns: The new presence or `nil` if the presence should not be changed open func transformTokenPresence(_ token: TokenSyntax) -> SourcePresence? { - return nil + nil } // MARK: - Formatting a token diff --git a/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift b/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift index c44671e727f..0193e7c3d0f 100644 --- a/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift +++ b/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift @@ -3,6 +3,6 @@ import SwiftSyntax public extension SyntaxProtocol { /// Build a syntax node from this `Buildable` and format it with the given format. func formatted(using format: BasicFormat = BasicFormat()) -> Syntax { - return format.rewrite(self) + format.rewrite(self) } } diff --git a/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift b/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift index a7bca3ebf53..d8c66fe18e9 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift @@ -172,7 +172,7 @@ struct UnimplementedError: Error, CustomStringConvertible { public extension PluginProvider { var features: [PluginFeature] { // No optional features by default. - return [] + [] } func loadPluginLibrary(libraryPath: String, moduleName: String) throws { diff --git a/Sources/SwiftDiagnostics/Convenience.swift b/Sources/SwiftDiagnostics/Convenience.swift index ea42df6b6ba..5f9222c976d 100644 --- a/Sources/SwiftDiagnostics/Convenience.swift +++ b/Sources/SwiftDiagnostics/Convenience.swift @@ -40,7 +40,7 @@ extension FixIt { oldNode: some SyntaxProtocol, newNode: some SyntaxProtocol ) -> Self { - return FixIt( + FixIt( message: message, changes: [ .replace(oldNode: Syntax(oldNode), newNode: Syntax(newNode)) diff --git a/Sources/SwiftDiagnostics/Diagnostic.swift b/Sources/SwiftDiagnostics/Diagnostic.swift index 939bfea6d57..6f8e07738ab 100644 --- a/Sources/SwiftDiagnostics/Diagnostic.swift +++ b/Sources/SwiftDiagnostics/Diagnostic.swift @@ -53,18 +53,18 @@ public struct Diagnostic: CustomDebugStringConvertible { /// The message that should be displayed to the user. public var message: String { - return diagMessage.message + diagMessage.message } /// An ID that identifies the diagnostic's message. /// See ``MessageID``. public var diagnosticID: MessageID { - return diagMessage.diagnosticID + diagMessage.diagnosticID } /// The location at which the diagnostic should be displayed. public func location(converter: SourceLocationConverter) -> SourceLocation { - return converter.location(for: position) + converter.location(for: position) } public var debugDescription: String { diff --git a/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift b/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift index f55c9b42411..cbb38698b12 100644 --- a/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift +++ b/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift @@ -66,7 +66,7 @@ public struct DiagnosticsFormatter { /// Whether this line is free of annotations. var isFreeOfAnnotations: Bool { - return diagnostics.isEmpty && suffixText.isEmpty + diagnostics.isEmpty && suffixText.isEmpty } } @@ -305,7 +305,7 @@ public struct DiagnosticsFormatter { tree: some SyntaxProtocol, diags: [Diagnostic] ) -> String { - return annotatedSource( + annotatedSource( tree: tree, diags: diags, indentString: "", @@ -401,7 +401,7 @@ struct ANSIAnnotation { } func withTrait(_ trait: Trait) -> Self { - return ANSIAnnotation(color: self.color, trait: trait) + ANSIAnnotation(color: self.color, trait: trait) } func applied(to message: String, resetAfter: Bool = true) -> String { diff --git a/Sources/SwiftDiagnostics/GroupedDiagnostics.swift b/Sources/SwiftDiagnostics/GroupedDiagnostics.swift index f0581d2e967..049acf11f06 100644 --- a/Sources/SwiftDiagnostics/GroupedDiagnostics.swift +++ b/Sources/SwiftDiagnostics/GroupedDiagnostics.swift @@ -258,7 +258,7 @@ extension GroupedDiagnostics { extension DiagnosticsFormatter { /// Annotate all of the source files in the given set of grouped diagnostics. public func annotateSources(in group: GroupedDiagnostics) -> String { - return group.rootSourceFiles.map { rootSourceFileID in + group.rootSourceFiles.map { rootSourceFileID in group.annotateSource(rootSourceFileID, formatter: self, indentString: "") }.joined(separator: "\n") } diff --git a/Sources/SwiftDiagnostics/Note.swift b/Sources/SwiftDiagnostics/Note.swift index fecbe1a056a..2a5621f675f 100644 --- a/Sources/SwiftDiagnostics/Note.swift +++ b/Sources/SwiftDiagnostics/Note.swift @@ -47,12 +47,12 @@ public struct Note: CustomDebugStringConvertible { /// The message that should be displayed to the user. public var message: String { - return noteMessage.message + noteMessage.message } /// The location at which the note should be displayed. public func location(converter: SourceLocationConverter) -> SourceLocation { - return converter.location(for: position) + converter.location(for: position) } public var debugDescription: String { diff --git a/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift b/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift index 90a3bcf7fd7..693aa62892f 100644 --- a/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift +++ b/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift @@ -17,32 +17,32 @@ public extension SyntaxClassification { /// A `#` keyword like `#warning`. @available(*, deprecated, renamed: "ifConfigDirective") static var poundDirective: SyntaxClassification { - return .ifConfigDirective + .ifConfigDirective } @available(*, deprecated, renamed: "ifConfigDirective") static var buildConfigId: SyntaxClassification { - return .ifConfigDirective + .ifConfigDirective } @available(*, deprecated, message: "String interpolation anchors are now classified as .none") static var stringInterpolationAnchor: SyntaxClassification { - return .none + .none } @available(*, deprecated, renamed: "type") static var typeIdentifier: SyntaxClassification { - return .type + .type } @available(*, deprecated, renamed: "operator") static var operatorIdentifier: SyntaxClassification { - return .operator + .operator } @available(*, deprecated, renamed: "floatLiteral") static var floatingLiteral: SyntaxClassification { - return .floatLiteral + .floatLiteral } } diff --git a/Sources/SwiftIDEUtils/Syntax+Classifications.swift b/Sources/SwiftIDEUtils/Syntax+Classifications.swift index c6793b44c1d..862f37d5f26 100644 --- a/Sources/SwiftIDEUtils/Syntax+Classifications.swift +++ b/Sources/SwiftIDEUtils/Syntax+Classifications.swift @@ -40,7 +40,7 @@ public extension SyntaxProtocol { /// - in: The relative byte range to pull ``SyntaxClassifiedRange``s from. /// - Returns: Sequence of ``SyntaxClassifiedRange``s. func classifications(in range: ByteSourceRange) -> SyntaxClassifications { - return SyntaxClassifications(_syntaxNode, in: range) + SyntaxClassifications(_syntaxNode, in: range) } /// The ``SyntaxClassifiedRange`` for a relative byte offset. diff --git a/Sources/SwiftIDEUtils/SyntaxClassifier.swift b/Sources/SwiftIDEUtils/SyntaxClassifier.swift index 3f3d5333433..0c668e66219 100644 --- a/Sources/SwiftIDEUtils/SyntaxClassifier.swift +++ b/Sources/SwiftIDEUtils/SyntaxClassifier.swift @@ -89,9 +89,9 @@ public struct SyntaxClassifiedRange: Equatable { public var kind: SyntaxClassification public var range: ByteSourceRange - public var offset: Int { return range.offset } - public var length: Int { return range.length } - public var endOffset: Int { return range.endOffset } + public var offset: Int { range.offset } + public var length: Int { range.length } + public var endOffset: Int { range.endOffset } } private struct ClassificationVisitor { diff --git a/Sources/SwiftOperators/OperatorTable+Folding.swift b/Sources/SwiftOperators/OperatorTable+Folding.swift index 2dbe7c65634..962ac051068 100644 --- a/Sources/SwiftOperators/OperatorTable+Folding.swift +++ b/Sources/SwiftOperators/OperatorTable+Folding.swift @@ -534,7 +534,7 @@ extension OperatorTable { _ node: some SyntaxProtocol, errorHandler: OperatorErrorHandler = { throw $0 } ) rethrows -> Syntax { - return try withoutActuallyEscaping(errorHandler) { errorHandler in + try withoutActuallyEscaping(errorHandler) { errorHandler in let folder = SequenceFolder( opPrecedence: self, errorHandler: errorHandler diff --git a/Sources/SwiftOperators/OperatorTable+Semantics.swift b/Sources/SwiftOperators/OperatorTable+Semantics.swift index 002721f09f9..db56c7e28b6 100644 --- a/Sources/SwiftOperators/OperatorTable+Semantics.swift +++ b/Sources/SwiftOperators/OperatorTable+Semantics.swift @@ -120,24 +120,24 @@ extension OperatorTable { override func visit( _ node: SourceFileSyntax ) -> SyntaxVisitorContinueKind { - return .visitChildren + .visitChildren } override func visit( _ node: CodeBlockItemListSyntax ) -> SyntaxVisitorContinueKind { - return .visitChildren + .visitChildren } override func visit( _ node: CodeBlockItemSyntax ) -> SyntaxVisitorContinueKind { - return .visitChildren + .visitChildren } // Everything else stops the visitation. override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind { - return .skipChildren + .skipChildren } } diff --git a/Sources/SwiftOperators/OperatorTable.swift b/Sources/SwiftOperators/OperatorTable.swift index 5ff34872e5b..6ebc30b969d 100644 --- a/Sources/SwiftOperators/OperatorTable.swift +++ b/Sources/SwiftOperators/OperatorTable.swift @@ -86,19 +86,19 @@ extension OperatorTable { /// Returns the ``Operator`` corresponding to the given infix operator, or /// `nil` if it is not defined in the operator table. public func infixOperator(named operatorName: OperatorName) -> Operator? { - return infixOperators[operatorName] + infixOperators[operatorName] } /// Returns the ``Operator`` corresponding to the given prefix operator, or /// `nil` if it is not defined in the operator table. public func prefixOperator(named operatorName: OperatorName) -> Operator? { - return prefixOperators[operatorName] + prefixOperators[operatorName] } /// Returns the ``Operator`` corresponding to the given prefix operator, or /// `nil` if it is not defined in the operator table. public func postfixOperator(named operatorName: OperatorName) -> Operator? { - return postfixOperators[operatorName] + postfixOperators[operatorName] } /// Look for the precedence group corresponding to the given operator. diff --git a/Sources/SwiftOperators/PrecedenceGraph.swift b/Sources/SwiftOperators/PrecedenceGraph.swift index d8940256d80..557301cfe28 100644 --- a/Sources/SwiftOperators/PrecedenceGraph.swift +++ b/Sources/SwiftOperators/PrecedenceGraph.swift @@ -62,7 +62,7 @@ struct PrecedenceGraph { /// Look for the precedence group with the given name, or return nil if /// no such group is known. func lookupGroup(_ groupName: PrecedenceGroupName) -> PrecedenceGroup? { - return precedenceGroups[groupName] + precedenceGroups[groupName] } /// Search the precedence-group relationships, starting at the given diff --git a/Sources/SwiftOperators/PrecedenceGroup.swift b/Sources/SwiftOperators/PrecedenceGroup.swift index be175c749d8..efde2ee1bc8 100644 --- a/Sources/SwiftOperators/PrecedenceGroup.swift +++ b/Sources/SwiftOperators/PrecedenceGroup.swift @@ -68,7 +68,7 @@ public struct PrecedenceRelation { _ groupName: PrecedenceGroupName, syntax: PrecedenceGroupNameSyntax? = nil ) -> PrecedenceRelation { - return .init(kind: .higherThan, groupName: groupName, syntax: syntax) + .init(kind: .higherThan, groupName: groupName, syntax: syntax) } /// Return a lower-than precedence relation. @@ -76,7 +76,7 @@ public struct PrecedenceRelation { _ groupName: PrecedenceGroupName, syntax: PrecedenceGroupNameSyntax? = nil ) -> PrecedenceRelation { - return .init(kind: .lowerThan, groupName: groupName, syntax: syntax) + .init(kind: .lowerThan, groupName: groupName, syntax: syntax) } } diff --git a/Sources/SwiftParser/Attributes.swift b/Sources/SwiftParser/Attributes.swift index 1f2267b9360..ecae159d0cf 100644 --- a/Sources/SwiftParser/Attributes.swift +++ b/Sources/SwiftParser/Attributes.swift @@ -216,9 +216,9 @@ extension Parser { if self.at(.poundIf) { return .ifConfigDecl( self.parsePoundIfDirective { (parser, _) -> RawAttributeListSyntax.Element in - return parser.parseAttribute() + parser.parseAttribute() } syntax: { parser, attributes in - return .attributes(RawAttributeListSyntax(elements: attributes, arena: parser.arena)) + .attributes(RawAttributeListSyntax(elements: attributes, arena: parser.arena)) } ) } @@ -226,39 +226,39 @@ extension Parser { switch DeclarationAttributeWithSpecialSyntax(lexeme: self.peek()) { case .available, ._spi_available: return parseAttribute(argumentMode: .required) { parser in - return .availability(parser.parseAvailabilityArgumentSpecList()) + .availability(parser.parseAvailabilityArgumentSpecList()) } case .backDeployed, ._backDeploy: return parseAttribute(argumentMode: .required) { parser in - return .backDeployedArguments(parser.parseBackDeployedAttributeArguments()) + .backDeployedArguments(parser.parseBackDeployedAttributeArguments()) } case .differentiable: return parseAttribute(argumentMode: .required) { parser in - return .differentiableArguments(parser.parseDifferentiableAttributeArguments()) + .differentiableArguments(parser.parseDifferentiableAttributeArguments()) } case .derivative, .transpose: return parseAttribute(argumentMode: .required) { parser in - return .derivativeRegistrationArguments(parser.parseDerivativeAttributeArguments()) + .derivativeRegistrationArguments(parser.parseDerivativeAttributeArguments()) } case .objc: return parseAttribute(argumentMode: .optional) { parser in - return .objCName(parser.parseObjectiveCSelector()) + .objCName(parser.parseObjectiveCSelector()) } case ._specialize: return parseAttribute(argumentMode: .required) { parser in - return .specializeArguments(parser.parseSpecializeAttributeArgumentList()) + .specializeArguments(parser.parseSpecializeAttributeArgumentList()) } case ._private: return parseAttribute(argumentMode: .required) { parser in - return .underscorePrivateAttributeArguments(parser.parseUnderscorePrivateAttributeArguments()) + .underscorePrivateAttributeArguments(parser.parseUnderscorePrivateAttributeArguments()) } case ._dynamicReplacement: return parseAttribute(argumentMode: .required) { parser in - return .dynamicReplacementArguments(parser.parseDynamicReplacementAttributeArguments()) + .dynamicReplacementArguments(parser.parseDynamicReplacementAttributeArguments()) } case ._documentation: return parseAttribute(argumentMode: .required) { parser in - return .documentationArguments(parser.parseDocumentationAttributeArguments()) + .documentationArguments(parser.parseDocumentationAttributeArguments()) } case ._spi, ._objcRuntimeName, ._projectedValueProperty, ._swift_native_objc_runtime_base, ._typeEraser, ._optimize, .exclusivity, .inline, ._alignment: // Attributes that take a single token as argument. Some examples of these include: @@ -294,27 +294,27 @@ extension Parser { } case ._cdecl: return parseAttribute(argumentMode: .required) { parser in - return .string(parser.parseStringLiteral()) + .string(parser.parseStringLiteral()) } case ._implements: return parseAttribute(argumentMode: .required) { parser in - return .implementsArguments(parser.parseImplementsAttributeArguments()) + .implementsArguments(parser.parseImplementsAttributeArguments()) } case ._semantics: return parseAttribute(argumentMode: .required) { parser in - return .string(parser.parseStringLiteral()) + .string(parser.parseStringLiteral()) } case ._expose: return parseAttribute(argumentMode: .required) { parser in - return .exposeAttributeArguments(parser.parseExposeArguments()) + .exposeAttributeArguments(parser.parseExposeArguments()) } case ._originallyDefinedIn: return parseAttribute(argumentMode: .required) { parser in - return .originallyDefinedInArguments(parser.parseOriginallyDefinedInAttributeArguments()) + .originallyDefinedInArguments(parser.parseOriginallyDefinedInAttributeArguments()) } case ._unavailableFromAsync: return parseAttribute(argumentMode: .optional) { parser in - return .unavailableFromAsyncArguments(parser.parseUnavailableFromAsyncAttributeArguments()) + .unavailableFromAsyncArguments(parser.parseUnavailableFromAsyncAttributeArguments()) } case .attached: return parseAttribute(argumentMode: .customAttribute) { parser in diff --git a/Sources/SwiftParser/CharacterInfo.swift b/Sources/SwiftParser/CharacterInfo.swift index 17e9d63ef54..4adabcfcb3f 100644 --- a/Sources/SwiftParser/CharacterInfo.swift +++ b/Sources/SwiftParser/CharacterInfo.swift @@ -28,7 +28,7 @@ extension Character { extension Unicode.Scalar { var isASCII: Bool { - return self.value <= 127 + self.value <= 127 } /// A Boolean value indicating whether this scalar is one which is recommended diff --git a/Sources/SwiftParser/CollectionNodes+Parsable.swift b/Sources/SwiftParser/CollectionNodes+Parsable.swift index 900607b0e12..324a20ae2b1 100644 --- a/Sources/SwiftParser/CollectionNodes+Parsable.swift +++ b/Sources/SwiftParser/CollectionNodes+Parsable.swift @@ -54,10 +54,10 @@ fileprivate extension SyntaxCollection { extension AccessorDeclListSyntax: SyntaxParseable { public static func parse(from parser: inout Parser) -> Self { - return parse(from: &parser) { parser in - return parser.parseAccessorList() ?? RawAccessorDeclListSyntax(elements: [], arena: parser.arena) + parse(from: &parser) { parser in + parser.parseAccessorList() ?? RawAccessorDeclListSyntax(elements: [], arena: parser.arena) } makeMissing: { remainingTokens, arena in - return RawAccessorDeclSyntax( + RawAccessorDeclSyntax( attributes: RawAttributeListSyntax(elements: [], arena: arena), modifier: nil, accessorSpecifier: RawTokenSyntax(missing: .keyword, text: "get", arena: arena), @@ -72,10 +72,10 @@ extension AccessorDeclListSyntax: SyntaxParseable { extension AttributeListSyntax: SyntaxParseable { public static func parse(from parser: inout Parser) -> Self { - return parse(from: &parser) { parser in - return RawSyntax(parser.parseAttributeList()) + parse(from: &parser) { parser in + RawSyntax(parser.parseAttributeList()) } makeMissing: { remainingTokens, arena in - return RawAttributeSyntax( + RawAttributeSyntax( atSign: RawTokenSyntax(missing: .atSign, arena: arena), attributeName: RawTypeSyntax(RawMissingTypeSyntax(arena: arena)), leftParen: nil, @@ -89,7 +89,7 @@ extension AttributeListSyntax: SyntaxParseable { extension CodeBlockItemListSyntax: SyntaxParseable { public static func parse(from parser: inout Parser) -> Self { - return parse(from: &parser) { parser in + parse(from: &parser) { parser in let node = parser.parseCodeBlockItemList(until: { _ in false }) return RawSyntax(node) } makeMissing: { remainingTokens, arena in @@ -101,8 +101,8 @@ extension CodeBlockItemListSyntax: SyntaxParseable { extension MemberBlockItemListSyntax: SyntaxParseable { public static func parse(from parser: inout Parser) -> Self { - return parse(from: &parser) { parser in - return RawSyntax(parser.parseMemberDeclList()) + parse(from: &parser) { parser in + RawSyntax(parser.parseMemberDeclList()) } makeMissing: { remainingTokens, arena in let missingDecl = RawMissingDeclSyntax( attributes: RawAttributeListSyntax(elements: [], arena: arena), diff --git a/Sources/SwiftParser/Declarations.swift b/Sources/SwiftParser/Declarations.swift index 89bf6f425ea..e674c865382 100644 --- a/Sources/SwiftParser/Declarations.swift +++ b/Sources/SwiftParser/Declarations.swift @@ -318,7 +318,7 @@ extension Parser { } mutating func parseImportKind() -> RawTokenSyntax? { - return self.consume(ifAnyIn: ImportDeclSyntax.ImportKindSpecifierOptions.self) + self.consume(ifAnyIn: ImportDeclSyntax.ImportKindSpecifierOptions.self) } mutating func parseImportPath() -> RawImportPathComponentListSyntax { diff --git a/Sources/SwiftParser/Expressions.swift b/Sources/SwiftParser/Expressions.swift index 318f8932330..8431dce482d 100644 --- a/Sources/SwiftParser/Expressions.swift +++ b/Sources/SwiftParser/Expressions.swift @@ -368,7 +368,7 @@ extension Parser { /// identifier or keyword on the same line. We do this to ensure that we do /// not break any copy functions defined by users. private mutating func atContextualExpressionModifier() -> Bool { - return self.peek( + self.peek( isAt: TokenSpec(.identifier, allowAtStartOfLine: false), TokenSpec(.dollarIdentifier, allowAtStartOfLine: false), TokenSpec(.self, allowAtStartOfLine: false) diff --git a/Sources/SwiftParser/IncrementalParseTransition.swift b/Sources/SwiftParser/IncrementalParseTransition.swift index 7ddb696f651..f4767f7fd27 100644 --- a/Sources/SwiftParser/IncrementalParseTransition.swift +++ b/Sources/SwiftParser/IncrementalParseTransition.swift @@ -85,11 +85,11 @@ struct IncrementalParseLookup { } fileprivate var edits: ConcurrentEdits { - return transition.edits + transition.edits } fileprivate var reusedCallback: ReusedNodeCallback? { - return transition.reusedNodeCallback + transition.reusedNodeCallback } /// Does a lookup to see if the current source `offset` should be associated @@ -382,12 +382,12 @@ public struct ConcurrentEdits { /// **Public for testing purposes only** public static func _isValidConcurrentEditArray(_ edits: [IncrementalEdit]) -> Bool { - return isValidConcurrentEditArray(edits) + isValidConcurrentEditArray(edits) } } fileprivate extension Sequence where Element: Comparable { var isSorted: Bool { - return zip(self, self.dropFirst()).allSatisfy({ $0.0 < $0.1 }) + zip(self, self.dropFirst()).allSatisfy({ $0.0 < $0.1 }) } } diff --git a/Sources/SwiftParser/Lexer/Cursor.swift b/Sources/SwiftParser/Lexer/Cursor.swift index 57deef40b1d..e3a78db3bf1 100644 --- a/Sources/SwiftParser/Lexer/Cursor.swift +++ b/Sources/SwiftParser/Lexer/Cursor.swift @@ -166,7 +166,7 @@ extension Lexer.Cursor { private var stateStack: UnsafeBufferPointer? = nil var currentState: State { - return topState ?? .normal + topState ?? .normal } mutating func perform(stateTransition: Lexer.StateTransition, stateAllocator: BumpPtrAllocator) { @@ -220,7 +220,7 @@ extension Lexer.Cursor { } func tokenDiagnostic(tokenStart: Lexer.Cursor) -> TokenDiagnostic { - return TokenDiagnostic(kind, byteOffset: tokenStart.position.distance(to: position)) + TokenDiagnostic(kind, byteOffset: tokenStart.position.distance(to: position)) } } } @@ -268,7 +268,7 @@ extension Lexer { } func starts(with possiblePrefix: some Sequence) -> Bool { - return self.input.starts(with: possiblePrefix) + self.input.starts(with: possiblePrefix) } var pointer: UnsafePointer { @@ -288,7 +288,7 @@ extension Lexer { /// Debug function to print the remaining source text to be lexed. var debugRemainingText: SyntaxText { - return SyntaxText(baseAddress: input.baseAddress, count: input.count) + SyntaxText(baseAddress: input.baseAddress, count: input.count) } } @@ -806,7 +806,7 @@ extension Lexer.Cursor { /// that case bytes are consumed until we reach the next start of a UTF-8 /// character. mutating func advanceValidatingUTF8Character() -> Unicode.Scalar? { - return Unicode.Scalar.lexing(advance: { self.advance() }, peek: { self.peek(at: 0) }) + Unicode.Scalar.lexing(advance: { self.advance() }, peek: { self.peek(at: 0) }) } } diff --git a/Sources/SwiftParser/Lexer/Lexeme.swift b/Sources/SwiftParser/Lexer/Lexeme.swift index dab116d9ec3..bce0c8fd015 100644 --- a/Sources/SwiftParser/Lexer/Lexeme.swift +++ b/Sources/SwiftParser/Lexer/Lexeme.swift @@ -65,11 +65,11 @@ extension Lexer { var cursor: Lexer.Cursor var isAtStartOfLine: Bool { - return self.flags.contains(.isAtStartOfLine) + self.flags.contains(.isAtStartOfLine) } var isEditorPlaceholder: Bool { - return self.rawTokenKind == .identifier && self.tokenText.isEditorPlaceholder + self.rawTokenKind == .identifier && self.tokenText.isEditorPlaceholder } init( @@ -132,7 +132,7 @@ extension Lexer { @_spi(Testing) public var debugDescription: String { - return String(syntaxText: SyntaxText(baseAddress: start, count: byteLength)) + String(syntaxText: SyntaxText(baseAddress: start, count: byteLength)) } } } diff --git a/Sources/SwiftParser/Lexer/LexemeSequence.swift b/Sources/SwiftParser/Lexer/LexemeSequence.swift index a82f5bf341f..3d1d9414b57 100644 --- a/Sources/SwiftParser/Lexer/LexemeSequence.swift +++ b/Sources/SwiftParser/Lexer/LexemeSequence.swift @@ -53,7 +53,7 @@ extension Lexer { @_spi(Testing) public mutating func next() -> Lexer.Lexeme? { - return self.advance() + self.advance() } /// Record the offset of the end of `nextToken` as the furthest offset in ``LookaheadTracker`` @@ -71,7 +71,7 @@ extension Lexer { /// Get the offset of the leading trivia start of `token` relative to `sourceBufferStart`. func offsetToStart(_ token: Lexer.Lexeme) -> Int { - return self.sourceBufferStart.distance(to: token.cursor) + self.sourceBufferStart.distance(to: token.cursor) } /// Advance the the cursor by `offset` and reset `currentToken` diff --git a/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift b/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift index 52774807220..301f576eeea 100644 --- a/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift +++ b/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift @@ -148,13 +148,13 @@ extension Unicode.Scalar { var isPrintableASCII: Bool { // Exclude non-printables before the space character U+20, and anything // including and above the DEL character U+7F. - return self.value >= 0x20 && self.value < 0x7F + self.value >= 0x20 && self.value < 0x7F } var isStartOfUTF8Character: Bool { // RFC 2279: The octet values FE and FF never appear. // RFC 3629: The octet values C0, C1, F5 to FF never appear. - return self.value <= 0x80 || (self.value >= 0xC2 && self.value < 0xF5) + self.value <= 0x80 || (self.value >= 0xC2 && self.value < 0xF5) } } diff --git a/Sources/SwiftParser/Lookahead.swift b/Sources/SwiftParser/Lookahead.swift index e36108bde45..d61a725dabb 100644 --- a/Sources/SwiftParser/Lookahead.swift +++ b/Sources/SwiftParser/Lookahead.swift @@ -52,7 +52,7 @@ extension Parser { /// Initiates a lookahead session from the current point in this /// lookahead session. func lookahead() -> Lookahead { - return Lookahead( + Lookahead( lexemes: self.lexemes, currentToken: self.currentToken, experimentalFeatures: self.experimentalFeatures @@ -62,7 +62,7 @@ extension Parser { /// Initiates a lookahead session from the current point in this parse. func lookahead() -> Lookahead { - return Lookahead(cloning: self) + Lookahead(cloning: self) } func withLookahead(_ body: (_: inout Lookahead) -> T) -> T { @@ -80,7 +80,7 @@ extension Parser.Lookahead: TokenConsumer { /// - Parameter kind: The kind of token to consume. /// - Returns: A token of the given kind. mutating func eat(_ spec: TokenSpec) -> Token { - return self.consume(if: spec)! + self.consume(if: spec)! } #if SWIFTPARSER_ENABLE_ALTERNATE_TOKEN_INTROSPECTION @@ -92,7 +92,7 @@ extension Parser.Lookahead: TokenConsumer { extension Parser.Lookahead { func peek() -> Lexer.Lexeme { - return self.lexemes.peek() + self.lexemes.peek() } } @@ -305,7 +305,7 @@ extension Parser.Lookahead { extension Parser.Lookahead { mutating func skipUntil(_ t1: TokenSpec, _ t2: TokenSpec) { - return skip(initialState: .skipUntil(t1, t2)) + skip(initialState: .skipUntil(t1, t2)) } mutating func skipUntilEndOfLine() { @@ -315,7 +315,7 @@ extension Parser.Lookahead { } mutating func skipSingle() { - return skip(initialState: .skipSingle) + skip(initialState: .skipSingle) } // Note: We don't need to treat string quotes as bracketed tokens because: diff --git a/Sources/SwiftParser/LoopProgressCondition.swift b/Sources/SwiftParser/LoopProgressCondition.swift index 9a9b6bf6803..e1e236e7ca7 100644 --- a/Sources/SwiftParser/LoopProgressCondition.swift +++ b/Sources/SwiftParser/LoopProgressCondition.swift @@ -56,7 +56,7 @@ extension Parser { /// progress, thus aborting the loop. @inline(__always) func hasProgressed(_ loopProgress: inout LoopProgressCondition) -> Bool { - return loopProgress.evaluate(self.currentToken) + loopProgress.evaluate(self.currentToken) } } @@ -71,6 +71,6 @@ extension Parser.Lookahead { /// progress, thus aborting the loop. @inline(__always) func hasProgressed(_ loopProgress: inout LoopProgressCondition) -> Bool { - return loopProgress.evaluate(self.currentToken) + loopProgress.evaluate(self.currentToken) } } diff --git a/Sources/SwiftParser/Names.swift b/Sources/SwiftParser/Names.swift index 17d5e00cdb0..581ae018765 100644 --- a/Sources/SwiftParser/Names.swift +++ b/Sources/SwiftParser/Names.swift @@ -304,13 +304,13 @@ extension Lexer.Lexeme { } func isContextualPunctuator(_ name: SyntaxText) -> Bool { - return Operator(lexeme: self) != nil && self.tokenText == name + Operator(lexeme: self) != nil && self.tokenText == name } var isLexerClassifiedKeyword: Bool { // Only lexer-classified lexemes have ``RawTokenKind`` of `keyword. // Contextual keywords will only be made keywords when a ``RawTokenSyntax`` is // constructed from them. - return self.rawTokenKind == .keyword + self.rawTokenKind == .keyword } } diff --git a/Sources/SwiftParser/Nominals.swift b/Sources/SwiftParser/Nominals.swift index 7e65bea5068..9e5a7240638 100644 --- a/Sources/SwiftParser/Nominals.swift +++ b/Sources/SwiftParser/Nominals.swift @@ -62,7 +62,7 @@ extension RawProtocolDeclSyntax: NominalTypeDeclarationTrait { } static func parsePrimaryOrGenerics(_ parser: inout Parser) -> RawPrimaryAssociatedTypeClauseSyntax? { - return parser.parsePrimaryAssociatedTypes() + parser.parsePrimaryAssociatedTypes() } } @@ -96,7 +96,7 @@ extension RawClassDeclSyntax: NominalTypeDeclarationTrait { } static func parsePrimaryOrGenerics(_ parser: inout Parser) -> RawGenericParameterClauseSyntax? { - return parser.parseGenericParameters() + parser.parseGenericParameters() } } @@ -130,7 +130,7 @@ extension RawActorDeclSyntax: NominalTypeDeclarationTrait { } static func parsePrimaryOrGenerics(_ parser: inout Parser) -> RawGenericParameterClauseSyntax? { - return parser.parseGenericParameters() + parser.parseGenericParameters() } } @@ -164,7 +164,7 @@ extension RawStructDeclSyntax: NominalTypeDeclarationTrait { } static func parsePrimaryOrGenerics(_ parser: inout Parser) -> RawGenericParameterClauseSyntax? { - return parser.parseGenericParameters() + parser.parseGenericParameters() } } @@ -198,7 +198,7 @@ extension RawEnumDeclSyntax: NominalTypeDeclarationTrait { } static func parsePrimaryOrGenerics(_ parser: inout Parser) -> RawGenericParameterClauseSyntax? { - return parser.parseGenericParameters() + parser.parseGenericParameters() } } diff --git a/Sources/SwiftParser/Parser.swift b/Sources/SwiftParser/Parser.swift index 9cf9aaad516..caca59eb6ec 100644 --- a/Sources/SwiftParser/Parser.swift +++ b/Sources/SwiftParser/Parser.swift @@ -333,7 +333,7 @@ public struct Parser { } mutating func missingToken(_ keyword: Keyword) -> RawTokenSyntax { - return missingToken(.keyword, text: keyword.defaultText) + missingToken(.keyword, text: keyword.defaultText) } /// Consumes the current token and advances the lexer to the next token. @@ -399,7 +399,7 @@ public struct Parser { extension Parser { /// Retrieves the token following the current token without consuming it. func peek() -> Lexer.Lexeme { - return self.lexemes.peek() + self.lexemes.peek() } } @@ -549,7 +549,7 @@ extension Parser { mutating func expect( _ spec: TokenSpec ) -> (unexpected: RawUnexpectedNodesSyntax?, token: RawTokenSyntax) { - return expectImpl( + expectImpl( consume: { $0.consume(if: spec) }, canRecoverTo: { $0.canRecoverTo(spec) }, makeMissing: { $0.missingToken(spec) } @@ -569,7 +569,7 @@ extension Parser { _ spec2: TokenSpec, default defaultKind: TokenSpec ) -> (unexpected: RawUnexpectedNodesSyntax?, token: RawTokenSyntax) { - return expectImpl( + expectImpl( consume: { $0.consume(if: spec1, spec2) }, canRecoverTo: { $0.canRecoverTo(spec1, spec2) }, makeMissing: { $0.missingToken(defaultKind) } @@ -590,7 +590,7 @@ extension Parser { _ spec3: TokenSpec, default defaultKind: TokenSpec ) -> (unexpected: RawUnexpectedNodesSyntax?, token: RawTokenSyntax) { - return expectImpl( + expectImpl( consume: { $0.consume(if: spec1, spec2, spec3) }, canRecoverTo: { $0.canRecoverTo(spec1, spec2, spec3) }, makeMissing: { $0.missingToken(defaultKind) } @@ -602,7 +602,7 @@ extension Parser { anyIn specSet: SpecSet.Type, default defaultKind: SpecSet ) -> (unexpected: RawUnexpectedNodesSyntax?, token: RawTokenSyntax) { - return expectImpl( + expectImpl( consume: { $0.consume(ifAnyIn: specSet) }, canRecoverTo: { $0.canRecoverTo(anyIn: specSet)?.1 }, makeMissing: { $0.missingToken(defaultKind.spec) } diff --git a/Sources/SwiftParser/Recovery.swift b/Sources/SwiftParser/Recovery.swift index 58b91a5d9be..0d3ec59bfa5 100644 --- a/Sources/SwiftParser/Recovery.swift +++ b/Sources/SwiftParser/Recovery.swift @@ -22,7 +22,7 @@ struct RecoveryConsumptionHandle { var tokenConsumptionHandle: TokenConsumptionHandle static func constant(_ spec: TokenSpec) -> RecoveryConsumptionHandle { - return RecoveryConsumptionHandle( + RecoveryConsumptionHandle( unexpectedTokens: 0, tokenConsumptionHandle: TokenConsumptionHandle(spec: spec) ) @@ -31,7 +31,7 @@ struct RecoveryConsumptionHandle { /// A `RecoveryConsumptionHandle` that will not eat any tokens but instead /// synthesize a missing token of kind `token`. static func missing(_ spec: TokenSpec) -> RecoveryConsumptionHandle { - return RecoveryConsumptionHandle( + RecoveryConsumptionHandle( unexpectedTokens: 0, tokenConsumptionHandle: TokenConsumptionHandle(spec: spec, tokenIsMissing: true) ) @@ -43,7 +43,7 @@ extension Parser.Lookahead { mutating func canRecoverTo( _ spec: TokenSpec ) -> RecoveryConsumptionHandle? { - return canRecoverTo(spec, spec, spec) + canRecoverTo(spec, spec, spec) } /// See `canRecoverTo` that takes 3 specs. @@ -51,7 +51,7 @@ extension Parser.Lookahead { _ spec1: TokenSpec, _ spec2: TokenSpec ) -> RecoveryConsumptionHandle? { - return canRecoverTo(spec1, spec2, spec1) + canRecoverTo(spec1, spec2, spec1) } /// Tries eating tokens until it finds a token that matches `spec1`, `spec2` or `spec3` diff --git a/Sources/SwiftParser/Specifiers.swift b/Sources/SwiftParser/Specifiers.swift index 2238cd54067..95534016aa9 100644 --- a/Sources/SwiftParser/Specifiers.swift +++ b/Sources/SwiftParser/Specifiers.swift @@ -118,7 +118,7 @@ public enum EffectSpecifier: TokenSpecSet { @_spi(Diagnostics) public static var allCases: [EffectSpecifier] { - return AsyncEffectSpecifier.allCases.map(Self.asyncSpecifier) + AsyncEffectSpecifier.allCases.map(Self.asyncSpecifier) + ThrowsEffectSpecifier.allCases.map(Self.throwsSpecifier) } @@ -195,7 +195,7 @@ extension RawEffectSpecifiersTrait { } func withMisplaced(async misplacedAsyncKeyword: RawTokenSyntax?, throws misplacedThrowsKeyword: RawTokenSyntax?, arena: __shared SyntaxArena) -> Self { - return Self.init( + Self.init( self.unexpectedBeforeAsyncSpecifier, asyncSpecifier: self.asyncSpecifier ?? misplacedAsyncKeyword, self.unexpectedBetweenAsyncSpecifierAndThrowsSpecifier, @@ -651,15 +651,15 @@ extension Parser { } mutating func parseTypeEffectSpecifiers() -> RawTypeEffectSpecifiersSyntax? { - return parseEffectSpecifiers(RawTypeEffectSpecifiersSyntax.self) + parseEffectSpecifiers(RawTypeEffectSpecifiersSyntax.self) } mutating func parseFunctionEffectSpecifiers() -> RawFunctionEffectSpecifiersSyntax? { - return parseEffectSpecifiers(RawFunctionEffectSpecifiersSyntax.self) + parseEffectSpecifiers(RawFunctionEffectSpecifiersSyntax.self) } mutating func parseAccessorEffectSpecifiers() -> RawAccessorEffectSpecifiersSyntax? { - return parseEffectSpecifiers(RawAccessorEffectSpecifiersSyntax.self) + parseEffectSpecifiers(RawAccessorEffectSpecifiersSyntax.self) } mutating func parseDeinitEffectSpecifiers() -> RawDeinitializerEffectSpecifiersSyntax? { diff --git a/Sources/SwiftParser/SwiftParserCompatibility.swift b/Sources/SwiftParser/SwiftParserCompatibility.swift index 24c966d245e..3204ce0f31d 100644 --- a/Sources/SwiftParser/SwiftParserCompatibility.swift +++ b/Sources/SwiftParser/SwiftParserCompatibility.swift @@ -16,12 +16,12 @@ public extension TokenSpec { @available(*, deprecated, renamed: "leftSquare") static var leftSquareBracket: TokenSpec { - return .leftSquare + .leftSquare } @available(*, deprecated, renamed: "rightSquare") static var rightSquareBracket: TokenSpec { - return .rightSquare + .rightSquare } } diff --git a/Sources/SwiftParser/SyntaxUtils.swift b/Sources/SwiftParser/SyntaxUtils.swift index 5891956f1fe..fbcc45dfcc6 100644 --- a/Sources/SwiftParser/SyntaxUtils.swift +++ b/Sources/SwiftParser/SyntaxUtils.swift @@ -17,7 +17,7 @@ extension RawUnexpectedNodesSyntax { /// Returns `true` if this contains a token that satisfies `condition`. func containsToken(where condition: (RawTokenSyntax) -> Bool) -> Bool { - return self.elements.contains(where: { node in + self.elements.contains(where: { node in if let token = node.as(RawTokenSyntax.self) { return condition(token) } else { @@ -66,7 +66,7 @@ extension Optional: UnexpectedNodesCombinable where Wrapped: UnexpectedNodesComb extension RawTokenSyntax: UnexpectedNodesCombinable { var elements: [RawSyntax] { - return [RawSyntax(self)] + [RawSyntax(self)] } } @@ -101,7 +101,7 @@ extension RawUnexpectedNodesSyntax { extension SyntaxText { var isEditorPlaceholder: Bool { - return self.starts(with: SyntaxText("<#")) && self.hasSuffix(SyntaxText("#>")) + self.starts(with: SyntaxText("<#")) && self.hasSuffix(SyntaxText("#>")) } var isStartingWithUppercase: Bool { diff --git a/Sources/SwiftParser/TokenConsumer.swift b/Sources/SwiftParser/TokenConsumer.swift index 59b3a7cf76a..c77dfdaad1f 100644 --- a/Sources/SwiftParser/TokenConsumer.swift +++ b/Sources/SwiftParser/TokenConsumer.swift @@ -121,7 +121,7 @@ extension TokenConsumer { /// Returns whether the current token is an operator with the given `name`. @inline(__always) mutating func atContextualPunctuator(_ name: SyntaxText) -> Bool { - return self.currentToken.isContextualPunctuator(name) + self.currentToken.isContextualPunctuator(name) } /// Checks whether the parser is currently positioned at any token in `Subset`. @@ -147,13 +147,13 @@ extension TokenConsumer { /// Whether the current token’s text starts with the given prefix. @inline(__always) mutating func at(prefix: SyntaxText) -> Bool { - return self.currentToken.tokenText.hasPrefix(prefix) + self.currentToken.tokenText.hasPrefix(prefix) } /// Whether the current token is at the start of a line. @inline(__always) var atStartOfLine: Bool { - return self.currentToken.isAtStartOfLine + self.currentToken.isAtStartOfLine } /// Eat a token that we know we are currently positioned at, based on `at(anyIn:)`. @@ -362,6 +362,6 @@ extension TokenConsumer { /// Whether the current token can be a function argument label. func atArgumentLabel(allowDollarIdentifier: Bool = false) -> Bool { - return self.currentToken.isArgumentLabel(allowDollarIdentifier: allowDollarIdentifier) + self.currentToken.isArgumentLabel(allowDollarIdentifier: allowDollarIdentifier) } } diff --git a/Sources/SwiftParser/TokenPrecedence.swift b/Sources/SwiftParser/TokenPrecedence.swift index e2a48b167c6..b610214ceed 100644 --- a/Sources/SwiftParser/TokenPrecedence.swift +++ b/Sources/SwiftParser/TokenPrecedence.swift @@ -103,7 +103,7 @@ enum TokenPrecedence: Comparable { /// When expecting a token with `stmtKeyword` precedence or higher, newlines may be skipped to find that token. /// For lower precedence groups, we consider newlines the end of the lookahead scope. var shouldSkipOverNewlines: Bool { - return self >= .stmtKeyword + self >= .stmtKeyword } init(_ lexeme: Lexer.Lexeme) { diff --git a/Sources/SwiftParser/TokenSpec.swift b/Sources/SwiftParser/TokenSpec.swift index da0b3fc74fd..8c2c37baf8f 100644 --- a/Sources/SwiftParser/TokenSpec.swift +++ b/Sources/SwiftParser/TokenSpec.swift @@ -128,7 +128,7 @@ public struct TokenSpec { @inline(__always) static func ~= (kind: TokenSpec, lexeme: Lexer.Lexeme) -> Bool { - return kind.matches( + kind.matches( rawTokenKind: lexeme.rawTokenKind, keyword: Keyword(lexeme.tokenText), atStartOfLine: lexeme.isAtStartOfLine @@ -137,7 +137,7 @@ public struct TokenSpec { @inline(__always) static func ~= (kind: TokenSpec, token: TokenSyntax) -> Bool { - return kind.matches( + kind.matches( rawTokenKind: token.tokenView.rawKind, keyword: Keyword(token.tokenView.rawText), atStartOfLine: token.leadingTrivia.contains(where: { $0.isNewline }) @@ -146,7 +146,7 @@ public struct TokenSpec { @inline(__always) static func ~= (kind: TokenSpec, token: RawTokenSyntax) -> Bool { - return kind.matches( + kind.matches( rawTokenKind: token.tokenKind, keyword: Keyword(token.tokenView.rawText), atStartOfLine: token.leadingTriviaPieces.contains(where: \.isNewline) @@ -155,7 +155,7 @@ public struct TokenSpec { @inline(__always) static func ~= (kind: TokenSpec, lexeme: PrepareForKeywordMatch) -> Bool { - return kind.matches( + kind.matches( rawTokenKind: lexeme.rawTokenKind, keyword: lexeme.keyword, atStartOfLine: lexeme.isAtStartOfLine @@ -191,7 +191,7 @@ extension TokenConsumer { /// Generates a missing token that has the expected kind of `spec`. @inline(__always) mutating func missingToken(_ spec: TokenSpec) -> Token { - return missingToken(spec.remapping ?? spec.rawTokenKind, text: spec.keyword?.defaultText ?? spec.rawTokenKind.defaultText) + missingToken(spec.remapping ?? spec.rawTokenKind, text: spec.keyword?.defaultText ?? spec.rawTokenKind.defaultText) } /// Asserts that the current token matches `spec` and consumes it, performing diff --git a/Sources/SwiftParser/TokenSpecSet.swift b/Sources/SwiftParser/TokenSpecSet.swift index 87aa295d627..a73e258a847 100644 --- a/Sources/SwiftParser/TokenSpecSet.swift +++ b/Sources/SwiftParser/TokenSpecSet.swift @@ -49,7 +49,7 @@ enum EitherTokenSpecSet: TokenSpecSet { } static var allCases: [EitherTokenSpecSet] { - return LHS.allCases.map(Self.lhs) + RHS.allCases.map(Self.rhs) + LHS.allCases.map(Self.lhs) + RHS.allCases.map(Self.rhs) } } @@ -476,7 +476,7 @@ enum DeclarationStart: TokenSpecSet { } static var allCases: [DeclarationStart] { - return DeclarationModifier.allCases.map(Self.declarationModifier) + DeclarationKeyword.allCases.map(Self.declarationKeyword) + DeclarationModifier.allCases.map(Self.declarationModifier) + DeclarationKeyword.allCases.map(Self.declarationKeyword) } var spec: TokenSpec { @@ -961,7 +961,7 @@ enum ExpressionStart: TokenSpecSet { } static var allCases: [ExpressionStart] { - return ExpressionModifierKeyword.allCases.map(Self.awaitTryMove) + ExpressionModifierKeyword.allCases.map(Self.awaitTryMove) + ExpressionPrefixOperator.allCases.map(Self.expressionPrefixOperator) + PrimaryExpressionStart.allCases.map(Self.primaryExpressionStart) + IfOrSwitch.allCases.map(Self.ifOrSwitch) diff --git a/Sources/SwiftParser/TopLevel.swift b/Sources/SwiftParser/TopLevel.swift index 08b77823726..6f3e5258b20 100644 --- a/Sources/SwiftParser/TopLevel.swift +++ b/Sources/SwiftParser/TopLevel.swift @@ -84,7 +84,7 @@ extension Parser { /// Parse the top level items in a source file. mutating func parseTopLevelCodeBlockItems() -> RawCodeBlockItemListSyntax { - return parseCodeBlockItemList(isAtTopLevel: true, until: { _ in false }) + parseCodeBlockItemList(isAtTopLevel: true, until: { _ in false }) } /// The optional form of `parseCodeBlock` that checks to see if the parser has diff --git a/Sources/SwiftParser/Types.swift b/Sources/SwiftParser/Types.swift index 0ee67433e91..afbdb5eebd5 100644 --- a/Sources/SwiftParser/Types.swift +++ b/Sources/SwiftParser/Types.swift @@ -931,11 +931,11 @@ extension Parser { case .convention: return parseAttribute(argumentMode: .required) { parser in - return parser.parseConventionArguments() + parser.parseConventionArguments() } case ._opaqueReturnTypeOf: return parseAttribute(argumentMode: .required) { parser in - return .opaqueReturnTypeOfAttributeArguments(parser.parseOpaqueReturnTypeOfAttributeArguments()) + .opaqueReturnTypeOfAttributeArguments(parser.parseOpaqueReturnTypeOfAttributeArguments()) } case nil: // Custom attribute return parseAttribute(argumentMode: .customAttribute) { parser in diff --git a/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift b/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift index 27fb25ccb5b..8fa282b21f1 100644 --- a/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift +++ b/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift @@ -51,7 +51,7 @@ extension FixIt.MultiNodeChange { /// If `transferTrivia` is `true`, the leading and trailing trivia of the /// removed node will be transferred to the trailing trivia of the previous token. static func makeMissing(_ token: TokenSyntax, transferTrivia: Bool = true) -> Self { - return makeMissing([token], transferTrivia: transferTrivia) + makeMissing([token], transferTrivia: transferTrivia) } /// Replace present tokens with missing tokens. @@ -115,7 +115,7 @@ class PresentMakingFormatter: BasicFormat { override func isMutable(_ token: TokenSyntax) -> Bool { // Assume that all missing nodes will be made present by the Fix-It. - return token.isMissing + token.isMissing } /// Change the text of all missing tokens to a placeholder with their diff --git a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift index 9a59b1ded2b..e8f362b3cc7 100644 --- a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift @@ -23,15 +23,15 @@ public protocol TokenError: DiagnosticMessage { public extension TokenError { static var diagnosticID: MessageID { - return MessageID(domain: diagnosticDomain, id: "\(self)") + MessageID(domain: diagnosticDomain, id: "\(self)") } var diagnosticID: MessageID { - return Self.diagnosticID + Self.diagnosticID } var severity: DiagnosticSeverity { - return .error + .error } } @@ -178,7 +178,7 @@ public extension SwiftSyntax.TokenDiagnostic { } func diagnosticMessage(in token: TokenSyntax) -> DiagnosticMessage { - return self.diagnosticMessage(wholeTextBytes: token.syntaxTextBytes) + self.diagnosticMessage(wholeTextBytes: token.syntaxTextBytes) } func fixIts(in token: TokenSyntax) -> [FixIt] { diff --git a/Sources/SwiftParserDiagnostics/MissingNodesError.swift b/Sources/SwiftParserDiagnostics/MissingNodesError.swift index 74f73c0d63f..427f99b7c2b 100644 --- a/Sources/SwiftParserDiagnostics/MissingNodesError.swift +++ b/Sources/SwiftParserDiagnostics/MissingNodesError.swift @@ -18,14 +18,14 @@ import SwiftDiagnostics /// Returns the bottommost node that is an ancestor of all nodes in `nodes`. fileprivate func findCommonAncestor(_ nodes: [Syntax]) -> Syntax? { - return findCommonAncestorOrSelf(nodes.compactMap({ $0.parent })) + findCommonAncestorOrSelf(nodes.compactMap({ $0.parent })) } class NoNewlinesFormat: BasicFormat { override var inferInitialTokenIndentation: Bool { false } override func requiresNewline(between first: TokenSyntax?, and second: TokenSyntax?) -> Bool { - return false + false } } @@ -128,7 +128,7 @@ fileprivate enum NodesDescriptionPart { /// If `commonParent` is not `nil`, `missingNodes` are expected to all be children of `commonParent`. /// If `format` is `true`, `BasicFormat` will be used to format the tokens prior to printing. This is useful if the nodes have been synthesized. func nodesDescription(_ nodes: [some SyntaxProtocol], format: Bool) -> String { - return nodesDescriptionAndCommonParent(nodes, format: format).description + nodesDescriptionAndCommonParent(nodes, format: format).description } /// Same as `nodesDescription` but if a common ancestor was used to describe `missingNodes`, also return that `commonAncestor` @@ -184,7 +184,7 @@ fileprivate extension TokenKind { } var isEndMarker: Bool { - return matchingStartMarkerKind != nil + matchingStartMarkerKind != nil } var matchingStartMarkerKind: TokenKind? { diff --git a/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift b/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift index 517cf281594..77a69f3c2c8 100644 --- a/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift +++ b/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift @@ -478,7 +478,7 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } public override func visit(_ node: AccessorEffectSpecifiersSyntax) -> SyntaxVisitorContinueKind { - return handleEffectSpecifiers(node) + handleEffectSpecifiers(node) } public override func visit(_ node: AssociatedTypeDeclSyntax) -> SyntaxVisitorContinueKind { @@ -749,7 +749,7 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } public override func visit(_ node: FunctionEffectSpecifiersSyntax) -> SyntaxVisitorContinueKind { - return handleEffectSpecifiers(node) + handleEffectSpecifiers(node) } public override func visit(_ node: GenericRequirementSyntax) -> SyntaxVisitorContinueKind { @@ -1313,27 +1313,27 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } public override func visit(_ node: MissingDeclSyntax) -> SyntaxVisitorContinueKind { - return handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) + handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) } public override func visit(_ node: MissingExprSyntax) -> SyntaxVisitorContinueKind { - return handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) + handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) } public override func visit(_ node: MissingPatternSyntax) -> SyntaxVisitorContinueKind { - return handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) + handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) } public override func visit(_ node: MissingStmtSyntax) -> SyntaxVisitorContinueKind { - return handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) + handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) } public override func visit(_ node: MissingSyntax) -> SyntaxVisitorContinueKind { - return handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) + handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) } public override func visit(_ node: MissingTypeSyntax) -> SyntaxVisitorContinueKind { - return handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) + handleMissingSyntax(node, additionalHandledNodes: [node.placeholder.id]) } override open func visit(_ node: OriginallyDefinedInAttributeArgumentsSyntax) -> SyntaxVisitorContinueKind { @@ -1782,7 +1782,7 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } public override func visit(_ node: TypeEffectSpecifiersSyntax) -> SyntaxVisitorContinueKind { - return handleEffectSpecifiers(node) + handleEffectSpecifiers(node) } public override func visit(_ node: InheritanceClauseSyntax) -> SyntaxVisitorContinueKind { diff --git a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift index 8d210bd5be6..579b8616715 100644 --- a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift @@ -23,15 +23,15 @@ public protocol ParserError: DiagnosticMessage { public extension ParserError { static var diagnosticID: MessageID { - return MessageID(domain: diagnosticDomain, id: "\(self)") + MessageID(domain: diagnosticDomain, id: "\(self)") } var diagnosticID: MessageID { - return Self.diagnosticID + Self.diagnosticID } var severity: DiagnosticSeverity { - return .error + .error } } @@ -41,11 +41,11 @@ public protocol ParserNote: NoteMessage { public extension ParserNote { static var fixItID: MessageID { - return MessageID(domain: diagnosticDomain, id: "\(self)") + MessageID(domain: diagnosticDomain, id: "\(self)") } var fixItID: MessageID { - return Self.fixItID + Self.fixItID } } @@ -55,11 +55,11 @@ public protocol ParserFixIt: FixItMessage { public extension ParserFixIt { static var fixItID: MessageID { - return MessageID(domain: diagnosticDomain, id: "\(self)") + MessageID(domain: diagnosticDomain, id: "\(self)") } var fixItID: MessageID { - return Self.fixItID + Self.fixItID } } @@ -169,7 +169,7 @@ extension DiagnosticMessage where Self == StaticParserError { .init("argument cannot be an extended escaping string literal") } public static var forbiddenInterpolatedString: Self { - return .init("argument cannot be an interpolated string literal") + .init("argument cannot be an interpolated string literal") } public static var initializerInPattern: Self { .init("unexpected initializer in pattern; did you mean to use '='?") @@ -276,7 +276,7 @@ public struct AsyncMustPrecedeThrows: ParserError { public let throwsKeyword: TokenSyntax public var message: String { - return "\(nodesDescription(asyncKeywords, format: false)) must precede \(nodesDescription([throwsKeyword], format: false))" + "\(nodesDescription(asyncKeywords, format: false)) must precede \(nodesDescription([throwsKeyword], format: false))" } } @@ -285,7 +285,7 @@ public struct AvailabilityConditionAsExpression: ParserError { public let negatedAvailabilityToken: TokenSyntax public var message: String { - return "\(availabilityToken) cannot be used as an expression, did you mean to use '\(negatedAvailabilityToken)'?" + "\(availabilityToken) cannot be used as an expression, did you mean to use '\(negatedAvailabilityToken)'?" } } @@ -293,7 +293,7 @@ public struct AvailabilityConditionInExpression: ParserError { public let availabilityCondition: AvailabilityConditionSyntax public var message: String { - return "\(nodesDescription([availabilityCondition], format: false)) cannot be used in an expression, only as a condition of 'if' or 'guard'" + "\(nodesDescription([availabilityCondition], format: false)) cannot be used in an expression, only as a condition of 'if' or 'guard'" } } @@ -301,7 +301,7 @@ public struct CannotParseVersionTuple: ParserError { public let versionTuple: UnexpectedNodesSyntax public var message: String { - return "cannot parse version component \(versionTuple.shortSingleLineContentDescription)" + "cannot parse version component \(versionTuple.shortSingleLineContentDescription)" } } @@ -330,7 +330,7 @@ public struct ExtraneousCodeAtTopLevel: ParserError { public let extraneousCode: UnexpectedNodesSyntax public var message: String { - return "extraneous \(extraneousCode.shortSingleLineContentDescription) at top level" + "extraneous \(extraneousCode.shortSingleLineContentDescription) at top level" } } @@ -338,7 +338,7 @@ public struct ExtraneousWhitespace: ParserError { public let tokenWithWhitespace: TokenSyntax public var message: String { - return "extraneous whitespace after '\(tokenWithWhitespace.text)' is not permitted" + "extraneous whitespace after '\(tokenWithWhitespace.text)' is not permitted" } } @@ -346,7 +346,7 @@ public struct IdentifierNotAllowedInOperatorName: ParserError { public let identifier: TokenSyntax public var message: String { - return "\(nodesDescription([identifier], format: false)) is considered an identifier and must not appear within an operator name" + "\(nodesDescription([identifier], format: false)) is considered an identifier and must not appear within an operator name" } } @@ -354,7 +354,7 @@ public struct InvalidFloatLiteralMissingLeadingZero: ParserError { public let decimalDigits: TokenSyntax public var message: String { - return "'.\(decimalDigits.text)' is not a valid floating point literal; it must be written '0.\(decimalDigits.text)'" + "'.\(decimalDigits.text)' is not a valid floating point literal; it must be written '0.\(decimalDigits.text)'" } } @@ -411,7 +411,7 @@ public struct MissingAttributeArgument: ParserError { public let attributeName: TypeSyntax public var message: String { - return "expected argument for '@\(attributeName)' attribute" + "expected argument for '@\(attributeName)' attribute" } } @@ -419,7 +419,7 @@ public struct MissingBothStringQuotesOfStringSegments: ParserError { public let stringSegments: StringLiteralSegmentListSyntax public var message: String { - return #"expected \#(stringSegments.shortSingleLineContentDescription) to be surrounded by '"'"# + #"expected \#(stringSegments.shortSingleLineContentDescription) to be surrounded by '"'"# } } @@ -452,8 +452,8 @@ public struct NegatedAvailabilityCondition: ParserError { public let negatedAvailabilityKeyword: TokenSyntax public var message: String { - return - "\(nodesDescription([availabilityCondition], format: false)) cannot be used in an expression; did you mean \(nodesDescription([negatedAvailabilityKeyword], format: false))?" + + "\(nodesDescription([availabilityCondition], format: false)) cannot be used in an expression; did you mean \(nodesDescription([negatedAvailabilityKeyword], format: false))?" } } @@ -476,7 +476,7 @@ public struct SpecifierOnParameterName: ParserError { public let misplacedSpecifiers: [TokenSyntax] public var message: String { - return "\(nodesDescription(misplacedSpecifiers, format: false)) before a parameter name is not allowed" + "\(nodesDescription(misplacedSpecifiers, format: false)) before a parameter name is not allowed" } } @@ -484,7 +484,7 @@ public struct TokensNotAllowedInOperatorName: ParserError { public let tokens: [TokenSyntax] public var message: String { - return "\(nodesDescription(tokens, format: false)) is not allowed in operator names" + "\(nodesDescription(tokens, format: false)) is not allowed in operator names" } } @@ -493,7 +493,7 @@ public struct TrailingVersionAreIgnored: ParserError { public let components: VersionComponentListSyntax public var message: String { - return "trailing components of version \(major)\(components) are ignored" + "trailing components of version \(major)\(components) are ignored" } public var severity: DiagnosticSeverity = .warning @@ -503,7 +503,7 @@ public struct TryCannotBeUsed: ParserError { public let nextToken: TokenSyntax public var message: String { - return "'try' cannot be used with '\(nextToken.text)'" + "'try' cannot be used with '\(nextToken.text)'" } } @@ -529,7 +529,7 @@ public struct UnknownDirectiveError: ParserError { public let unexpected: UnexpectedNodesSyntax public var message: String { - return "use of unknown directive \(nodesDescription([unexpected], format: false))" + "use of unknown directive \(nodesDescription([unexpected], format: false))" } } @@ -556,7 +556,7 @@ public struct EffectSpecifierDeclaredHere: ParserNote { let specifier: TokenSyntax public var message: String { - return "\(nodesDescription([specifier], format: false)) declared here" + "\(nodesDescription([specifier], format: false)) declared here" } } diff --git a/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift b/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift index e5e14afcec9..37a5aee78ab 100644 --- a/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift +++ b/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift @@ -15,11 +15,11 @@ extension UnexpectedNodesSyntax { func presentTokens(satisfying isIncluded: (TokenSyntax) -> Bool) -> [TokenSyntax] { - return self.children(viewMode: .sourceAccurate).compactMap({ $0.as(TokenSyntax.self) }).filter(isIncluded) + self.children(viewMode: .sourceAccurate).compactMap({ $0.as(TokenSyntax.self) }).filter(isIncluded) } func presentTokens(withKind kind: TokenKind) -> [TokenSyntax] { - return self.presentTokens(satisfying: { $0.tokenKind == kind }) + self.presentTokens(satisfying: { $0.tokenKind == kind }) } /// If this only contains a single item, which is a present token satisfying `condition`, return that token, otherwise return `nil`. @@ -185,10 +185,10 @@ public extension TriviaPiece { extension TokenSyntax { var isMissing: Bool { - return presence == .missing + presence == .missing } var isPresent: Bool { - return presence == .present + presence == .present } } diff --git a/Sources/SwiftRefactor/CallToTrailingClosures.swift b/Sources/SwiftRefactor/CallToTrailingClosures.swift index 96bbbdcd3cf..c5a879022e3 100644 --- a/Sources/SwiftRefactor/CallToTrailingClosures.swift +++ b/Sources/SwiftRefactor/CallToTrailingClosures.swift @@ -48,7 +48,7 @@ public struct CallToTrailingClosures: SyntaxRefactoringProvider { // TODO: Rather than returning nil, we should consider throwing errors with // appropriate messages instead. public static func refactor(syntax call: FunctionCallExprSyntax, in context: Context = Context()) -> FunctionCallExprSyntax? { - return call.convertToTrailingClosures(from: context.startAtArgument)?.formatted().as(FunctionCallExprSyntax.self) + call.convertToTrailingClosures(from: context.startAtArgument)?.formatted().as(FunctionCallExprSyntax.self) } } diff --git a/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift b/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift index 996e6909b0f..1fd1ceb5625 100644 --- a/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift +++ b/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift @@ -71,15 +71,15 @@ import SwiftSyntaxBuilder /// ``` public struct ExpandEditorPlaceholder: EditRefactoringProvider { public static func isPlaceholder(_ str: String) -> Bool { - return str.hasPrefix(placeholderStart) && str.hasSuffix(placeholderEnd) + str.hasPrefix(placeholderStart) && str.hasSuffix(placeholderEnd) } public static func wrapInPlaceholder(_ str: String) -> String { - return placeholderStart + str + placeholderEnd + placeholderStart + str + placeholderEnd } public static func wrapInTypePlaceholder(_ str: String, type: String) -> String { - return Self.wrapInPlaceholder("T##" + str + "##" + type) + Self.wrapInPlaceholder("T##" + str + "##" + type) } public static func textRefactor(syntax token: TokenSyntax, in context: Void) -> [SourceEdit] { diff --git a/Sources/SwiftRefactor/RefactoringProvider.swift b/Sources/SwiftRefactor/RefactoringProvider.swift index 533da8c1fa2..52f3a7cf9bd 100644 --- a/Sources/SwiftRefactor/RefactoringProvider.swift +++ b/Sources/SwiftRefactor/RefactoringProvider.swift @@ -39,7 +39,7 @@ extension EditRefactoringProvider where Context == Void { /// - syntax: The syntax to transform. /// - Returns: Textual edits describing the refactoring to perform. public static func textRefactor(syntax: Input) -> [SourceEdit] { - return self.textRefactor(syntax: syntax, in: ()) + self.textRefactor(syntax: syntax, in: ()) } } @@ -94,7 +94,7 @@ extension SyntaxRefactoringProvider where Context == Void { /// - Returns: The result of applying the refactoring action, or `nil` if the /// action could not be performed. public static func refactor(syntax: Input) -> Output? { - return self.refactor(syntax: syntax, in: ()) + self.refactor(syntax: syntax, in: ()) } } @@ -121,7 +121,7 @@ public struct SourceEdit: Equatable { /// Length of the original source range that this edit applies to. Zero if /// this is an addition. public var length: SourceLength { - return SourceLength(utf8Length: range.lowerBound.utf8Offset - range.upperBound.utf8Offset) + SourceLength(utf8Length: range.lowerBound.utf8Offset - range.upperBound.utf8Offset) } /// Create an edit to replace `range` in the original source with @@ -134,25 +134,25 @@ public struct SourceEdit: Equatable { /// Convenience function to create a textual addition after the given node /// and its trivia. public static func insert(_ newText: String, after node: some SyntaxProtocol) -> SourceEdit { - return SourceEdit(range: node.endPosition.. SourceEdit { - return SourceEdit(range: node.position.. SourceEdit { - return SourceEdit(range: node.position.. SourceEdit { - return SourceEdit(range: node.position.. AbsolutePosition { - return AbsolutePosition(utf8Offset: self.utf8Offset + offset) + AbsolutePosition(utf8Offset: self.utf8Offset + offset) } public static func < (lhs: AbsolutePosition, rhs: AbsolutePosition) -> Bool { - return lhs.utf8Offset < rhs.utf8Offset + lhs.utf8Offset < rhs.utf8Offset } } diff --git a/Sources/SwiftSyntax/AbsoluteSyntaxInfo.swift b/Sources/SwiftSyntax/AbsoluteSyntaxInfo.swift index 3f5e9eee868..e2e55dfb963 100644 --- a/Sources/SwiftSyntax/AbsoluteSyntaxInfo.swift +++ b/Sources/SwiftSyntax/AbsoluteSyntaxInfo.swift @@ -22,11 +22,11 @@ struct AbsoluteSyntaxPosition { } func advancedToFirstChild() -> AbsoluteSyntaxPosition { - return .init(offset: self.offset, indexInParent: 0) + .init(offset: self.offset, indexInParent: 0) } static var forRoot: AbsoluteSyntaxPosition { - return .init(offset: 0, indexInParent: 0) + .init(offset: 0, indexInParent: 0) } } @@ -37,8 +37,8 @@ struct AbsoluteSyntaxInfo { let nodeId: SyntaxIdentifier /// The UTF-8 offset of the syntax node in the source file - var offset: UInt32 { return position.offset } - var indexInParent: UInt32 { return position.indexInParent } + var offset: UInt32 { position.offset } + var indexInParent: UInt32 { position.indexInParent } func advancedBySibling(_ raw: RawSyntax?) -> AbsoluteSyntaxInfo { let newPosition = position.advancedBySibling(raw) @@ -53,6 +53,6 @@ struct AbsoluteSyntaxInfo { } static func forRoot(_ raw: RawSyntax) -> AbsoluteSyntaxInfo { - return .init(position: .forRoot, nodeId: .forRoot(raw)) + .init(position: .forRoot, nodeId: .forRoot(raw)) } } diff --git a/Sources/SwiftSyntax/BumpPtrAllocator.swift b/Sources/SwiftSyntax/BumpPtrAllocator.swift index 181552f3dc0..8dba5215ea5 100644 --- a/Sources/SwiftSyntax/BumpPtrAllocator.swift +++ b/Sources/SwiftSyntax/BumpPtrAllocator.swift @@ -61,7 +61,7 @@ public class BumpPtrAllocator { /// Calculate the size of the slab at the index. private func slabSize(at index: Int) -> Int { // Double the slab size every 'GROWTH_DELAY' slabs. - return self.slabSize * (1 << min(30, index / Self.GROWTH_DELAY)) + self.slabSize * (1 << min(30, index / Self.GROWTH_DELAY)) } private func startNewSlab() { diff --git a/Sources/SwiftSyntax/Raw/RawSyntax.swift b/Sources/SwiftSyntax/Raw/RawSyntax.swift index 9ff39983aa0..395bd823e9a 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntax.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntax.swift @@ -16,7 +16,7 @@ typealias RawTriviaPieceBuffer = UnsafeBufferPointer fileprivate extension SyntaxKind { /// Whether this node kind should be considered as `hasError` for purposes of `RecursiveRawSyntaxFlags`. var hasError: Bool { - return self == .unexpectedNodes || self.isMissing + self == .unexpectedNodes || self.isMissing } } @@ -940,7 +940,7 @@ extension RawSyntax: Identifiable { } public var id: ID { - return ID(self) + ID(self) } } diff --git a/Sources/SwiftSyntax/Raw/RawSyntaxLayoutView.swift b/Sources/SwiftSyntax/Raw/RawSyntaxLayoutView.swift index cb619707378..36ae8b98f1a 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntaxLayoutView.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntaxLayoutView.swift @@ -50,7 +50,7 @@ public struct RawSyntaxLayoutView { } var recursiveFlags: RecursiveRawSyntaxFlags { - return layoutData.recursiveFlags + layoutData.recursiveFlags } /// Creates a new node of the same kind but with children replaced by `elements`. @@ -61,7 +61,7 @@ public struct RawSyntaxLayoutView { with elements: some Collection, arena: SyntaxArena ) -> RawSyntax { - return .makeLayout( + .makeLayout( kind: raw.kind, uninitializedCount: elements.count, arena: arena diff --git a/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift b/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift index 23779d414c5..1aeade0d513 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift @@ -36,7 +36,7 @@ public extension RawSyntaxNodeProtocol { } func cast(_ syntaxType: S.Type) -> S { - return self.as(S.self)! + self.as(S.self)! } var description: String { @@ -48,7 +48,7 @@ public extension RawSyntaxNodeProtocol { } var isEmpty: Bool { - return raw.byteLength == 0 + raw.byteLength == 0 } /// Whether the tree contained by this layout has any @@ -56,7 +56,7 @@ public extension RawSyntaxNodeProtocol { /// - unexpected nodes or /// - tokens with a ``TokenDiagnostic`` of severity `error` var hasError: Bool { - return raw.recursiveFlags.contains(.hasError) + raw.recursiveFlags.contains(.hasError) } } @@ -64,7 +64,7 @@ public extension RawSyntaxNodeProtocol { extension RawSyntax: RawSyntaxNodeProtocol { @_spi(RawSyntax) public static func isKindOf(_ raw: RawSyntax) -> Bool { - return true + true } @_spi(RawSyntax) @@ -104,12 +104,12 @@ public struct RawTokenSyntax: RawSyntaxNodeProtocol { @_spi(RawSyntax) public var tokenView: RawSyntaxTokenView { - return raw.tokenView! + raw.tokenView! } @_spi(RawSyntax) public static func isKindOf(_ raw: RawSyntax) -> Bool { - return raw.kind == .token + raw.kind == .token } @_spi(RawSyntax) @@ -132,17 +132,17 @@ public struct RawTokenSyntax: RawSyntaxNodeProtocol { @_spi(RawSyntax) public var tokenKind: RawTokenKind { - return tokenView.rawKind + tokenView.rawKind } @_spi(RawSyntax) public var tokenText: SyntaxText { - return tokenView.rawText + tokenView.rawText } @_spi(RawSyntax) public var byteLength: Int { - return raw.byteLength + raw.byteLength } @_spi(RawSyntax) @@ -157,7 +157,7 @@ public struct RawTokenSyntax: RawSyntaxNodeProtocol { @_spi(RawSyntax) public var leadingTriviaByteLength: Int { - return tokenView.leadingTriviaByteLength + tokenView.leadingTriviaByteLength } @_spi(RawSyntax) @@ -167,7 +167,7 @@ public struct RawTokenSyntax: RawSyntaxNodeProtocol { @_spi(RawSyntax) public var trailingTriviaByteLength: Int { - return tokenView.trailingTriviaByteLength + tokenView.trailingTriviaByteLength } @_spi(RawSyntax) diff --git a/Sources/SwiftSyntax/Raw/RawSyntaxTokenView.swift b/Sources/SwiftSyntax/Raw/RawSyntaxTokenView.swift index 6f732f6aa05..5ff48f2822c 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntaxTokenView.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntaxTokenView.swift @@ -120,13 +120,13 @@ public struct RawSyntaxTokenView { /// Returns the leading ``Trivia`` length. @_spi(RawSyntax) public var leadingTriviaLength: SourceLength { - return SourceLength(utf8Length: leadingTriviaByteLength) + SourceLength(utf8Length: leadingTriviaByteLength) } /// Returns the trailing ``Trivia`` length. @_spi(RawSyntax) public var trailingTriviaLength: SourceLength { - return SourceLength(utf8Length: trailingTriviaByteLength) + SourceLength(utf8Length: trailingTriviaByteLength) } /// Run `body` with text of the leading trivia and return its result. @@ -160,14 +160,14 @@ public struct RawSyntaxTokenView { /// Returns the leading ``Trivia``. @_spi(RawSyntax) public func formLeadingTrivia() -> Trivia { - return Trivia(pieces: leadingRawTriviaPieces.map({ TriviaPiece(raw: $0) })) + Trivia(pieces: leadingRawTriviaPieces.map({ TriviaPiece(raw: $0) })) } /// Returns the trailing ``Trivia``. /// - Returns: nil if called on a layout node. @_spi(RawSyntax) public func formTrailingTrivia() -> Trivia { - return Trivia(pieces: trailingRawTriviaPieces.map({ TriviaPiece(raw: $0) })) + Trivia(pieces: trailingRawTriviaPieces.map({ TriviaPiece(raw: $0) })) } /// Returns a ``RawSyntax`` node with the same source text but with the token diff --git a/Sources/SwiftSyntax/SourceLength.swift b/Sources/SwiftSyntax/SourceLength.swift index 46e88e38521..72d06441391 100644 --- a/Sources/SwiftSyntax/SourceLength.swift +++ b/Sources/SwiftSyntax/SourceLength.swift @@ -32,7 +32,7 @@ public struct SourceLength: Comparable { /// Returns `true` if `lhs` is shorter than `rhs`. public static func < (lhs: SourceLength, rhs: SourceLength) -> Bool { - return lhs.utf8Length < rhs.utf8Length + lhs.utf8Length < rhs.utf8Length } /// Combine the length of two source length. diff --git a/Sources/SwiftSyntax/SourceLocation.swift b/Sources/SwiftSyntax/SourceLocation.swift index 95a9de62f39..70f4e7c9913 100644 --- a/Sources/SwiftSyntax/SourceLocation.swift +++ b/Sources/SwiftSyntax/SourceLocation.swift @@ -235,14 +235,14 @@ public final class SourceLocationConverter { self.fileName = file self.source = Array(source.utf8) (self.lines, endOfFile) = self.source.withUnsafeBufferPointer { buf in - return computeLines(SyntaxText(buffer: buf)) + computeLines(SyntaxText(buffer: buf)) } precondition(source.utf8.count == endOfFile.utf8Offset) } /// Execute the body with an array that contains each source line. func withSourceLines(_ body: ([SyntaxText]) throws -> T) rethrows -> T { - return try source.withUnsafeBufferPointer { (sourcePointer: UnsafeBufferPointer) in + try source.withUnsafeBufferPointer { (sourcePointer: UnsafeBufferPointer) in var result: [SyntaxText] = [] var previousLoc = AbsolutePosition.startOfFile precondition(lines.first == AbsolutePosition.startOfFile) @@ -262,7 +262,7 @@ public final class SourceLocationConverter { /// Return the source lines of the file as `String`s. /// Because `String` cannot model invalid UTF-8, the concatenation of these source lines might not be source-accurate in case there are Unicode errors in the source file, but for most practical purposes, this should not pose an issue. public var sourceLines: [String] { - return withSourceLines { syntaxTextLines in + withSourceLines { syntaxTextLines in return syntaxTextLines.map { String(syntaxText: $0) } } } @@ -365,7 +365,7 @@ public final class SourceLocationConverter { /// Returns false if the `position` is out-of-bounds for the file. public func isValid(position pos: AbsolutePosition) -> Bool { - return pos >= .startOfFile && pos <= self.endOfFile + pos >= .startOfFile && pos <= self.endOfFile } /// Returns false if the `line`/`column` pair is out-of-bounds for the file or @@ -458,7 +458,7 @@ public extension SyntaxProtocol { converter: SourceLocationConverter, afterLeadingTrivia: Bool = true ) -> SourceLocation { - return _syntaxNode.startLocation( + _syntaxNode.startLocation( converter: converter, afterLeadingTrivia: afterLeadingTrivia ) @@ -474,7 +474,7 @@ public extension SyntaxProtocol { converter: SourceLocationConverter, afterTrailingTrivia: Bool = false ) -> SourceLocation { - return _syntaxNode.endLocation( + _syntaxNode.endLocation( converter: converter, afterTrailingTrivia: afterTrailingTrivia ) @@ -493,7 +493,7 @@ public extension SyntaxProtocol { afterLeadingTrivia: Bool = true, afterTrailingTrivia: Bool = false ) -> SourceRange { - return _syntaxNode.sourceRange( + _syntaxNode.sourceRange( converter: converter, afterLeadingTrivia: afterLeadingTrivia, afterTrailingTrivia: afterTrailingTrivia @@ -580,7 +580,7 @@ fileprivate extension SyntaxText { } func containsSwiftNewline() -> Bool { - return self.contains { $0 == 10 || $0 == 13 } + self.contains { $0 == 10 || $0 == 13 } } } diff --git a/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift b/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift index 2af9197c7db..79daeaa6904 100644 --- a/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift +++ b/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift @@ -34,7 +34,7 @@ extension ClosureSignatureSyntax { extension ClosureSignatureSyntax.ParameterClause { @available(*, deprecated, renamed: "parameterClause") public static func input(_ parameterClause: ClosureParameterClauseSyntax) -> Self { - return .parameterClause(parameterClause) + .parameterClause(parameterClause) } } @@ -42,7 +42,7 @@ public extension DeclGroupSyntax { @available(*, deprecated, renamed: "memberBlock") var members: MemberDeclBlockSyntax { get { - return memberBlock + memberBlock } set(value) { memberBlock = value @@ -54,7 +54,7 @@ public extension FreestandingMacroExpansionSyntax { @available(*, deprecated, renamed: "pound") var poundToken: TokenSyntax { get { - return pound + pound } set { pound = newValue @@ -64,7 +64,7 @@ public extension FreestandingMacroExpansionSyntax { @available(*, deprecated, renamed: "macroName") var macro: TokenSyntax { get { - return macroName + macroName } set { macroName = newValue @@ -74,7 +74,7 @@ public extension FreestandingMacroExpansionSyntax { @available(*, deprecated, renamed: "genericArgumentClause") var genericArguments: GenericArgumentClauseSyntax? { get { - return genericArgumentClause + genericArgumentClause } set { genericArgumentClause = newValue @@ -84,7 +84,7 @@ public extension FreestandingMacroExpansionSyntax { @available(*, deprecated, renamed: "arguments") var argumentList: LabeledExprListSyntax { get { - return arguments + arguments } set { arguments = newValue @@ -104,7 +104,7 @@ extension KeyPathPropertyComponentSyntax { @available(*, deprecated, renamed: "declName.baseName") public var identifier: TokenSyntax { get { - return declName.baseName + declName.baseName } set { declName.baseName = newValue @@ -114,7 +114,7 @@ extension KeyPathPropertyComponentSyntax { @available(*, deprecated, renamed: "declName.argumentNames") public var declNameArguments: DeclNameArgumentsSyntax? { get { - return declName.argumentNames + declName.argumentNames } set { declName.argumentNames = newValue @@ -126,7 +126,7 @@ extension NamedDeclSyntax { @available(*, deprecated, renamed: "name") public var identifier: TokenSyntax { get { - return self.name + self.name } set { self.name = newValue @@ -138,7 +138,7 @@ extension MemberAccessExprSyntax { @available(*, deprecated, renamed: "declName.baseName") public var name: TokenSyntax { get { - return declName.baseName + declName.baseName } set { declName.baseName = newValue @@ -148,7 +148,7 @@ extension MemberAccessExprSyntax { @available(*, deprecated, renamed: "declName.argumentNames") public var declNameArguments: DeclNameArgumentsSyntax? { get { - return declName.argumentNames + declName.argumentNames } set { declName.argumentNames = newValue @@ -192,69 +192,69 @@ extension MemberAccessExprSyntax { public extension SyntaxProtocol { @available(*, deprecated, message: "Use detached computed property instead.") func detach() -> Self { - return detached + detached } } public extension TokenKind { @available(*, deprecated, renamed: "regexPoundDelimiter") static func extendedRegexDelimiter(_ text: String) -> TokenKind { - return .regexPoundDelimiter(text) + .regexPoundDelimiter(text) } @available(*, deprecated, renamed: "floatLiteral") static func floatingLiteral(_ text: String) -> TokenKind { - return .floatLiteral(text) + .floatLiteral(text) } @available(*, deprecated, renamed: "leftSquare") static var leftSquareBracket: TokenKind { - return .leftSquare + .leftSquare } @available(*, deprecated, renamed: "poundAvailable") static var poundAvailableKeyword: TokenKind { - return .poundAvailable + .poundAvailable } @available(*, deprecated, renamed: "poundElse") static var poundElseKeyword: TokenKind { - return .poundElse + .poundElse } @available(*, deprecated, renamed: "poundElseif") static var poundElseifKeyword: TokenKind { - return .poundElseif + .poundElseif } @available(*, deprecated, renamed: "poundEndif") static var poundEndifKeyword: TokenKind { - return .poundEndif + .poundEndif } @available(*, deprecated, renamed: "poundIf") static var poundIfKeyword: TokenKind { - return .poundIf + .poundIf } @available(*, deprecated, renamed: "poundSourceLocation") static var poundSourceLocationKeyword: TokenKind { - return .poundSourceLocation + .poundSourceLocation } @available(*, deprecated, renamed: "poundUnavailable") static var poundUnavailableKeyword: TokenKind { - return .poundUnavailable + .poundUnavailable } @available(*, deprecated, renamed: "rawStringPoundDelimiter") static func rawStringDelimiter(_ text: String) -> TokenKind { - return .rawStringPoundDelimiter(text) + .rawStringPoundDelimiter(text) } @available(*, deprecated, renamed: "rightSquare") static var rightSquareBracket: TokenKind { - return .rightSquare + .rightSquare } @available(*, deprecated, renamed: "endOfFile") @@ -269,7 +269,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return regexPoundDelimiter( + regexPoundDelimiter( text, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, @@ -284,7 +284,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return floatLiteral( + floatLiteral( text, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, @@ -298,7 +298,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return .leftSquareToken( + .leftSquareToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -311,7 +311,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundAvailableToken( + poundAvailableToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -324,7 +324,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundElseToken( + poundElseToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -337,7 +337,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundElseifToken( + poundElseifToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -350,7 +350,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundEndifToken( + poundEndifToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -363,7 +363,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundIfToken( + poundIfToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -376,7 +376,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundSourceLocationToken( + poundSourceLocationToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -389,7 +389,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return poundUnavailableToken( + poundUnavailableToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -403,7 +403,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return rawStringPoundDelimiter( + rawStringPoundDelimiter( text, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, @@ -417,7 +417,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return .rightSquareToken( + .rightSquareToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence @@ -430,7 +430,7 @@ public extension TokenSyntax { trailingTrivia: Trivia = [], presence: SourcePresence = .present ) -> TokenSyntax { - return .endOfFileToken( + .endOfFileToken( leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence diff --git a/Sources/SwiftSyntax/Syntax.swift b/Sources/SwiftSyntax/Syntax.swift index 312d31daade..6997f561534 100644 --- a/Sources/SwiftSyntax/Syntax.swift +++ b/Sources/SwiftSyntax/Syntax.swift @@ -81,12 +81,12 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// The position of the start of this node's content, skipping its trivia public var positionAfterSkippingLeadingTrivia: AbsolutePosition { - return position + raw.leadingTriviaLength + position + raw.leadingTriviaLength } /// The end position of this node's content, before any trailing trivia. public var endPositionBeforeTrailingTrivia: AbsolutePosition { - return endPosition - raw.trailingTriviaLength + endPosition - raw.trailingTriviaLength } /// The end position of this node, including its trivia. @@ -191,8 +191,8 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// that ensures that the arena of`newChild` doesn’t get de-allocated before /// `newChild` has been addded to the result. func replacingChild(at index: Int, with newChild: Syntax?, arena: SyntaxArena) -> Syntax { - return withExtendedLifetime(newChild) { - return replacingChild(at: index, with: newChild?.raw, rawNodeArena: newChild?.raw.arena, allocationArena: arena) + withExtendedLifetime(newChild) { + replacingChild(at: index, with: newChild?.raw, rawNodeArena: newChild?.raw.arena, allocationArena: arena) } } @@ -224,7 +224,7 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// /// Needed for the conformance to ``SyntaxProtocol``. Just returns `self`. public var _syntaxNode: Syntax { - return self + self } @_spi(RawSyntax) @@ -253,18 +253,18 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// Note that this will incur an existential conversion. @available(*, deprecated, message: "Expression always evaluates to true") public func isProtocol(_: SyntaxProtocol.Protocol) -> Bool { - return true + true } /// Return the non-type erased version of this syntax node. /// Note that this will incur an existential conversion. public func asProtocol(_: SyntaxProtocol.Protocol) -> SyntaxProtocol { - return self.raw.kind.syntaxNodeType.init(self)! + self.raw.kind.syntaxNodeType.init(self)! } /// Add the hash value of this node’s ID to `hasher`. public func hash(into hasher: inout Hasher) { - return id.hash(into: &hasher) + id.hash(into: &hasher) } /// Returns `true` if `rhs` and `lhs` have the same ID. @@ -272,7 +272,7 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// Note `lhs` and `rhs` might have the same contents even if their IDs are /// different. See documentation on ``SyntaxIdentifier``. public static func == (lhs: Syntax, rhs: Syntax) -> Bool { - return lhs.id == rhs.id + lhs.id == rhs.id } } @@ -299,7 +299,7 @@ extension Syntax { /// Retrieve the syntax text as an array of bytes that models the input /// source even in the presence of invalid UTF-8. public var syntaxTextBytes: [UInt8] { - return raw.syntaxTextBytes + raw.syntaxTextBytes } } diff --git a/Sources/SwiftSyntax/SyntaxArena.swift b/Sources/SwiftSyntax/SyntaxArena.swift index 015b562eba4..cb50316561b 100644 --- a/Sources/SwiftSyntax/SyntaxArena.swift +++ b/Sources/SwiftSyntax/SyntaxArena.swift @@ -101,7 +101,7 @@ public class SyntaxArena { /// Allocates a buffer of `RawSyntax?` with the given count, then returns the /// uninitialized memory range as a `UnsafeMutableBufferPointer`. func allocateRawSyntaxBuffer(count: Int) -> UnsafeMutableBufferPointer { - return allocator.allocate(RawSyntax?.self, count: count) + allocator.allocate(RawSyntax?.self, count: count) } /// Allocates a buffer of ``RawTriviaPiece`` with the given count, then returns @@ -109,13 +109,13 @@ public class SyntaxArena { func allocateRawTriviaPieceBuffer( count: Int ) -> UnsafeMutableBufferPointer { - return allocator.allocate(RawTriviaPiece.self, count: count) + allocator.allocate(RawTriviaPiece.self, count: count) } /// Allocates a buffer of `UInt8` with the given count, then returns the /// uninitialized memory range as a `UnsafeMutableBufferPointer`. func allocateTextBuffer(count: Int) -> UnsafeMutableBufferPointer { - return allocator.allocate(UInt8.self, count: count) + allocator.allocate(UInt8.self, count: count) } /// Copies the contents of a ``SyntaxText`` to the memory this arena manages, @@ -192,7 +192,7 @@ public class SyntaxArena { /// "managed" means it's empty, a part of "source buffer", or in the memory /// allocated by the underlying arena. func contains(text: SyntaxText) -> Bool { - return (text.isEmpty || allocator.contains(address: text.baseAddress!)) + (text.isEmpty || allocator.contains(address: text.baseAddress!)) } } @@ -254,7 +254,7 @@ public class ParsingSyntaxArena: SyntaxArena { /// Parse `source` into a list of ``RawTriviaPiece`` using `parseTriviaFunction`. @_spi(RawSyntax) public func parseTrivia(source: SyntaxText, position: TriviaPosition) -> [RawTriviaPiece] { - return self.parseTriviaFunction(source, position) + self.parseTriviaFunction(source, position) } } @@ -289,6 +289,6 @@ struct SyntaxArenaRef: Hashable { } static func == (lhs: SyntaxArenaRef, rhs: SyntaxArenaRef) -> Bool { - return lhs._value.toOpaque() == rhs._value.toOpaque() + lhs._value.toOpaque() == rhs._value.toOpaque() } } diff --git a/Sources/SwiftSyntax/SyntaxChildren.swift b/Sources/SwiftSyntax/SyntaxChildren.swift index ffe67a40bdf..8e0304f9125 100644 --- a/Sources/SwiftSyntax/SyntaxChildren.swift +++ b/Sources/SwiftSyntax/SyntaxChildren.swift @@ -29,7 +29,7 @@ struct SyntaxChildrenIndexData: Hashable, Comparable { lhs: SyntaxChildrenIndexData, rhs: SyntaxChildrenIndexData ) -> Bool { - return lhs.indexInParent < rhs.indexInParent + lhs.indexInParent < rhs.indexInParent } fileprivate init( @@ -148,7 +148,7 @@ struct RawSyntaxChildren: BidirectionalCollection { private let parent: RawSyntax private var parentLayoutView: RawSyntaxLayoutView { - return parent.layoutView! + parent.layoutView! } /// The rootId of the tree the child nodes belong to @@ -160,11 +160,11 @@ struct RawSyntaxChildren: BidirectionalCollection { let startIndex: SyntaxChildrenIndex var endIndex: SyntaxChildrenIndex { - return nil + nil } func makeIterator() -> Iterator { - return Iterator(collection: self) + Iterator(collection: self) } /// Advance the given index by the given ``RawSyntax`` node. @@ -316,11 +316,11 @@ struct NonNilRawSyntaxChildren: BidirectionalCollection { let startIndex: SyntaxChildrenIndex var endIndex: SyntaxChildrenIndex { - return allChildren.endIndex + allChildren.endIndex } func makeIterator() -> Iterator { - return Iterator(allChildren: allChildren, viewMode: viewMode) + Iterator(allChildren: allChildren, viewMode: viewMode) } /// Advances the index to the next present node in the given collection. If @@ -386,7 +386,7 @@ struct NonNilRawSyntaxChildren: BidirectionalCollection { // contract of the index(before:) function we are not called on the start // index. The start index points to the first present node. Hence there is // a present node before us. - return Self.presentIndex( + Self.presentIndex( before: allChildren.index(before: index), in: allChildren, viewMode: viewMode @@ -432,19 +432,19 @@ public struct SyntaxChildren: BidirectionalCollection { private let parent: Syntax /// The index of the first child in this collection. - public var startIndex: SyntaxChildrenIndex { return rawChildren.startIndex } + public var startIndex: SyntaxChildrenIndex { rawChildren.startIndex } /// The index that’s one after the last element in the collection. - public var endIndex: SyntaxChildrenIndex { return rawChildren.endIndex } + public var endIndex: SyntaxChildrenIndex { rawChildren.endIndex } /// The index for the child that’s after the child at `index`. public func index(after index: SyntaxChildrenIndex) -> SyntaxChildrenIndex { - return rawChildren.index(after: index) + rawChildren.index(after: index) } /// The index for the child that’s before the child at `index`. public func index(before index: SyntaxChildrenIndex) -> SyntaxChildrenIndex { - return rawChildren.index(before: index) + rawChildren.index(before: index) } /// The syntax node at the given `index` @@ -462,7 +462,7 @@ public struct SyntaxChildren: BidirectionalCollection { /// /// If `node` is not part of this collection, returns `nil`. public func index(of node: some SyntaxProtocol) -> SyntaxChildrenIndex? { - return index(of: Syntax(node)) + index(of: Syntax(node)) } /// Return the index of `node` within this collection. diff --git a/Sources/SwiftSyntax/SyntaxCollection.swift b/Sources/SwiftSyntax/SyntaxCollection.swift index a0717bce757..13a16f96167 100644 --- a/Sources/SwiftSyntax/SyntaxCollection.swift +++ b/Sources/SwiftSyntax/SyntaxCollection.swift @@ -20,7 +20,7 @@ where Element: SyntaxProtocol, Index == SyntaxChildrenIndex { extension SyntaxCollection { public static var structure: SyntaxNodeStructure { - return .collection(Element.self) + .collection(Element.self) } private var layoutView: RawSyntaxLayoutView { @@ -58,7 +58,7 @@ extension SyntaxCollection { /// The number of elements, `present` or `missing`, in this collection. public var count: Int { - return layoutView.children.count + layoutView.children.count } /// Creates a new collection by replacing the underlying layout with a @@ -139,7 +139,7 @@ extension SyntaxCollection { /// beginning. @available(*, deprecated, message: "Create a new array of elements and construct a new collection type from those elements") public func prepending(_ syntax: Element) -> Self { - return inserting(syntax, at: 0) + inserting(syntax, at: 0) } /// Creates a new collection by inserting the provided syntax element @@ -404,34 +404,34 @@ extension SyntaxCollection { /// Conformance to `BidirectionalCollection`. extension SyntaxCollection { public func makeIterator() -> SyntaxCollectionIterator { - return SyntaxCollectionIterator(parent: Syntax(self), rawChildren: rawChildren) + SyntaxCollectionIterator(parent: Syntax(self), rawChildren: rawChildren) } private var rawChildren: RawSyntaxChildren { // We know children in a syntax collection cannot be missing. So we can // use the low-level and faster RawSyntaxChildren collection instead of // NonNilRawSyntaxChildren. - return RawSyntaxChildren(Syntax(self).absoluteRaw) + RawSyntaxChildren(Syntax(self).absoluteRaw) } public var startIndex: SyntaxChildrenIndex { - return rawChildren.startIndex + rawChildren.startIndex } public var endIndex: SyntaxChildrenIndex { - return rawChildren.endIndex + rawChildren.endIndex } public func index(after index: SyntaxChildrenIndex) -> SyntaxChildrenIndex { - return rawChildren.index(after: index) + rawChildren.index(after: index) } public func index(before index: SyntaxChildrenIndex) -> SyntaxChildrenIndex { - return rawChildren.index(before: index) + rawChildren.index(before: index) } public func distance(from start: SyntaxChildrenIndex, to end: SyntaxChildrenIndex) -> Int { - return rawChildren.distance(from: start, to: end) + rawChildren.distance(from: start, to: end) } public subscript(position: SyntaxChildrenIndex) -> Element { diff --git a/Sources/SwiftSyntax/SyntaxHashable.swift b/Sources/SwiftSyntax/SyntaxHashable.swift index 753b2806dbd..fc35e4a7b9e 100644 --- a/Sources/SwiftSyntax/SyntaxHashable.swift +++ b/Sources/SwiftSyntax/SyntaxHashable.swift @@ -17,10 +17,10 @@ public protocol SyntaxHashable: Hashable { public extension SyntaxHashable { func hash(into hasher: inout Hasher) { - return _syntaxNode.id.hash(into: &hasher) + _syntaxNode.id.hash(into: &hasher) } static func == (lhs: Self, rhs: Self) -> Bool { - return lhs._syntaxNode.id == rhs._syntaxNode.id + lhs._syntaxNode.id == rhs._syntaxNode.id } } diff --git a/Sources/SwiftSyntax/SyntaxIdentifier.swift b/Sources/SwiftSyntax/SyntaxIdentifier.swift index 6886c6bfe3f..3ad59d663b2 100644 --- a/Sources/SwiftSyntax/SyntaxIdentifier.swift +++ b/Sources/SwiftSyntax/SyntaxIdentifier.swift @@ -42,7 +42,7 @@ public struct SyntaxIndexInTree: Comparable, Hashable { /// Returns `true` if `lhs` occurs before `rhs` in the tree. public static func < (lhs: SyntaxIndexInTree, rhs: SyntaxIndexInTree) -> Bool { - return lhs.indexInTree < rhs.indexInTree + lhs.indexInTree < rhs.indexInTree } } @@ -81,7 +81,7 @@ public struct SyntaxIdentifier: Hashable { } static func forRoot(_ raw: RawSyntax) -> SyntaxIdentifier { - return .init( + .init( rootId: UInt(bitPattern: raw.pointer), indexInTree: .zero ) diff --git a/Sources/SwiftSyntax/SyntaxProtocol.swift b/Sources/SwiftSyntax/SyntaxProtocol.swift index 4b2e7bc09c1..05d9e9e68c6 100644 --- a/Sources/SwiftSyntax/SyntaxProtocol.swift +++ b/Sources/SwiftSyntax/SyntaxProtocol.swift @@ -35,7 +35,7 @@ public protocol SyntaxProtocol: CustomStringConvertible, extension SyntaxProtocol { @_spi(RawSyntax) public var raw: RawSyntax { - return _syntaxNode.raw + _syntaxNode.raw } } @@ -57,7 +57,7 @@ public extension SyntaxProtocol { /// /// - Returns: `true` if the node can be cast, `false` otherwise. func `is`(_ syntaxType: S.Type) -> Bool { - return self.as(syntaxType) != nil + self.as(syntaxType) != nil } /// Checks if the current syntax node can be upcast to ``Syntax`` node. @@ -68,7 +68,7 @@ public extension SyntaxProtocol { /// informing the user that the upcast will always succeed. @available(*, deprecated, message: "This cast will always succeed") func `is`(_ syntaxType: Syntax.Type) -> Bool { - return true + true } /// Checks if the current syntax node can be cast to its own type. @@ -79,14 +79,14 @@ public extension SyntaxProtocol { /// informing the user that the cast will always succeed. @available(*, deprecated, message: "This cast will always succeed") func `is`(_ syntaxType: Self.Type) -> Bool { - return true + true } /// Attempts to cast the current syntax node to a given specialized syntax type. /// /// - Returns: An instance of the specialized type, or `nil` if the cast fails. func `as`(_ syntaxType: S.Type) -> S? { - return S.init(self) + S.init(self) } /// Attempts to upcast the current syntax node to ``Syntax`` node.. @@ -97,7 +97,7 @@ public extension SyntaxProtocol { /// informing the user the upcast should be performed using the base node's initializer. @available(*, deprecated, message: "Use `Syntax.init` for upcasting.") func `as`(_ syntaxType: Syntax.Type) -> Syntax? { - return Syntax(self) + Syntax(self) } /// Casts the current syntax node to its own type. @@ -108,7 +108,7 @@ public extension SyntaxProtocol { /// informing the user that the cast will always succeed. @available(*, deprecated, message: "This cast will always succeed") func `as`(_ syntaxType: Self.Type) -> Self? { - return self + self } /// Force-casts the current syntax node to a given specialized syntax type. @@ -116,7 +116,7 @@ public extension SyntaxProtocol { /// - Returns: An instance of the specialized type. /// - Warning: This function will crash if the cast is not possible. Use `as` to safely attempt a cast. func cast(_ syntaxType: S.Type) -> S { - return self.as(S.self)! + self.as(S.self)! } /// Force-cast the current syntax node to ``Syntax`` node.. @@ -127,7 +127,7 @@ public extension SyntaxProtocol { /// informing the user the upcast should be performed using the base node's initializer. @available(*, deprecated, message: "Use `Syntax.init` for upcasting.") func cast(_ syntaxType: Syntax.Type) -> Syntax { - return Syntax(self) + Syntax(self) } /// Force-casts the current syntax node to its own type. @@ -138,7 +138,7 @@ public extension SyntaxProtocol { /// informing the user that the cast will always succeed. @available(*, deprecated, message: "This cast will always succeed") func cast(_ syntaxType: Self.Type) -> Self { - return self + self } } @@ -158,7 +158,7 @@ public extension SyntaxProtocol { var detached: Self { // Make sure `self` (and thus the arena of `self.raw`) can’t get deallocated // before the detached node can be created. - return withExtendedLifetime(self) { + withExtendedLifetime(self) { return Syntax(raw: self.raw, rawNodeArena: self.raw.arena).cast(Self.self) } } @@ -172,7 +172,7 @@ extension SyntaxProtocol { /// If you want to check for a node's kind and cast the node to that type, see /// `self.as(FunctionDeclSyntax.self)` or `self.as(SyntaxEnum.self)`. public var kind: SyntaxKind { - return raw.kind + raw.kind } /// The dynamic metatype of the concrete node. @@ -182,7 +182,7 @@ extension SyntaxProtocol { /// `type(of: self)` will return ``DeclSyntax``, while `syntaxNodeType` looks /// at the dynamic kind of this node and returns ``FunctionDeclSyntax``. public var syntaxNodeType: SyntaxProtocol.Type { - return self.raw.kind.syntaxNodeType + self.raw.kind.syntaxNodeType } } @@ -191,23 +191,23 @@ extension SyntaxProtocol { public extension SyntaxProtocol { /// A sequence over the children of this node. func children(viewMode: SyntaxTreeViewMode) -> SyntaxChildren { - return SyntaxChildren(_syntaxNode, viewMode: viewMode) + SyntaxChildren(_syntaxNode, viewMode: viewMode) } /// The index of this node in a ``SyntaxChildren`` collection. @available(*, deprecated, message: "Use index(of:) on the collection that contains this node") var index: SyntaxChildrenIndex { - return indexInParent + indexInParent } /// The index of this node in a ``SyntaxChildren`` collection. internal var indexInParent: SyntaxChildrenIndex { - return SyntaxChildrenIndex(Syntax(self).absoluteInfo) + SyntaxChildrenIndex(Syntax(self).absoluteInfo) } /// The parent of this syntax node, or `nil` if this node is the root. var parent: Syntax? { - return Syntax(self).parent + Syntax(self).parent } /// The root of the tree in which this node resides. @@ -221,7 +221,7 @@ public extension SyntaxProtocol { /// Whether or not this node has a parent. var hasParent: Bool { - return parent != nil + parent != nil } var keyPathInParent: AnyKeyPath? { @@ -236,7 +236,7 @@ public extension SyntaxProtocol { @available(*, deprecated, message: "Use previousToken(viewMode:) instead") var previousToken: TokenSyntax? { - return self.previousToken(viewMode: .sourceAccurate) + self.previousToken(viewMode: .sourceAccurate) } } @@ -265,7 +265,7 @@ public extension SyntaxProtocol { @available(*, deprecated, message: "Use nextToken(viewMode:) instead") var nextToken: TokenSyntax? { - return self.nextToken(viewMode: .sourceAccurate) + self.nextToken(viewMode: .sourceAccurate) } /// Recursively walks through the tree to find the next token semantically @@ -287,7 +287,7 @@ public extension SyntaxProtocol { @available(*, deprecated, message: "Use firstToken(viewMode: .sourceAccurate) instead") var firstToken: TokenSyntax? { - return self.firstToken(viewMode: .sourceAccurate) + self.firstToken(viewMode: .sourceAccurate) } /// Returns the first token node that is part of this syntax node. @@ -307,7 +307,7 @@ public extension SyntaxProtocol { @available(*, deprecated, message: "Use lastToken(viewMode: .sourceAccurate) instead") var lastToken: TokenSyntax? { - return self.lastToken(viewMode: .sourceAccurate) + self.lastToken(viewMode: .sourceAccurate) } /// Returns the last token node that is part of this syntax node. @@ -327,7 +327,7 @@ public extension SyntaxProtocol { /// Sequence of tokens that are part of this Syntax node. func tokens(viewMode: SyntaxTreeViewMode) -> TokenSequence { - return TokenSequence(_syntaxNode, viewMode: viewMode) + TokenSequence(_syntaxNode, viewMode: viewMode) } /// Find the syntax token at the given absolute position within this @@ -362,22 +362,22 @@ public extension SyntaxProtocol { /// - unexpected nodes or /// - tokens with a ``TokenDiagnostic`` of severity ``TokenDiagnostic/Severity-swift.enum/error``. var hasError: Bool { - return raw.hasError + raw.hasError } /// Whether the tree contained by this layout has any tokens with a /// ``TokenDiagnostic`` of severity `warning`. var hasWarning: Bool { - return raw.recursiveFlags.contains(.hasWarning) + raw.recursiveFlags.contains(.hasWarning) } /// Whether this tree contains a missing token or unexpected node. var hasSequenceExpr: Bool { - return raw.recursiveFlags.contains(.hasSequenceExpr) + raw.recursiveFlags.contains(.hasSequenceExpr) } var hasMaximumNestingLevelOverflow: Bool { - return raw.recursiveFlags.contains(.hasMaximumNestingLevelOverflow) + raw.recursiveFlags.contains(.hasMaximumNestingLevelOverflow) } } @@ -388,28 +388,28 @@ public extension SyntaxProtocol { /// is with leading trivia, the position points to the start of the leading /// trivia. var position: AbsolutePosition { - return Syntax(self).position + Syntax(self).position } /// The absolute position of the starting point of this node, skipping any /// leading trivia attached to the first token syntax. var positionAfterSkippingLeadingTrivia: AbsolutePosition { - return Syntax(self).positionAfterSkippingLeadingTrivia + Syntax(self).positionAfterSkippingLeadingTrivia } /// The end position of this node's content, before any trailing trivia. var endPositionBeforeTrailingTrivia: AbsolutePosition { - return Syntax(self).endPositionBeforeTrailingTrivia + Syntax(self).endPositionBeforeTrailingTrivia } /// The end position of this node, including its trivia. var endPosition: AbsolutePosition { - return Syntax(self).endPosition + Syntax(self).endPosition } /// The length of this node including all of its trivia. var totalLength: SourceLength { - return raw.totalLength + raw.totalLength } /// The length this node takes up spelled out in the source, excluding its @@ -418,12 +418,12 @@ public extension SyntaxProtocol { /// - Note: If this node consists of multiple tokens, only the first token’s /// leading and the last token’s trailing trivia will be trimmed. var trimmedLength: SourceLength { - return raw.trimmedLength + raw.trimmedLength } /// The byte source range of this node including leading and trailing trivia. var totalByteRange: ByteSourceRange { - return ByteSourceRange(offset: position.utf8Offset, length: totalLength.utf8Length) + ByteSourceRange(offset: position.utf8Offset, length: totalLength.utf8Length) } /// The byte source range of this node excluding leading and trailing trivia. @@ -431,7 +431,7 @@ public extension SyntaxProtocol { /// - Note: If this node consists of multiple tokens, only the first token’s /// leading and the last token’s trailing trivia will be trimmed. var trimmedByteRange: ByteSourceRange { - return ByteSourceRange( + ByteSourceRange( offset: positionAfterSkippingLeadingTrivia.utf8Offset, length: trimmedLength.utf8Length ) @@ -439,24 +439,24 @@ public extension SyntaxProtocol { @available(*, deprecated, renamed: "trimmedLength") var contentLength: SourceLength { - return trimmedLength + trimmedLength } @available(*, deprecated, renamed: "totalByteRange") var byteRange: ByteSourceRange { - return ByteSourceRange(offset: position.utf8Offset, length: totalLength.utf8Length) + ByteSourceRange(offset: position.utf8Offset, length: totalLength.utf8Length) } /// The textual byte length of this node including leading and trailing trivia. @available(*, deprecated, message: "Use totalLength.utf8Length") var byteSize: Int { - return totalLength.utf8Length + totalLength.utf8Length } /// The textual byte length of this node excluding leading and trailing trivia. @available(*, deprecated, message: "Use trimmedLength.utf8Length") var byteSizeAfterTrimmingTrivia: Int { - return trimmedLength.utf8Length + trimmedLength.utf8Length } } @@ -474,7 +474,7 @@ public extension SyntaxProtocol { /// ``` var leadingTrivia: Trivia { get { - return raw.formLeadingTrivia() + raw.formLeadingTrivia() } set { self = Syntax(self).withLeadingTrivia(newValue, arena: SyntaxArena()).cast(Self.self) @@ -492,7 +492,7 @@ public extension SyntaxProtocol { /// ``` var trailingTrivia: Trivia { get { - return raw.formTrailingTrivia() + raw.formTrailingTrivia() } set { self = Syntax(self).withTrailingTrivia(newValue, arena: SyntaxArena()).cast(Self.self) @@ -501,12 +501,12 @@ public extension SyntaxProtocol { /// The length this node's leading trivia takes up spelled out in source. var leadingTriviaLength: SourceLength { - return raw.leadingTriviaLength + raw.leadingTriviaLength } /// The length this node's trailing trivia takes up spelled out in source. var trailingTriviaLength: SourceLength { - return raw.trailingTriviaLength + raw.trailingTriviaLength } } @@ -521,13 +521,13 @@ public extension SyntaxProtocol { /// byte-accurate representation of this node in the presence of /// invalid UTF-8. var description: String { - return Syntax(self).raw.description + Syntax(self).raw.description } /// Retrieve the syntax text as an array of bytes that models the input /// source even in the presence of invalid UTF-8. var syntaxTextBytes: [UInt8] { - return Syntax(self).raw.syntaxTextBytes + Syntax(self).raw.syntaxTextBytes } /// Prints the raw value of this node to the provided stream. @@ -541,14 +541,14 @@ public extension SyntaxProtocol { /// node and the trailing trivia of the last token in the node. var trimmed: Self { // TODO: Should only need one new node here - return self.with(\.leadingTrivia, []).with(\.trailingTrivia, []) + self.with(\.leadingTrivia, []).with(\.trailingTrivia, []) } /// A copy of this node with pieces that match `matching` trimmed from the /// leading trivia of the first token and trailing trivia of the last token. func trimmed(matching filter: (TriviaPiece) -> Bool) -> Self { // TODO: Should only need one new node here - return self.with( + self.with( \.leadingTrivia, Trivia(pieces: leadingTrivia.pieces.drop(while: filter)) ).with( @@ -562,7 +562,7 @@ public extension SyntaxProtocol { var trimmedDescription: String { // TODO: We shouldn't need to create to copies just to get the trimmed // description. - return self.trimmed.description + self.trimmed.description } /// The description of this node with pieces that match `matching` removed @@ -571,7 +571,7 @@ public extension SyntaxProtocol { func trimmedDescription(matching filter: (TriviaPiece) -> Bool) -> String { // TODO: We shouldn't need to create to copies just to get the trimmed // description. - return self.trimmed(matching: filter).description + self.trimmed(matching: filter).description } } @@ -582,12 +582,12 @@ public extension SyntaxProtocol { /// underlying tokens, e.g. an empty CodeBlockItemList. @available(*, deprecated, message: "Check children(viewMode: .all).isEmpty instead") var isImplicit: Bool { - return raw.isEmpty + raw.isEmpty } /// Returns a value representing the unique identity of the node. var id: SyntaxIdentifier { - return Syntax(self).id + Syntax(self).id } } @@ -603,7 +603,7 @@ public extension SyntaxProtocol { var customMirror: Mirror { // Suppress printing of children when doing `po node` in the debugger. // `debugDescription` already prints them in a nicer way. - return Mirror(self, children: [:]) + Mirror(self, children: [:]) } /// Returns a summarized dump of this node. diff --git a/Sources/SwiftSyntax/SyntaxText.swift b/Sources/SwiftSyntax/SyntaxText.swift index c5613bee381..2764600b60c 100644 --- a/Sources/SwiftSyntax/SyntaxText.swift +++ b/Sources/SwiftSyntax/SyntaxText.swift @@ -107,7 +107,7 @@ public struct SyntaxText { /// Returns `true` if `other` is a substring of this ``SyntaxText``. public func contains(_ other: SyntaxText) -> Bool { - return firstRange(of: other) != nil + firstRange(of: other) != nil } /// Finds and returns the range of the first occurrence of `other` within this @@ -166,7 +166,7 @@ extension SyntaxText: RandomAccessCollection { /// Access the byte at `index`. public subscript(index: Index) -> Element { - get { return buffer[index] } + get { buffer[index] } } } diff --git a/Sources/SwiftSyntax/TokenDiagnostic.swift b/Sources/SwiftSyntax/TokenDiagnostic.swift index 0a48338c265..f525a4e3b79 100644 --- a/Sources/SwiftSyntax/TokenDiagnostic.swift +++ b/Sources/SwiftSyntax/TokenDiagnostic.swift @@ -153,6 +153,6 @@ public struct TokenDiagnostic: Hashable { /// The severity of the diagnostic, i.e. whether it’s a warning or error. public var severity: Severity { - return kind.severity + kind.severity } } diff --git a/Sources/SwiftSyntax/TokenSequence.swift b/Sources/SwiftSyntax/TokenSequence.swift index 7c78340a561..37802ebcf7a 100644 --- a/Sources/SwiftSyntax/TokenSequence.swift +++ b/Sources/SwiftSyntax/TokenSequence.swift @@ -51,19 +51,19 @@ public struct TokenSequence: Sequence { /// Create an iterator that iterates over all the tokens in the sequence. public func makeIterator() -> Iterator { - return Iterator(node.firstToken(viewMode: viewMode), endToken: node.lastToken(viewMode: viewMode), viewMode: viewMode) + Iterator(node.firstToken(viewMode: viewMode), endToken: node.lastToken(viewMode: viewMode), viewMode: viewMode) } /// Iterate the tokens in reverse order. public func reversed() -> ReversedTokenSequence { - return ReversedTokenSequence(node, viewMode: viewMode) + ReversedTokenSequence(node, viewMode: viewMode) } } extension TokenSequence: CustomReflectable { /// A custom mirror for ``TokenSequence`` that shows all elements in the sequence. public var customMirror: Mirror { - return Mirror(self, unlabeledChildren: self.map { $0 }) + Mirror(self, unlabeledChildren: self.map { $0 }) } } @@ -108,18 +108,18 @@ public struct ReversedTokenSequence: Sequence { /// Create an iterator that iterates over all the tokens in the sequence. public func makeIterator() -> Iterator { - return Iterator(node.lastToken(viewMode: viewMode), startPosition: node.position, viewMode: viewMode) + Iterator(node.lastToken(viewMode: viewMode), startPosition: node.position, viewMode: viewMode) } /// Iterate over the tokens in source order. public func reversed() -> TokenSequence { - return TokenSequence(node, viewMode: viewMode) + TokenSequence(node, viewMode: viewMode) } } extension ReversedTokenSequence: CustomReflectable { /// A custom mirror for ``ReversedTokenSequence`` that shows all elements in the sequence. public var customMirror: Mirror { - return Mirror(self, unlabeledChildren: self.map { $0 }) + Mirror(self, unlabeledChildren: self.map { $0 }) } } diff --git a/Sources/SwiftSyntax/TokenSyntax.swift b/Sources/SwiftSyntax/TokenSyntax.swift index f7576677bb4..6519e724e4d 100644 --- a/Sources/SwiftSyntax/TokenSyntax.swift +++ b/Sources/SwiftSyntax/TokenSyntax.swift @@ -30,7 +30,7 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// properties of the token. @_spi(RawSyntax) public var tokenView: RawSyntaxTokenView { - return raw.tokenView! + raw.tokenView! } /// If `node` is a token, return the ``TokenSyntax`` that represents it. @@ -63,7 +63,7 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// Whether the token is present or missing. public var presence: SourcePresence { get { - return tokenView.presence + tokenView.presence } set { self = Syntax(self).withPresence(newValue, arena: SyntaxArena()).cast(TokenSyntax.self) @@ -72,13 +72,13 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// The text of the token as written in the source code, without any trivia. public var text: String { - return tokenKind.text + tokenKind.text } /// The leading trivia (spaces, newlines, etc.) associated with this token. public var leadingTrivia: Trivia { get { - return tokenView.formLeadingTrivia() + tokenView.formLeadingTrivia() } set { self = Syntax(self).withLeadingTrivia(newValue, arena: SyntaxArena()).cast(TokenSyntax.self) @@ -88,7 +88,7 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// The trailing trivia (spaces, newlines, etc.) associated with this token. public var trailingTrivia: Trivia { get { - return tokenView.formTrailingTrivia() + tokenView.formTrailingTrivia() } set { self = Syntax(self).withTrailingTrivia(newValue, arena: SyntaxArena()).cast(TokenSyntax.self) @@ -98,7 +98,7 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// The kind of token this node represents. public var tokenKind: TokenKind { get { - return tokenView.formKind() + tokenView.formKind() } set { guard raw.kind == .token else { @@ -113,22 +113,22 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// The length this node takes up spelled out in the source, excluding its /// leading or trailing trivia. public var trimmedLength: SourceLength { - return tokenView.trimmedLength + tokenView.trimmedLength } /// The length this node's leading trivia takes up spelled out in source. public var leadingTriviaLength: SourceLength { - return tokenView.leadingTriviaLength + tokenView.leadingTriviaLength } /// The length this node's trailing trivia takes up spelled out in source. public var trailingTriviaLength: SourceLength { - return tokenView.trailingTriviaLength + tokenView.trailingTriviaLength } /// The length of this node including all of its trivia. public var totalLength: SourceLength { - return raw.totalLength + raw.totalLength } /// A token by itself has no structure, so we represent its structure by an @@ -138,12 +138,12 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// ``SyntaxNodeStructure/SyntaxChoice/token(_:)`` case for the token and those /// choices represent the token kinds the token might have. public static var structure: SyntaxNodeStructure { - return .layout([]) + .layout([]) } /// If the token has a lexical error, the type of the error. public var tokenDiagnostic: TokenDiagnostic? { - return tokenView.tokenDiagnostic + tokenView.tokenDiagnostic } /// Checks if the current leaf syntax node can be cast to a different specified type. @@ -154,7 +154,7 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") public func `is`(_ syntaxType: S.Type) -> Bool { - return false + false } /// Attempts to cast the current leaf syntax node to a different specified type. @@ -165,7 +165,7 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") public func `as`(_ syntaxType: S.Type) -> S? { - return nil + nil } /// Force-casts the current leaf syntax node to a different specified type. @@ -185,7 +185,7 @@ extension TokenSyntax: CustomReflectable { /// A custom mirror that shows the token properties in a simpler form, making /// the debug output of the token easier to read. public var customMirror: Mirror { - return Mirror( + Mirror( self, children: [ "text": text, diff --git a/Sources/SwiftSyntax/Trivia.swift b/Sources/SwiftSyntax/Trivia.swift index 2cf9b27ce58..2f85de486bb 100644 --- a/Sources/SwiftSyntax/Trivia.swift +++ b/Sources/SwiftSyntax/Trivia.swift @@ -44,13 +44,13 @@ public struct Trivia { /// The length of all the pieces in this ``Trivia``. public var sourceLength: SourceLength { - return pieces.map({ $0.sourceLength }).reduce(.zero, +) + pieces.map({ $0.sourceLength }).reduce(.zero, +) } /// Get the number of bytes this trivia needs to be represented as UTF-8. @available(*, deprecated, renamed: "sourceLength.utf8Length") public var byteSize: Int { - return sourceLength.utf8Length + sourceLength.utf8Length } /// Creates a new ``Trivia`` by appending the provided ``TriviaPiece`` to the end. @@ -96,7 +96,7 @@ public struct Trivia { /// Concatenates two collections of ``Trivia`` into one collection. public static func + (lhs: Trivia, rhs: Trivia) -> Trivia { - return lhs.appending(rhs) + lhs.appending(rhs) } /// Concatenates two collections of ``Trivia`` into the left-hand side. @@ -110,22 +110,22 @@ extension Trivia: Equatable {} extension Trivia: Collection { /// The index of the first ``TriviaPiece`` within this trivia. public var startIndex: Int { - return pieces.startIndex + pieces.startIndex } /// The index one after the last ``TriviaPiece`` within this trivia. public var endIndex: Int { - return pieces.endIndex + pieces.endIndex } /// The index of the trivia piece after the piece at `index`. public func index(after index: Int) -> Int { - return pieces.index(after: index) + pieces.index(after: index) } /// The ``TriviaPiece`` at `index`. public subscript(_ index: Int) -> TriviaPiece { - return pieces[index] + pieces[index] } } diff --git a/Sources/SwiftSyntax/Utils.swift b/Sources/SwiftSyntax/Utils.swift index 856bac5ab6f..37d49d47545 100644 --- a/Sources/SwiftSyntax/Utils.swift +++ b/Sources/SwiftSyntax/Utils.swift @@ -20,19 +20,19 @@ public struct ByteSourceRange: Equatable { } public var endOffset: Int { - return offset + length + offset + length } public var isEmpty: Bool { - return length == 0 + length == 0 } public func intersectsOrTouches(_ other: ByteSourceRange) -> Bool { - return self.endOffset >= other.offset && self.offset <= other.endOffset + self.endOffset >= other.offset && self.offset <= other.endOffset } public func intersects(_ other: ByteSourceRange) -> Bool { - return self.endOffset > other.offset && self.offset < other.endOffset + self.endOffset > other.offset && self.offset < other.endOffset } /// Returns the byte range for the overlapping region between two ranges. @@ -53,15 +53,15 @@ public struct IncrementalEdit: Equatable { /// The length of the edit replacement in UTF8 bytes. public let replacementLength: Int - public var offset: Int { return range.offset } + public var offset: Int { range.offset } - public var length: Int { return range.length } + public var length: Int { range.length } - public var endOffset: Int { return range.endOffset } + public var endOffset: Int { range.endOffset } /// After the edit has been applied the range of the replacement text. public var replacementRange: ByteSourceRange { - return ByteSourceRange(offset: offset, length: replacementLength) + ByteSourceRange(offset: offset, length: replacementLength) } public init(range: ByteSourceRange, replacementLength: Int) { @@ -75,11 +75,11 @@ public struct IncrementalEdit: Equatable { } public func intersectsOrTouchesRange(_ other: ByteSourceRange) -> Bool { - return self.range.intersectsOrTouches(other) + self.range.intersectsOrTouches(other) } public func intersectsRange(_ other: ByteSourceRange) -> Bool { - return self.range.intersects(other) + self.range.intersects(other) } } diff --git a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift index 6c4c3a302b9..19629e64382 100644 --- a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift +++ b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift @@ -259,7 +259,7 @@ fileprivate extension Unicode.Scalar { var isPrintableASCII: Bool { // Exclude non-printables before the space character U+20, and anything // including and above the DEL character U+7F. - return self.value >= 0x20 && self.value < 0x7F + self.value >= 0x20 && self.value < 0x7F } } diff --git a/Sources/SwiftSyntaxBuilder/Indenter.swift b/Sources/SwiftSyntaxBuilder/Indenter.swift index da8316871f2..590b1e69b94 100644 --- a/Sources/SwiftSyntaxBuilder/Indenter.swift +++ b/Sources/SwiftSyntaxBuilder/Indenter.swift @@ -39,11 +39,11 @@ public class Indenter: SyntaxRewriter { _ node: SyntaxType, indentation: Trivia ) -> SyntaxType { - return Indenter(indentation: indentation).rewrite(node).as(SyntaxType.self)! + Indenter(indentation: indentation).rewrite(node).as(SyntaxType.self)! } public override func visit(_ token: TokenSyntax) -> TokenSyntax { - return TokenSyntax( + TokenSyntax( token.tokenKind, leadingTrivia: token.leadingTrivia.indented(indentation: indentation), trailingTrivia: token.trailingTrivia.indented(indentation: indentation), diff --git a/Sources/SwiftSyntaxBuilder/ResultBuilderExtensions.swift b/Sources/SwiftSyntaxBuilder/ResultBuilderExtensions.swift index ebf0a04690d..8256bfbdbee 100644 --- a/Sources/SwiftSyntaxBuilder/ResultBuilderExtensions.swift +++ b/Sources/SwiftSyntaxBuilder/ResultBuilderExtensions.swift @@ -14,39 +14,39 @@ import SwiftSyntax extension CodeBlockItemListBuilder { public static func buildExpression(_ expression: some ExprSyntaxProtocol) -> Component { - return buildExpression(CodeBlockItemSyntax(item: .expr(ExprSyntax(expression)))) + buildExpression(CodeBlockItemSyntax(item: .expr(ExprSyntax(expression)))) } public static func buildExpression(_ expression: some StmtSyntaxProtocol) -> Component { - return buildExpression(CodeBlockItemSyntax(item: .stmt(StmtSyntax(expression)))) + buildExpression(CodeBlockItemSyntax(item: .stmt(StmtSyntax(expression)))) } public static func buildExpression(_ expression: some DeclSyntaxProtocol) -> Component { - return buildExpression(CodeBlockItemSyntax(item: .decl(DeclSyntax(expression)))) + buildExpression(CodeBlockItemSyntax(item: .decl(DeclSyntax(expression)))) } } extension ConditionElementListBuilder { public static func buildExpression(_ expression: some ExprSyntaxProtocol) -> Component { - return buildExpression(ConditionElementSyntax(condition: .expression(ExprSyntax(expression)))) + buildExpression(ConditionElementSyntax(condition: .expression(ExprSyntax(expression)))) } public static func buildExpression(_ expression: AvailabilityConditionSyntax) -> Component { - return buildExpression(ConditionElementSyntax(condition: .availability(expression))) + buildExpression(ConditionElementSyntax(condition: .availability(expression))) } public static func buildExpression(_ expression: MatchingPatternConditionSyntax) -> Component { - return buildExpression(ConditionElementSyntax(condition: .matchingPattern(expression))) + buildExpression(ConditionElementSyntax(condition: .matchingPattern(expression))) } public static func buildExpression(_ expression: OptionalBindingConditionSyntax) -> Component { - return buildExpression(ConditionElementSyntax(condition: .optionalBinding(expression))) + buildExpression(ConditionElementSyntax(condition: .optionalBinding(expression))) } } extension MemberBlockItemListBuilder { public static func buildExpression(_ expression: some DeclSyntaxProtocol) -> Component { - return buildExpression(MemberBlockItemSyntax(decl: expression)) + buildExpression(MemberBlockItemSyntax(decl: expression)) } } diff --git a/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift b/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift index 7c3dddd83b1..0587369efb7 100644 --- a/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift +++ b/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift @@ -166,7 +166,7 @@ enum SyntaxStringInterpolationError: Error, CustomStringConvertible { case diagnostics([Diagnostic], tree: Syntax) static func producedInvalidNodeType(expectedType: SyntaxProtocol.Type, actualNode: S) -> Self { - return .producedInvalidNodeType(expectedType: expectedType, actualType: type(of: actualNode)) + .producedInvalidNodeType(expectedType: expectedType, actualType: type(of: actualNode)) } var description: String { diff --git a/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift b/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift index f3794d7ebe9..326be7b919f 100644 --- a/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift +++ b/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift @@ -97,6 +97,6 @@ extension Trivia { extension SyntaxProtocol { /// This syntax node with all indentation removed. var withIndentationRemoved: Self { - return IndentationStripper().rewrite(self).cast(Self.self) + IndentationStripper().rewrite(self).cast(Self.self) } } diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift b/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift index 98383715293..2e93316a5b0 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift @@ -277,7 +277,7 @@ extension MacroDeclSyntax { definition: MacroExpansionExprSyntax, replacements: [MacroDefinition.Replacement] ) -> ExprSyntax { - return expand( + expand( argumentList: node.arguments, definition: definition, replacements: replacements diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift index 3cf445c1f26..d3a77ac5326 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift @@ -376,7 +376,7 @@ struct MacroSystem { /// Look for a macro with the given name. func lookup(_ macroName: String) -> Macro.Type? { - return macros[macroName] + macros[macroName] } } @@ -437,10 +437,10 @@ private enum MacroApplicationError: DiagnosticMessage, Error { case malformedAccessor var diagnosticID: MessageID { - return MessageID(domain: diagnosticDomain, id: "\(self)") + MessageID(domain: diagnosticDomain, id: "\(self)") } - var severity: DiagnosticSeverity { return .error } + var severity: DiagnosticSeverity { .error } var message: String { switch self { @@ -679,7 +679,7 @@ extension MacroApplication { attachedTo decl: DeclSyntax, ofType: MacroType.Type ) -> [(attributeNode: AttributeSyntax, definition: MacroType)] { - return macroAttributes(attachedTo: decl) + macroAttributes(attachedTo: decl) .compactMap { (attributeNode: AttributeSyntax, definition: Macro.Type) in if let macroType = definition as? MacroType { return (attributeNode, macroType) @@ -722,8 +722,8 @@ extension MacroApplication { /// /// - Returns: The macro-synthesized peers private func expandMemberDeclPeers(of decl: DeclSyntax) -> [MemberBlockItemSyntax] { - return expandMacros(attachedTo: decl, ofType: PeerMacro.Type.self) { attributeNode, definition in - return try expandPeerMacroMember( + expandMacros(attachedTo: decl, ofType: PeerMacro.Type.self) { attributeNode, definition in + try expandPeerMacroMember( definition: definition, attributeNode: attributeNode, attachedTo: decl, @@ -742,8 +742,8 @@ extension MacroApplication { /// /// - Returns: The macro-synthesized peers private func expandCodeBlockPeers(of decl: DeclSyntax) -> [CodeBlockItemSyntax] { - return expandMacros(attachedTo: decl, ofType: PeerMacro.Type.self) { attributeNode, definition in - return try expandPeerMacroCodeItem( + expandMacros(attachedTo: decl, ofType: PeerMacro.Type.self) { attributeNode, definition in + try expandPeerMacroCodeItem( definition: definition, attributeNode: attributeNode, attachedTo: decl, @@ -757,8 +757,8 @@ extension MacroApplication { /// /// - Returns: The macro-synthesized extensions private func expandExtensions(of decl: DeclSyntax) -> [CodeBlockItemSyntax] { - return expandMacros(attachedTo: decl, ofType: ExtensionMacro.Type.self) { attributeNode, definition in - return try expandExtensionMacro( + expandMacros(attachedTo: decl, ofType: ExtensionMacro.Type.self) { attributeNode, definition in + try expandExtensionMacro( definition: definition, attributeNode: attributeNode, attachedTo: decl, @@ -770,8 +770,8 @@ extension MacroApplication { /// Expand all 'member' macros attached to `decl`. private func expandMembers(of decl: DeclSyntax) -> [MemberBlockItemSyntax] { - return expandMacros(attachedTo: decl, ofType: MemberMacro.Type.self) { attributeNode, definition in - return try expandMemberMacro( + expandMacros(attachedTo: decl, ofType: MemberMacro.Type.self) { attributeNode, definition in + try expandMemberMacro( definition: definition, attributeNode: attributeNode, attachedTo: decl, @@ -790,8 +790,8 @@ extension MacroApplication { of decl: DeclSyntax, parentDecl: DeclSyntax ) -> [AttributeListSyntax.Element] { - return expandMacros(attachedTo: parentDecl, ofType: MemberAttributeMacro.Type.self) { attributeNode, definition in - return try expandMemberAttributeMacro( + expandMacros(attachedTo: parentDecl, ofType: MemberAttributeMacro.Type.self) { attributeNode, definition in + try expandMemberAttributeMacro( definition: definition, attributeNode: attributeNode, attachedTo: parentDecl, @@ -908,8 +908,8 @@ extension MacroApplication { /// } /// ``` func expandCodeBlockItem(node: CodeBlockItemSyntax) -> MacroExpansionResult { - return expandFreestandingMacro(node.item.asProtocol(FreestandingMacroExpansionSyntax.self)) { macro, node in - return try expandFreestandingCodeItemList( + expandFreestandingMacro(node.item.asProtocol(FreestandingMacroExpansionSyntax.self)) { macro, node in + try expandFreestandingCodeItemList( definition: macro, node: node, in: context, @@ -927,8 +927,8 @@ extension MacroApplication { /// } /// ``` func expandMemberDecl(node: MemberBlockItemSyntax) -> MacroExpansionResult { - return expandFreestandingMacro(node.decl.as(MacroExpansionDeclSyntax.self)) { macro, node in - return try expandFreestandingMemberDeclList( + expandFreestandingMacro(node.decl.as(MacroExpansionDeclSyntax.self)) { macro, node in + try expandFreestandingMemberDeclList( definition: macro, node: node, in: context, @@ -945,8 +945,8 @@ extension MacroApplication { /// let a = #foo /// ``` func expandExpr(node: Syntax) -> MacroExpansionResult { - return expandFreestandingMacro(node.as(MacroExpansionExprSyntax.self)) { macro, node in - return try expandFreestandingExpr( + expandFreestandingMacro(node.as(MacroExpansionExprSyntax.self)) { macro, node in + try expandFreestandingExpr( definition: macro, node: node, in: context, @@ -1003,7 +1003,7 @@ private extension String { func wrappingInTrivia(from node: some SyntaxProtocol) -> String { // We need to remove the indentation from the last line because the macro // expansion buffer already contains the indentation. - return node.leadingTrivia.removingIndentationOnLastLine.description + node.leadingTrivia.removingIndentationOnLastLine.description + self + node.trailingTrivia.description } @@ -1048,7 +1048,7 @@ private extension FreestandingMacroExpansionSyntax { in context: MacroExpansionContext, foldingWith operatorTable: OperatorTable? ) -> Self { - return (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self) + (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self) } } @@ -1060,6 +1060,6 @@ private extension AttributeSyntax { in context: MacroExpansionContext, foldingWith operatorTable: OperatorTable? ) -> Self { - return (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self) + (detach(in: context, foldingWith: operatorTable) as Syntax).cast(Self.self) } } diff --git a/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift b/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift index 801c98569c0..0008ab0f637 100644 --- a/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift +++ b/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift @@ -61,7 +61,7 @@ extension MacroExpansionContext { public func location( of node: some SyntaxProtocol ) -> AbstractSourceLocation? { - return location(of: node, at: .afterLeadingTrivia, filePathMode: .fileID) + location(of: node, at: .afterLeadingTrivia, filePathMode: .fileID) } } diff --git a/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift b/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift index 0672ca8877d..fc2ebe9382b 100644 --- a/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift +++ b/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift @@ -24,6 +24,6 @@ public enum FormatMode { public extension Macro { static var formatMode: FormatMode { - return .auto + .auto } } diff --git a/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift b/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift index e5673bacc35..ad0a87bf6a6 100644 --- a/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift +++ b/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift @@ -61,7 +61,7 @@ public extension MemberMacro { providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { - return try expansion(of: node, providingMembersOf: declaration, conformingTo: [], in: context) + try expansion(of: node, providingMembersOf: declaration, conformingTo: [], in: context) } /// Default implementation that ignores the unhandled conformances. @@ -71,6 +71,6 @@ public extension MemberMacro { conformingTo protocols: [TypeSyntax], in context: some MacroExpansionContext ) throws -> [DeclSyntax] { - return try expansion(of: node, providingMembersOf: declaration, in: context) + try expansion(of: node, providingMembersOf: declaration, in: context) } } diff --git a/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift b/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift index e48bf6dc367..bf87329631a 100644 --- a/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift +++ b/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift @@ -13,6 +13,6 @@ public extension String { // This implementation is really slow; to use it outside a test it should be optimized. func trimmingTrailingWhitespace() -> String { - return self.replacingOccurrences(of: "[ ]+\\n", with: "\n", options: .regularExpression).trimmingCharacters(in: [" "]) + self.replacingOccurrences(of: "[ ]+\\n", with: "\n", options: .regularExpression).trimmingCharacters(in: [" "]) } } diff --git a/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift b/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift index 32b203787ca..70257c7006c 100644 --- a/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift +++ b/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift @@ -115,7 +115,7 @@ extension SyntaxProtocol { /// - Warning: This is only designed for use in the debugger. Do not call it outside of the debugger. @available(*, deprecated, message: "For use in debugger only") public func debugInitCall(includeTrivia: Bool = true) -> String { - return self.debugInitCallExpr(includeTrivia: includeTrivia).formatted(using: InitializerExprFormat()).description + self.debugInitCallExpr(includeTrivia: includeTrivia).formatted(using: InitializerExprFormat()).description } private func debugInitCallExpr(includeTrivia: Bool) -> ExprSyntax { diff --git a/Sources/swift-parser-cli/ParseCommand.swift b/Sources/swift-parser-cli/ParseCommand.swift index db9a5f4a7cd..bdf4ab2e946 100644 --- a/Sources/swift-parser-cli/ParseCommand.swift +++ b/Sources/swift-parser-cli/ParseCommand.swift @@ -34,7 +34,7 @@ extension ParseCommand { /// This is not necessarily a file path if the file contents are read from /// stdin or the command line arguments. var sourceFileName: String { - return arguments.sourceFile ?? "stdin" + arguments.sourceFile ?? "stdin" } /// The contents of the source that should be parsed in UTF-8 bytes. diff --git a/Sources/swift-parser-cli/TerminalUtils.swift b/Sources/swift-parser-cli/TerminalUtils.swift index cb905a2754b..60fb78cf64f 100644 --- a/Sources/swift-parser-cli/TerminalUtils.swift +++ b/Sources/swift-parser-cli/TerminalUtils.swift @@ -28,12 +28,12 @@ typealias FILEPointer = UnsafeMutablePointer enum TerminalHelper { static var isConnectedToTerminal: Bool { - return isTTY(stderr) + isTTY(stderr) } /// Checks if passed file pointer is a tty. static func isTTY(_ filePointer: FILEPointer) -> Bool { - return terminalType(filePointer) == .tty + terminalType(filePointer) == .tty } /// The type of terminal. diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Build.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Build.swift index 171a6274dc9..f69d62a3102 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Build.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Build.swift @@ -15,7 +15,7 @@ import Foundation struct Build: ParsableCommand, BuildCommand { static var configuration: CommandConfiguration { - return CommandConfiguration( + CommandConfiguration( abstract: "Build swift-syntax." ) } diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/GenerateSourceCode.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/GenerateSourceCode.swift index a3fc553713b..73f303e9bda 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/GenerateSourceCode.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/GenerateSourceCode.swift @@ -15,7 +15,7 @@ import Foundation struct GenerateSourceCode: ParsableCommand, SourceCodeGeneratorCommand { static var configuration: CommandConfiguration { - return CommandConfiguration( + CommandConfiguration( abstract: "Generate swift-syntax sources." ) } diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Test.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Test.swift index 68a89a2896b..f6baa0af216 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Test.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/Test.swift @@ -15,7 +15,7 @@ import Foundation struct Test: ParsableCommand, BuildCommand { static var configuration: CommandConfiguration { - return CommandConfiguration( + CommandConfiguration( abstract: "Run swift-syntax tests." ) } @@ -72,7 +72,7 @@ struct Test: ParsableCommand, BuildCommand { } private func findSwiftpmBinPath(packageDir: URL) throws -> String { - return try invokeSwiftPM( + try invokeSwiftPM( action: "build", packageDir: packageDir, additionalArguments: ["--show-bin-path"], diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift index 03a1a465c13..4dc1d9c8039 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift @@ -19,7 +19,7 @@ fileprivate var modules: [String] { struct VerifySourceCode: ParsableCommand, SourceCodeGeneratorCommand { static var configuration: CommandConfiguration { - return CommandConfiguration( + CommandConfiguration( abstract: "Verify that the generated sources match the ones checked into the repository." ) } diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/BuildCommand.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/BuildCommand.swift index be0293f8502..74a84bbeebd 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/BuildCommand.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/BuildCommand.swift @@ -91,7 +91,7 @@ extension BuildCommand { @discardableResult func invokeXcodeBuild(projectPath: URL, scheme: String) throws -> ProcessResult { - return try withTemporaryDirectory { tempDir in + try withTemporaryDirectory { tempDir in guard let xcodebuildExec = Paths.xcodebuildExec else { throw ScriptExectutionError( message: """ diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift index 48a42e5e42f..64f5eb8286d 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift @@ -62,15 +62,15 @@ enum Paths { } static var python3Exec: URL? { - return lookupExecutable(for: "python3") + lookupExecutable(for: "python3") } static var diffExec: URL? { - return lookupExecutable(for: "diff") + lookupExecutable(for: "diff") } static var xcodebuildExec: URL? { - return lookupExecutable(for: "xcodebuild") + lookupExecutable(for: "xcodebuild") } private static var envSearchPaths: [URL] { @@ -99,14 +99,14 @@ enum Paths { } private static func lookupExecutable(for filename: String) -> URL? { - return envSearchPaths.map { $0.appendingPathComponent(filename) } + envSearchPaths.map { $0.appendingPathComponent(filename) } .first(where: { $0.isExecutableFile }) } } fileprivate extension URL { var isExecutableFile: Bool { - return (self.isFile(path) || self.isSymlink(path)) && FileManager.default.isExecutableFile(atPath: path) + (self.isFile(path) || self.isSymlink(path)) && FileManager.default.isExecutableFile(atPath: path) } private func isFile(_ path: String) -> Bool { diff --git a/Tests/PerformanceTest/ParsingPerformanceTests.swift b/Tests/PerformanceTest/ParsingPerformanceTests.swift index 805c8d96f7c..e5f478c0c91 100644 --- a/Tests/PerformanceTest/ParsingPerformanceTests.swift +++ b/Tests/PerformanceTest/ParsingPerformanceTests.swift @@ -17,7 +17,7 @@ import XCTest public class ParsingPerformanceTests: XCTestCase { var inputFile: URL { - return URL(fileURLWithPath: #file) + URL(fileURLWithPath: #file) .deletingLastPathComponent() .appendingPathComponent("Inputs") .appendingPathComponent("MinimalCollections.swift.input") diff --git a/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift b/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift index 70cea58a475..b8d891ffc7e 100644 --- a/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift +++ b/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift @@ -18,7 +18,7 @@ import XCTest public class SyntaxClassifierPerformanceTests: XCTestCase { var inputFile: URL { - return URL(fileURLWithPath: #file) + URL(fileURLWithPath: #file) .deletingLastPathComponent() .appendingPathComponent("Inputs") .appendingPathComponent("MinimalCollections.swift.input") diff --git a/Tests/PerformanceTest/VisitorPerformanceTests.swift b/Tests/PerformanceTest/VisitorPerformanceTests.swift index 796d0c0b5cb..4307f86ad2a 100644 --- a/Tests/PerformanceTest/VisitorPerformanceTests.swift +++ b/Tests/PerformanceTest/VisitorPerformanceTests.swift @@ -17,7 +17,7 @@ import XCTest public class VisitorPerformanceTests: XCTestCase { var inputFile: URL { - return URL(fileURLWithPath: #file) + URL(fileURLWithPath: #file) .deletingLastPathComponent() .appendingPathComponent("Inputs") .appendingPathComponent("MinimalCollections.swift.input") diff --git a/Tests/SwiftOperatorsTest/OperatorTableTests.swift b/Tests/SwiftOperatorsTest/OperatorTableTests.swift index b572c1d6329..97ac65402f7 100644 --- a/Tests/SwiftOperatorsTest/OperatorTableTests.swift +++ b/Tests/SwiftOperatorsTest/OperatorTableTests.swift @@ -27,7 +27,7 @@ private class ExprSequenceSearcher: SyntaxAnyVisitor { } override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind { - return foundSequenceExpr ? .skipChildren : .visitChildren + foundSequenceExpr ? .skipChildren : .visitChildren } } diff --git a/Tests/SwiftParserTest/Assertions.swift b/Tests/SwiftParserTest/Assertions.swift index 54f3536fa0a..74319e1e61f 100644 --- a/Tests/SwiftParserTest/Assertions.swift +++ b/Tests/SwiftParserTest/Assertions.swift @@ -286,7 +286,7 @@ class FixItApplier: SyntaxRewriter { diagnostics .flatMap { $0.fixIts } .filter { - return messages.contains($0.message.message) + messages.contains($0.message.message) } .flatMap { $0.changes } @@ -734,7 +734,7 @@ class TriviaRemover: SyntaxRewriter { } override func visit(_ token: TokenSyntax) -> TokenSyntax { - return token.with(\.leadingTrivia, []).with(\.trailingTrivia, []) + token.with(\.leadingTrivia, []).with(\.trailingTrivia, []) } } diff --git a/Tests/SwiftParserTest/LinkageTests.swift b/Tests/SwiftParserTest/LinkageTests.swift index 8c9f736fb15..0fd46d3ae3e 100644 --- a/Tests/SwiftParserTest/LinkageTests.swift +++ b/Tests/SwiftParserTest/LinkageTests.swift @@ -309,7 +309,7 @@ fileprivate enum Linkage: Comparable, Hashable { } func hasPrefix(_ prefix: String) -> Bool { - return self.linkage.hasPrefix(prefix) + self.linkage.hasPrefix(prefix) } } @@ -321,15 +321,15 @@ extension Linkage { var line: UInt func matches(_ linkage: Linkage) -> Bool { - return self.linkage == linkage + self.linkage == linkage } static func library(_ linkage: String, condition: Condition? = nil, file: StaticString = #file, line: UInt = #line) -> Assertion { - return Linkage.Assertion(linkage: .library(linkage), condition: condition, file: file, line: line) + Linkage.Assertion(linkage: .library(linkage), condition: condition, file: file, line: line) } static func framework(_ linkage: String, condition: Condition? = nil, file: StaticString = #file, line: UInt = #line) -> Assertion { - return Linkage.Assertion(linkage: .framework(linkage), condition: condition, file: file, line: line) + Linkage.Assertion(linkage: .framework(linkage), condition: condition, file: file, line: line) } } } @@ -358,19 +358,19 @@ extension Linkage.Assertion { } fileprivate static func when(swiftVersionAtLeast version: SwiftVersion) -> Condition { - return .swiftVersionAtLeast(versionBound: version) + .swiftVersionAtLeast(versionBound: version) } fileprivate static func when(configuration: ProductConfiguration) -> Condition { - return .configuration(configuration) + .configuration(configuration) } fileprivate static func when(compilationCondition: CompilationCondition) -> Condition { - return .compilationCondition(compilationCondition) + .compilationCondition(compilationCondition) } fileprivate static func mayBeAbsent(_ reason: StaticString) -> Condition { - return .flaky + .flaky } fileprivate func evaluate() -> Bool { diff --git a/Tests/SwiftParserTest/ThenStatementTests.swift b/Tests/SwiftParserTest/ThenStatementTests.swift index 6435b60a304..32d28f3ca22 100644 --- a/Tests/SwiftParserTest/ThenStatementTests.swift +++ b/Tests/SwiftParserTest/ThenStatementTests.swift @@ -17,7 +17,7 @@ import XCTest final class ThenStatementTests: ParserTestCase { // Enable then statements by default. override var experimentalFeatures: Parser.ExperimentalFeatures { - return .thenStatements + .thenStatements } func testThenStmt1() { diff --git a/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift index bb857bdb4d4..789f10c4537 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/AccessorMacroTests.swift @@ -29,7 +29,7 @@ fileprivate struct ConstantOneGetter: AccessorMacro { providingAccessorsOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext ) throws -> [AccessorDeclSyntax] { - return [ + [ """ get { return 1 diff --git a/Tests/SwiftSyntaxMacroExpansionTest/MemberAttributeMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/MemberAttributeMacroTests.swift index 223419b7453..bb560450310 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/MemberAttributeMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/MemberAttributeMacroTests.swift @@ -184,7 +184,7 @@ final class MemberAttributeMacroTests: XCTestCase { providingAttributesFor member: some DeclSyntaxProtocol, in context: some MacroExpansionContext ) throws -> [AttributeSyntax] { - return ["@Wrapper"] + ["@Wrapper"] } } @@ -273,7 +273,7 @@ final class MemberAttributeMacroTests: XCTestCase { providingAttributesFor member: some DeclSyntaxProtocol, in context: some MacroExpansionContext ) throws -> [AttributeSyntax] { - return ["/* start */@Wrapper/* end */"] + ["/* start */@Wrapper/* end */"] } } diff --git a/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift index 91b3bf8bad6..140e2515f6e 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift @@ -30,7 +30,7 @@ fileprivate struct NoOpMemberMacro: MemberMacro { providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { - return [] + [] } } @@ -89,7 +89,7 @@ final class MemberMacroTests: XCTestCase { providingMembersOf decl: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { - return ["var _storage: Storage"] + ["var _storage: Storage"] } } diff --git a/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift index 57179e615ee..5eb5026baa1 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift @@ -128,7 +128,7 @@ final class MultiRoleMacroTests: XCTestCase { providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { - return ["var _storage: Wrapper"] + ["var _storage: Wrapper"] } static func expansion( @@ -137,7 +137,7 @@ final class MultiRoleMacroTests: XCTestCase { providingAttributesFor member: some DeclSyntaxProtocol, in context: some MacroExpansionContext ) throws -> [AttributeSyntax] { - return ["@customTypeWrapper"] + ["@customTypeWrapper"] } static func expansion( @@ -209,7 +209,7 @@ final class MultiRoleMacroTests: XCTestCase { func testAttachedMacroOnFreestandingMacro() { struct DeclMacro: DeclarationMacro { static func expansion(of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext) throws -> [DeclSyntax] { - return ["var x: Int"] + ["var x: Int"] } } @@ -217,7 +217,7 @@ final class MultiRoleMacroTests: XCTestCase { static func expansion(of node: AttributeSyntax, providingPeersOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext) throws -> [DeclSyntax] { - return ["var peer: Int"] + ["var peer: Int"] } } diff --git a/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift index b92fdcdf232..fa0de62e014 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift @@ -137,7 +137,7 @@ final class PeerMacroTests: XCTestCase { providingPeersOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { - return ["var baz: Int = 0"] + ["var baz: Int = 0"] } } diff --git a/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift b/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift index ab96756a868..adb498b9bb7 100644 --- a/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift +++ b/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift @@ -18,7 +18,7 @@ import _SwiftSyntaxTestSupport private extension String { // This implementation is really slow; to use it outside a test it should be optimized. func trimmingTrailingWhitespace() -> String { - return self.replacingOccurrences(of: "[ ]+\\n", with: "\n", options: .regularExpression) + self.replacingOccurrences(of: "[ ]+\\n", with: "\n", options: .regularExpression) } } diff --git a/Tests/SwiftSyntaxTest/RawSyntaxTests.swift b/Tests/SwiftSyntaxTest/RawSyntaxTests.swift index dcec2884bd6..216b85d9591 100644 --- a/Tests/SwiftSyntaxTest/RawSyntaxTests.swift +++ b/Tests/SwiftSyntaxTest/RawSyntaxTests.swift @@ -121,7 +121,7 @@ final class RawSyntaxTests: XCTestCase { // Dummy trivia parsing function. func dummyParseToken(source: SyntaxText, position: TriviaPosition) -> [RawTriviaPiece] { // Emit a single `unexpectedText` trivia of the whole trivia text. - return [.unexpectedText(source)] + [.unexpectedText(source)] } withExtendedLifetime(ParsingSyntaxArena(parseTriviaFunction: dummyParseToken)) { arena in diff --git a/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift b/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift index 08ba3174b6b..90f98873a1a 100644 --- a/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift +++ b/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift @@ -152,7 +152,7 @@ public class SyntaxVisitorTests: XCTestCase { class ClosureRewriter: SyntaxRewriter { override func visit(_ node: ClosureExprSyntax) -> ExprSyntax { // Perform a no-op transform that requires rebuilding the node. - return ExprSyntax(node.with(\.statements, node.statements)) + ExprSyntax(node.with(\.statements, node.statements)) } } let closure = ClosureExprSyntax( @@ -219,7 +219,7 @@ public class SyntaxVisitorTests: XCTestCase { public func testRewriteTrivia() { class TriviaRemover: SyntaxRewriter { override func visit(_ token: TokenSyntax) -> TokenSyntax { - return token.with(\.trailingTrivia, []) + token.with(\.trailingTrivia, []) } } diff --git a/Tests/SwiftSyntaxTestSupportTest/SyntaxComparisonTests.swift b/Tests/SwiftSyntaxTestSupportTest/SyntaxComparisonTests.swift index cb799632ece..108eee4e290 100644 --- a/Tests/SwiftSyntaxTestSupportTest/SyntaxComparisonTests.swift +++ b/Tests/SwiftSyntaxTestSupportTest/SyntaxComparisonTests.swift @@ -16,7 +16,7 @@ import XCTest import _SwiftSyntaxTestSupport private func parse(source: String) -> Syntax { - return Syntax(Parser.parse(source: source)) + Syntax(Parser.parse(source: source)) } public class SyntaxComparisonTests: XCTestCase {