diff --git a/.swift-format b/.swift-format index 6d5a9acd29f..d3464f15b86 100644 --- a/.swift-format +++ b/.swift-format @@ -1,6 +1,6 @@ { "version": 1, - "lineLength": 1000, + "lineLength": 160, "indentation": { "spaces": 2 }, diff --git a/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift b/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift index d754f437fb4..a847083845e 100644 --- a/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift @@ -298,7 +298,13 @@ public let ATTRIBUTE_NODES: [Node] = [ children: [ Child( name: "DeclBaseName", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .token(tokenKind: "BinaryOperatorToken"), .keyword(text: "init"), .keyword(text: "self"), .keyword(text: "Self")]), + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .token(tokenKind: "BinaryOperatorToken"), + .keyword(text: "init"), + .keyword(text: "self"), + .keyword(text: "Self"), + ]), nameForDiagnostics: "base name", documentation: "The base name of the protocol's requirement." ), @@ -322,7 +328,8 @@ public let ATTRIBUTE_NODES: [Node] = [ kind: .derivativeRegistrationAttributeArguments, base: .syntax, nameForDiagnostics: "attribute arguments", - documentation: "The arguments for the '@derivative(of:)' and '@transpose(of:)' attributes: the 'of:' label, the original declaration name, and an optional differentiability parameter list.", + documentation: + "The arguments for the '@derivative(of:)' and '@transpose(of:)' attributes: the 'of:' label, the original declaration name, and an optional differentiability parameter list.", children: [ Child( name: "OfLabel", @@ -461,7 +468,8 @@ public let ATTRIBUTE_NODES: [Node] = [ kind: .differentiableAttributeArguments, base: .syntax, nameForDiagnostics: "'@differentiable' arguments", - documentation: "The arguments for the `@differentiable` attribute: an optional differentiability kind, an optional differentiability parameter clause, and an optional 'where' clause.", + documentation: + "The arguments for the `@differentiable` attribute: an optional differentiability kind, an optional differentiability parameter clause, and an optional 'where' clause.", children: [ Child( name: "DiffKind", @@ -515,7 +523,14 @@ public let ATTRIBUTE_NODES: [Node] = [ kind: .nodeChoices(choices: [ Child( name: "Token", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .keyword(text: "private"), .keyword(text: "fileprivate"), .keyword(text: "internal"), .keyword(text: "public"), .keyword(text: "open")]) + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .keyword(text: "private"), + .keyword(text: "fileprivate"), + .keyword(text: "internal"), + .keyword(text: "public"), + .keyword(text: "open"), + ]) ), // Keywords can be: public, internal, private, fileprivate, open Child( name: "String", @@ -670,7 +685,8 @@ public let ATTRIBUTE_NODES: [Node] = [ kind: .objCSelectorPiece, base: .syntax, nameForDiagnostics: "Objective-C selector piece", - documentation: "A piece of an Objective-C selector. Either consisting of just an identifier for a nullary selector, an identifier and a colon for a labeled argument or just a colon for an unlabeled argument", + documentation: + "A piece of an Objective-C selector. Either consisting of just an identifier for a nullary selector, an identifier and a colon for a labeled argument or just a colon for an unlabeled argument", children: [ Child( name: "Name", @@ -776,7 +792,13 @@ public let ATTRIBUTE_NODES: [Node] = [ ), Child( name: "Name", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .keyword(text: "self"), .keyword(text: "Self"), .keyword(text: "init"), .token(tokenKind: "BinaryOperatorToken")]), + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .keyword(text: "self"), + .keyword(text: "Self"), + .keyword(text: "init"), + .token(tokenKind: "BinaryOperatorToken"), + ]), nameForDiagnostics: "base name", documentation: "The base name of the referenced function." ), diff --git a/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift b/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift index f25ae4f4c75..ca87c268c81 100644 --- a/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift @@ -27,7 +27,11 @@ public let AVAILABILITY_NODES: [Node] = [ kind: .nodeChoices(choices: [ Child( name: "Token", - kind: .token(choices: [.token(tokenKind: "BinaryOperatorToken"), .token(tokenKind: "IdentifierToken")], requiresLeadingSpace: false, requiresTrailingSpace: false) + kind: .token( + choices: [.token(tokenKind: "BinaryOperatorToken"), .token(tokenKind: "IdentifierToken")], + requiresLeadingSpace: false, + requiresTrailingSpace: false + ) ), Child( name: "AvailabilityVersionRestriction", @@ -59,7 +63,13 @@ public let AVAILABILITY_NODES: [Node] = [ children: [ Child( name: "Label", - kind: .token(choices: [.keyword(text: "message"), .keyword(text: "renamed"), .keyword(text: "introduced"), .keyword(text: "obsoleted"), .keyword(text: "deprecated")]), + kind: .token(choices: [ + .keyword(text: "message"), + .keyword(text: "renamed"), + .keyword(text: "introduced"), + .keyword(text: "obsoleted"), + .keyword(text: "deprecated"), + ]), nameForDiagnostics: "label", documentation: "The label of the argument" ), @@ -106,7 +116,8 @@ public let AVAILABILITY_NODES: [Node] = [ name: "Platform", kind: .token(choices: [.token(tokenKind: "IdentifierToken")]), nameForDiagnostics: "platform", - documentation: "The name of the OS on which the availability should be restricted or 'swift' if the availability should be restricted based on a Swift version.", + documentation: + "The name of the OS on which the availability should be restricted or 'swift' if the availability should be restricted based on a Swift version.", classification: "Keyword" ), Child( diff --git a/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift b/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift index c455c4b9c6b..8dfaa334c09 100644 --- a/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift @@ -18,7 +18,12 @@ public let DECL_NODES: [Node] = [ children: [ Child( name: "Name", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .token(tokenKind: "BinaryOperatorToken"), .token(tokenKind: "PrefixOperatorToken"), .token(tokenKind: "PostfixOperatorToken")]), + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .token(tokenKind: "BinaryOperatorToken"), + .token(tokenKind: "PrefixOperatorToken"), + .token(tokenKind: "PostfixOperatorToken"), + ]), nameForDiagnostics: "name" ), Child( @@ -81,7 +86,20 @@ public let DECL_NODES: [Node] = [ ), Child( name: "AccessorKind", - kind: .token(choices: [.keyword(text: "get"), .keyword(text: "set"), .keyword(text: "didSet"), .keyword(text: "willSet"), .keyword(text: "unsafeAddress"), .keyword(text: "addressWithOwner"), .keyword(text: "addressWithNativeOwner"), .keyword(text: "unsafeMutableAddress"), .keyword(text: "mutableAddressWithOwner"), .keyword(text: "mutableAddressWithNativeOwner"), .keyword(text: "_read"), .keyword(text: "_modify")]) + kind: .token(choices: [ + .keyword(text: "get"), + .keyword(text: "set"), + .keyword(text: "didSet"), + .keyword(text: "willSet"), + .keyword(text: "unsafeAddress"), + .keyword(text: "addressWithOwner"), + .keyword(text: "addressWithNativeOwner"), + .keyword(text: "unsafeMutableAddress"), + .keyword(text: "mutableAddressWithOwner"), + .keyword(text: "mutableAddressWithNativeOwner"), + .keyword(text: "_read"), + .keyword(text: "_modify"), + ]) ), Child( name: "Parameter", @@ -373,7 +391,8 @@ public let DECL_NODES: [Node] = [ Child( name: "MemberBlock", kind: .node(kind: .memberDeclBlock), - documentation: "The members of the class declaration. As class extension declarations may declare additional members, the contents of this member block isn't guaranteed to be a complete list of members for this type." + documentation: + "The members of the class declaration. As class extension declarations may declare additional members, the contents of this member block isn't guaranteed to be a complete list of members for this type." ), ] ), @@ -766,7 +785,8 @@ public let DECL_NODES: [Node] = [ Child( name: "MemberBlock", kind: .node(kind: .memberDeclBlock), - documentation: "The cases and other members associated with this enum declaration. Because enum extension declarations may declare additional members the contents of this member block isn't guaranteed to be a complete list of members for this type." + documentation: + "The cases and other members associated with this enum declaration. Because enum extension declarations may declare additional members the contents of this member block isn't guaranteed to be a complete list of members for this type." ), ] ), @@ -854,7 +874,12 @@ public let DECL_NODES: [Node] = [ ), Child( name: "Identifier", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .token(tokenKind: "BinaryOperatorToken"), .token(tokenKind: "PrefixOperatorToken"), .token(tokenKind: "PostfixOperatorToken")]) + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .token(tokenKind: "BinaryOperatorToken"), + .token(tokenKind: "PrefixOperatorToken"), + .token(tokenKind: "PostfixOperatorToken"), + ]) ), Child( name: "GenericParameterClause", @@ -1085,7 +1110,17 @@ public let DECL_NODES: [Node] = [ ), Child( name: "ImportKind", - kind: .token(choices: [.keyword(text: "typealias"), .keyword(text: "struct"), .keyword(text: "class"), .keyword(text: "enum"), .keyword(text: "protocol"), .keyword(text: "var"), .keyword(text: "let"), .keyword(text: "func"), .keyword(text: "inout")]), + kind: .token(choices: [ + .keyword(text: "typealias"), + .keyword(text: "struct"), + .keyword(text: "class"), + .keyword(text: "enum"), + .keyword(text: "protocol"), + .keyword(text: "var"), + .keyword(text: "let"), + .keyword(text: "func"), + .keyword(text: "inout"), + ]), documentation: "The kind of declaration being imported. For example, a struct can be imported from a specific module.", isOptional: true ), @@ -1181,7 +1216,11 @@ public let DECL_NODES: [Node] = [ ), Child( name: "OptionalMark", - kind: .token(choices: [.token(tokenKind: "PostfixQuestionMarkToken"), .token(tokenKind: "InfixQuestionMarkToken"), .token(tokenKind: "ExclamationMarkToken")]), + kind: .token(choices: [ + .token(tokenKind: "PostfixQuestionMarkToken"), + .token(tokenKind: "InfixQuestionMarkToken"), + .token(tokenKind: "ExclamationMarkToken"), + ]), documentation: "If the initializer is failable, a question mark to indicate that.", isOptional: true ), @@ -1638,7 +1677,8 @@ public let DECL_NODES: [Node] = [ Child( name: "Flag", kind: .token(choices: [.keyword(text: "true"), .keyword(text: "false")]), - documentation: "When true, an operator in the corresponding precedence group uses the same grouping rules during optional chaining as the assignment operators from the standard library. Otherwise, operators in the precedence group follows the same optional chaining rules as operators that don't perform assignment." + documentation: + "When true, an operator in the corresponding precedence group uses the same grouping rules during optional chaining as the assignment operators from the standard library. Otherwise, operators in the precedence group follows the same optional chaining rules as operators that don't perform assignment." ), ] ), @@ -1663,7 +1703,8 @@ public let DECL_NODES: [Node] = [ Child( name: "Value", kind: .token(choices: [.keyword(text: "left"), .keyword(text: "right"), .keyword(text: "none")]), - documentation: "Operators that are `left`-associative group left-to-right. Operators that are `right`-associative group right-to-left. Operators that are specified with an associativity of `none` don't associate at all" + documentation: + "Operators that are `left`-associative group left-to-right. Operators that are `right`-associative group right-to-left. Operators that are specified with an associativity of `none` don't associate at all" ), ] ), @@ -2017,7 +2058,8 @@ public let DECL_NODES: [Node] = [ Child( name: "MemberBlock", kind: .node(kind: .memberDeclBlock), - documentation: "The members of the struct declaration. Because struct extension declarations may declare additional members the contents of this member block isn't guaranteed to be a complete list of members for this type." + documentation: + "The members of the struct declaration. Because struct extension declarations may declare additional members the contents of this member block isn't guaranteed to be a complete list of members for this type." ), ] ), diff --git a/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift b/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift index f5a1f07b1cb..489d41b2a39 100644 --- a/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift @@ -382,7 +382,8 @@ public let EXPR_NODES: [Node] = [ Child( name: "SecondName", kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .token(tokenKind: "WildcardToken")]), - documentation: "If this is specified, it is the name by which the parameter can be referenced inside the closure body. If it is `nil`, the closure parameter is referenced by the first name.", + documentation: + "If this is specified, it is the name by which the parameter can be referenced inside the closure body. If it is `nil`, the closure parameter is referenced by the first name.", isOptional: true ), Child( @@ -831,7 +832,14 @@ public let EXPR_NODES: [Node] = [ children: [ Child( name: "Identifier", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .keyword(text: "self"), .keyword(text: "Self"), .keyword(text: "init"), .token(tokenKind: "DollarIdentifierToken"), .token(tokenKind: "BinaryOperatorToken")]) + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .keyword(text: "self"), + .keyword(text: "Self"), + .keyword(text: "init"), + .token(tokenKind: "DollarIdentifierToken"), + .token(tokenKind: "BinaryOperatorToken"), + ]) ), Child( name: "DeclNameArguments", @@ -1067,7 +1075,15 @@ public let EXPR_NODES: [Node] = [ children: [ Child( name: "Identifier", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .keyword(text: "self"), .keyword(text: "Self"), .keyword(text: "init"), .token(tokenKind: "DollarIdentifierToken"), .token(tokenKind: "BinaryOperatorToken"), .token(tokenKind: "IntegerLiteralToken")]) + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .keyword(text: "self"), + .keyword(text: "Self"), + .keyword(text: "init"), + .token(tokenKind: "DollarIdentifierToken"), + .token(tokenKind: "BinaryOperatorToken"), + .token(tokenKind: "IntegerLiteralToken"), + ]) ), Child( name: "DeclNameArguments", diff --git a/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift b/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift index 5f060b970aa..c5a47c5c83e 100644 --- a/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift @@ -190,7 +190,15 @@ public let GENERIC_NODES: [Node] = [ ), Child( name: "LayoutConstraint", - kind: .token(choices: [.keyword(text: "_Trivial"), .keyword(text: "_TrivialAtMost"), .keyword(text: "_UnknownLayout"), .keyword(text: "_RefCountedObject"), .keyword(text: "_NativeRefCountedObject"), .keyword(text: "_Class"), .keyword(text: "_NativeClass")]) + kind: .token(choices: [ + .keyword(text: "_Trivial"), + .keyword(text: "_TrivialAtMost"), + .keyword(text: "_UnknownLayout"), + .keyword(text: "_RefCountedObject"), + .keyword(text: "_NativeRefCountedObject"), + .keyword(text: "_Class"), + .keyword(text: "_NativeClass"), + ]) ), Child( name: "LeftParen", diff --git a/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift b/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift index 9984570784c..9be37b3f51c 100644 --- a/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift +++ b/CodeGeneration/Sources/SyntaxSupport/TokenSpec.swift @@ -171,7 +171,14 @@ public let SYNTAX_TOKENS: [TokenSpec] = [ PunctuatorSpec(name: "AtSign", kind: "at_sign", text: "@", classification: "Attribute"), PunctuatorSpec(name: "Backslash", kind: "backslash", text: "\\"), PunctuatorSpec(name: "Backtick", kind: "backtick", text: "`"), - MiscSpec(name: "BinaryOperator", kind: "oper_binary", nameForDiagnostics: "binary operator", classification: "OperatorIdentifier", requiresLeadingSpace: true, requiresTrailingSpace: true), + MiscSpec( + name: "BinaryOperator", + kind: "oper_binary", + nameForDiagnostics: "binary operator", + classification: "OperatorIdentifier", + requiresLeadingSpace: true, + requiresTrailingSpace: true + ), PunctuatorSpec(name: "Colon", kind: "colon", text: ":", requiresTrailingSpace: true), PunctuatorSpec(name: "Comma", kind: "comma", text: ",", requiresTrailingSpace: true), MiscSpec(name: "DollarIdentifier", kind: "dollarident", nameForDiagnostics: "dollar identifier", classification: "DollarIdentifier"), diff --git a/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift b/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift index ca2e88269a3..9f5683120f8 100644 --- a/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift @@ -44,7 +44,15 @@ public let TYPE_NODES: [Node] = [ children: [ Child( name: "Specifier", - kind: .token(choices: [.keyword(text: "inout"), .keyword(text: "__shared"), .keyword(text: "__owned"), .keyword(text: "isolated"), .keyword(text: "_const"), .keyword(text: "borrowing"), .keyword(text: "consuming")]), + kind: .token(choices: [ + .keyword(text: "inout"), + .keyword(text: "__shared"), + .keyword(text: "__owned"), + .keyword(text: "isolated"), + .keyword(text: "_const"), + .keyword(text: "borrowing"), + .keyword(text: "consuming"), + ]), isOptional: true ), Child( @@ -408,7 +416,14 @@ public let TYPE_NODES: [Node] = [ children: [ Child( name: "Name", - kind: .token(choices: [.token(tokenKind: "IdentifierToken"), .keyword(text: "self"), .keyword(text: "Self"), .keyword(text: "Any"), .token(tokenKind: "KeywordToken"), .token(tokenKind: "WildcardToken")]), + kind: .token(choices: [ + .token(tokenKind: "IdentifierToken"), + .keyword(text: "self"), + .keyword(text: "Self"), + .keyword(text: "Any"), + .token(tokenKind: "KeywordToken"), + .token(tokenKind: "WildcardToken"), + ]), classification: "TypeIdentifier" ), Child( diff --git a/CodeGeneration/Sources/generate-swiftsyntax/GenerateSwiftSyntax.swift b/CodeGeneration/Sources/generate-swiftsyntax/GenerateSwiftSyntax.swift index 65c9e1ae4a9..05dcaa558de 100644 --- a/CodeGeneration/Sources/generate-swiftsyntax/GenerateSwiftSyntax.swift +++ b/CodeGeneration/Sources/generate-swiftsyntax/GenerateSwiftSyntax.swift @@ -120,7 +120,10 @@ struct GenerateSwiftSyntax: ParsableCommand { GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["BuildableCollectionNodes.swift"], buildableCollectionNodesFile), GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["BuildableNodes.swift"], buildableNodesFile), GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["ResultBuilders.swift"], resultBuildersFile), - GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["SyntaxExpressibleByStringInterpolationConformances.swift"], syntaxExpressibleByStringInterpolationConformancesFile), + GeneratedFileSpec( + swiftSyntaxBuilderGeneratedDir + ["SyntaxExpressibleByStringInterpolationConformances.swift"], + syntaxExpressibleByStringInterpolationConformancesFile + ), ] + BASE_KIND_FILES.map { baseKind in GeneratedFileSpec(swiftSyntaxGeneratedDir + ["syntaxNodes", baseKind.value], syntaxNode(emitKind: baseKind.key)) diff --git a/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableCollectionNodesFile.swift b/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableCollectionNodesFile.swift index 40272da5169..810ae1609eb 100644 --- a/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableCollectionNodesFile.swift +++ b/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableCollectionNodesFile.swift @@ -22,7 +22,10 @@ let buildableCollectionNodesFile = SourceFileSyntax(leadingTrivia: copyrightHead for node in SYNTAX_NODES.compactMap(\.collectionNode) { let elementType = node.collectionElementType - let docComment = node.documentation.isEmpty ? [.docLineComment("/// `\(node.kind.syntaxType)` represents a collection of `\(elementType.syntaxBaseName)`")] : node.documentation + let docComment = + node.documentation.isEmpty + ? [.docLineComment("/// `\(node.kind.syntaxType)` represents a collection of `\(elementType.syntaxBaseName)`")] + : node.documentation // Generate collection node struct try! ExtensionDeclSyntax( """ diff --git a/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableNodesFile.swift b/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableNodesFile.swift index caad4246b09..8eb0b1352d9 100644 --- a/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableNodesFile.swift +++ b/CodeGeneration/Sources/generate-swiftsyntax/templates/swiftsyntaxbuilder/BuildableNodesFile.swift @@ -71,7 +71,9 @@ private func createConvenienceInitializer(node: LayoutNode) throws -> Initialize produceExpr = ExprSyntax("\(raw: child.varName)Builder()") } builderParameters.append( - FunctionParameterSyntax("@\(builderInitializableType.resultBuilderType) \(raw: child.varName)Builder: () throws-> \(raw: builderInitializableType.syntax)") + FunctionParameterSyntax( + "@\(builderInitializableType.resultBuilderType) \(raw: child.varName)Builder: () throws-> \(raw: builderInitializableType.syntax)" + ) ) } else { produceExpr = convertFromSyntaxProtocolToSyntaxType(child: child) diff --git a/Package.swift b/Package.swift index 1b078b5b86a..54f7cdd05f9 100644 --- a/Package.swift +++ b/Package.swift @@ -181,7 +181,10 @@ let package = Package( .testTarget( name: "SwiftSyntaxMacrosTest", - dependencies: ["_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftOperators", "SwiftParser", "SwiftSyntaxBuilder", "SwiftSyntaxMacros", "SwiftSyntaxMacrosTestSupport"] + dependencies: [ + "_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftOperators", "SwiftParser", "SwiftSyntaxBuilder", "SwiftSyntaxMacros", + "SwiftSyntaxMacrosTestSupport", + ] ), // MARK: SwiftSyntaxMacroExpansion diff --git a/Sources/SwiftBasicFormat/BasicFormat.swift b/Sources/SwiftBasicFormat/BasicFormat.swift index 1a808e4030a..1498a2defe8 100644 --- a/Sources/SwiftBasicFormat/BasicFormat.swift +++ b/Sources/SwiftBasicFormat/BasicFormat.swift @@ -352,8 +352,17 @@ open class BasicFormat: SyntaxRewriter { guard let nextToken = nextToken else { return false } - return nextToken.leadingTrivia.startsWithNewline - || (requiresNewline(between: token, and: nextToken) && isMutable(nextToken) && !token.trailingTrivia.endsWithNewline && !token.isStringSegmentWithLastCharacterBeingNewline) + if nextToken.leadingTrivia.startsWithNewline { + return true + } + if requiresNewline(between: token, and: nextToken), + isMutable(nextToken), + !token.trailingTrivia.endsWithNewline, + !token.isStringSegmentWithLastCharacterBeingNewline + { + return true + } + return false }() /// This token's trailing trivia + any spaces or tabs at the start of the diff --git a/Sources/SwiftParser/Attributes.swift b/Sources/SwiftParser/Attributes.swift index 5e92df0c54a..4de56ac7eb0 100644 --- a/Sources/SwiftParser/Attributes.swift +++ b/Sources/SwiftParser/Attributes.swift @@ -165,7 +165,10 @@ extension Parser { case optional } - mutating func parseAttribute(argumentMode: AttributeArgumentMode, parseArguments: (inout Parser) -> RawAttributeSyntax.Argument) -> RawAttributeListSyntax.Element { + mutating func parseAttribute( + argumentMode: AttributeArgumentMode, + parseArguments: (inout Parser) -> RawAttributeSyntax.Argument + ) -> RawAttributeListSyntax.Element { let (unexpectedBeforeAtSign, atSign) = self.expect(.atSign) let attributeName = self.parseType() let shouldParseArgument: Bool diff --git a/Sources/SwiftParser/Availability.swift b/Sources/SwiftParser/Availability.swift index df49b20a05d..85e9b84b137 100644 --- a/Sources/SwiftParser/Availability.swift +++ b/Sources/SwiftParser/Availability.swift @@ -294,7 +294,12 @@ extension Parser { unexpectedTrailingComponents = RawUnexpectedNodesSyntax(elements: trailingComponents.compactMap { $0.as(RawSyntax.self) }, arena: self.arena) } - return RawVersionTupleSyntax(major: major, components: RawVersionComponentListSyntax(elements: components, arena: self.arena), unexpectedTrailingComponents, arena: self.arena) + return RawVersionTupleSyntax( + major: major, + components: RawVersionComponentListSyntax(elements: components, arena: self.arena), + unexpectedTrailingComponents, + arena: self.arena + ) } else { let major = self.expectDecimalIntegerWithoutRecovery() diff --git a/Sources/SwiftParser/Declarations.swift b/Sources/SwiftParser/Declarations.swift index a7e7cb6bc14..f437368e09d 100644 --- a/Sources/SwiftParser/Declarations.swift +++ b/Sources/SwiftParser/Declarations.swift @@ -487,7 +487,8 @@ extension Parser { var each = self.consume(if: .keyword(.each)) let (unexpectedBetweenEachAndName, name) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true) - if attributes == nil && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing && elements.isEmpty && !self.currentToken.starts(with: ">") { + if attributes == nil && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing && elements.isEmpty && !self.currentToken.starts(with: ">") + { break } @@ -1724,7 +1725,12 @@ extension Parser { let fixityModifier = modifiers[firstFixityIndex] fixity = fixityModifier.name - unexpectedBeforeFixity = RawUnexpectedNodesSyntax(combining: unexpectedBeforeFixity, RawUnexpectedNodesSyntax(Array(modifiers[0.. [Element] { var elements = [Element]() var elementsProgress = LoopProgressCondition() - while !self.at(.eof) && !self.at(.poundElseKeyword, .poundElseifKeyword, .poundEndifKeyword) && !self.atElifTypo() && elementsProgress.evaluate(currentToken) { + while !self.at(.eof) + && !self.at(.poundElseKeyword, .poundElseifKeyword, .poundEndifKeyword) + && !self.atElifTypo() + && elementsProgress.evaluate(currentToken) + { let newItemAtStartOfLine = self.currentToken.isAtStartOfLine guard let element = parseElement(&self, elements.isEmpty), !element.isEmpty else { break diff --git a/Sources/SwiftParser/Expressions.swift b/Sources/SwiftParser/Expressions.swift index 71c6dbaf997..0174bb5cde7 100644 --- a/Sources/SwiftParser/Expressions.swift +++ b/Sources/SwiftParser/Expressions.swift @@ -1112,7 +1112,9 @@ extension Parser { // Check for a .name or .1 suffix. if self.at(.period) { - let (unexpectedPeriod, period, name, declNameArgs, generics) = parseDottedExpressionSuffix(previousNode: components.last?.raw ?? rootType?.raw ?? backslash.raw) + let (unexpectedPeriod, period, name, declNameArgs, generics) = parseDottedExpressionSuffix( + previousNode: components.last?.raw ?? rootType?.raw ?? backslash.raw + ) components.append( RawKeyPathComponentSyntax( unexpectedPeriod, @@ -2223,7 +2225,10 @@ extension Parser.Lookahead { var backtrack = self.lookahead() backtrack.eat(.leftBrace) var loopProgress = LoopProgressCondition() - while !backtrack.at(.eof, .rightBrace) && !backtrack.at(.poundEndifKeyword, .poundElseKeyword, .poundElseifKeyword) && loopProgress.evaluate(backtrack.currentToken) { + while !backtrack.at(.eof, .rightBrace) + && !backtrack.at(.poundEndifKeyword, .poundElseKeyword, .poundElseifKeyword) + && loopProgress.evaluate(backtrack.currentToken) + { backtrack.skipSingle() } @@ -2615,7 +2620,15 @@ extension Parser { let version = self.parseVersionTuple(maxComponentCount: 4) - versionInfo = RawCanImportVersionInfoSyntax(comma: comma, unexpectedBeforeLabel, label: label, unexpectedBeforeColon, colon: colon, versionTuple: version, arena: self.arena) + versionInfo = RawCanImportVersionInfoSyntax( + comma: comma, + unexpectedBeforeLabel, + label: label, + unexpectedBeforeColon, + colon: colon, + versionTuple: version, + arena: self.arena + ) } let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) diff --git a/Sources/SwiftParser/Lexer/Cursor.swift b/Sources/SwiftParser/Lexer/Cursor.swift index 9f33f2b2b84..42f2a20606d 100644 --- a/Sources/SwiftParser/Lexer/Cursor.swift +++ b/Sources/SwiftParser/Lexer/Cursor.swift @@ -1056,13 +1056,19 @@ extension Lexer.Cursor { switch self.peek() { case UInt8(ascii: "("): _ = self.advance() - return Lexer.Result(.leftParen, stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount + 1))) + return Lexer.Result( + .leftParen, + stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount + 1)) + ) case UInt8(ascii: ")"): _ = self.advance() if parenCount == 0 { return Lexer.Result(.rightParen, stateTransition: .pop) } else { - return Lexer.Result(.rightParen, stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount - 1))) + return Lexer.Result( + .rightParen, + stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount - 1)) + ) } case UInt8(ascii: "\r"), UInt8(ascii: "\n"): // We don't eat newlines as leading trivia in string interpolation of diff --git a/Sources/SwiftParser/Lexer/LexemeSequence.swift b/Sources/SwiftParser/Lexer/LexemeSequence.swift index 0ffe22772db..9a4eb1a47e8 100644 --- a/Sources/SwiftParser/Lexer/LexemeSequence.swift +++ b/Sources/SwiftParser/Lexer/LexemeSequence.swift @@ -77,7 +77,8 @@ extension Lexer { @_spi(Testing) public var debugDescription: String { - let remainingText = self.nextToken.debugDescription + String(syntaxText: SyntaxText(baseAddress: self.cursor.input.baseAddress, count: self.cursor.input.count)) + let remainingText = + self.nextToken.debugDescription + String(syntaxText: SyntaxText(baseAddress: self.cursor.input.baseAddress, count: self.cursor.input.count)) if remainingText.count > 100 { return remainingText.prefix(100) + "..." } else { diff --git a/Sources/SwiftParser/LoopProgressCondition.swift b/Sources/SwiftParser/LoopProgressCondition.swift index 95742fd9af7..a3de3f19416 100644 --- a/Sources/SwiftParser/LoopProgressCondition.swift +++ b/Sources/SwiftParser/LoopProgressCondition.swift @@ -37,7 +37,9 @@ struct LoopProgressCondition { // - the parser is still pointing at the same position in the source file // but now has a different token kind (and thus consumed a zero-length // token like an empty string interpolation - let hasMadeProgress = previousToken.tokenText.baseAddress != currentToken.tokenText.baseAddress || (previousToken.byteLength == 0 && previousToken.rawTokenKind != currentToken.rawTokenKind) + let hasMadeProgress = + previousToken.tokenText.baseAddress != currentToken.tokenText.baseAddress + || (previousToken.byteLength == 0 && previousToken.rawTokenKind != currentToken.rawTokenKind) assert(hasMadeProgress, "Loop should always make progress") return hasMadeProgress } diff --git a/Sources/SwiftParser/Parameters.swift b/Sources/SwiftParser/Parameters.swift index f689060d75b..3bf206438e7 100644 --- a/Sources/SwiftParser/Parameters.swift +++ b/Sources/SwiftParser/Parameters.swift @@ -278,7 +278,9 @@ extension Parser { var elements = [ParameterClause.ParameterList.ParameterSyntax]() // If we are missing the left parenthesis and the next token doesn't appear // to be an argument label, don't parse any parameters. - let shouldSkipParameterParsing = lparen.isMissing && (!currentToken.canBeArgumentLabel(allowDollarIdentifier: true) || currentToken.isLexerClassifiedKeyword) + let shouldSkipParameterParsing = + lparen.isMissing + && (!currentToken.canBeArgumentLabel(allowDollarIdentifier: true) || currentToken.isLexerClassifiedKeyword) if !shouldSkipParameterParsing { var keepGoing = true var loopProgress = LoopProgressCondition() diff --git a/Sources/SwiftParser/Parser.swift b/Sources/SwiftParser/Parser.swift index f97b3ec64bf..5398227bbe4 100644 --- a/Sources/SwiftParser/Parser.swift +++ b/Sources/SwiftParser/Parser.swift @@ -449,7 +449,9 @@ extension Parser { if let identifier = self.consume(if: .identifier) { return (nil, identifier) } - if allowSelfOrCapitalSelfAsIdentifier, let selfOrCapitalSelf = self.consume(if: TokenSpec(.self, remapping: .identifier), TokenSpec(.Self, remapping: .identifier)) { + if allowSelfOrCapitalSelfAsIdentifier, + let selfOrCapitalSelf = self.consume(if: TokenSpec(.self, remapping: .identifier), TokenSpec(.Self, remapping: .identifier)) + { return (nil, selfOrCapitalSelf) } if let unknown = self.consume(if: .unknown) { @@ -594,7 +596,9 @@ extension Parser { /// unexpected period (with the extraneous whitespace) and a missing /// period. If there is a newline also set `skipMember` to inform /// callers to not parse any futher member names. - mutating func consumeMemberPeriod(previousNode: (some RawSyntaxNodeProtocol)?) -> (unexpected: RawUnexpectedNodesSyntax?, period: RawTokenSyntax, skipMemberName: Bool) { + mutating func consumeMemberPeriod( + previousNode: (some RawSyntaxNodeProtocol)? + ) -> (unexpected: RawUnexpectedNodesSyntax?, period: RawTokenSyntax, skipMemberName: Bool) { precondition(self.at(.period)) let beforePeriodWhitespace = previousNode?.raw.trailingTriviaByteLength ?? 0 > 0 || self.currentToken.leadingTriviaByteLength > 0 diff --git a/Sources/SwiftParser/Specifiers.swift b/Sources/SwiftParser/Specifiers.swift index ec6b5f3e70f..0f966d22f2e 100644 --- a/Sources/SwiftParser/Specifiers.swift +++ b/Sources/SwiftParser/Specifiers.swift @@ -419,7 +419,10 @@ extension RawAccessorEffectSpecifiersSyntax: RawEffectSpecifiersTrait { } extension TokenConsumer { - mutating func at(anyIn specSet1: SpecSet1.Type, or specSet2: SpecSet2.Type) -> (spec: TokenSpec, handle: TokenConsumptionHandle, matchedSubset: Any.Type)? { + mutating func at( + anyIn specSet1: SpecSet1.Type, + or specSet2: SpecSet2.Type + ) -> (spec: TokenSpec, handle: TokenConsumptionHandle, matchedSubset: Any.Type)? { if let (spec, handle) = self.at(anyIn: specSet1) { return (spec.spec, handle, SpecSet1.self) } else if let (spec, handle) = self.at(anyIn: specSet2) { diff --git a/Sources/SwiftParser/Statements.swift b/Sources/SwiftParser/Statements.swift index edb647c1b10..3bf9b3f2742 100644 --- a/Sources/SwiftParser/Statements.swift +++ b/Sources/SwiftParser/Statements.swift @@ -222,7 +222,11 @@ extension Parser { // Parse the basic expression case. If we have a leading let, var, inout, // borrow, case keyword or an assignment, then we know this is a binding. - guard self.at(.keyword(.let), .keyword(.var), .keyword(.case)) || self.at(.keyword(.inout)) || (lastBindingKind != nil && self.peek().rawTokenKind == .equal) else { + guard + self.at(.keyword(.let), .keyword(.var), .keyword(.case)) + || self.at(.keyword(.inout)) + || (lastBindingKind != nil && self.peek().rawTokenKind == .equal) + else { // If we lack it, then this is theoretically a boolean condition. // However, we also need to handle migrating from Swift 2 syntax, in // which a comma followed by an expression could actually be a pattern diff --git a/Sources/SwiftParser/StringLiterals.swift b/Sources/SwiftParser/StringLiterals.swift index 2555055fdaa..48a90dcd2cb 100644 --- a/Sources/SwiftParser/StringLiterals.swift +++ b/Sources/SwiftParser/StringLiterals.swift @@ -49,7 +49,11 @@ fileprivate class StringLiteralExpressionIndentationChecker { return nil } let hasSufficientIndentation = token.tokenView.leadingTrivia { leadingTrivia -> Bool in - let indentationStartIndex = leadingTrivia.lastIndex(where: { $0 == UInt8(ascii: "\n") || $0 == UInt8(ascii: "\r") })?.advanced(by: 1) ?? leadingTrivia.startIndex + let indentationStartIndex = + leadingTrivia + .lastIndex(where: { $0 == UInt8(ascii: "\n") || $0 == UInt8(ascii: "\r") })? + .advanced(by: 1) + ?? leadingTrivia.startIndex return SyntaxText(rebasing: leadingTrivia[indentationStartIndex...]).hasPrefix(expectedIndentation) } if hasSufficientIndentation { @@ -249,7 +253,9 @@ extension Parser { segment.unexpectedAfterContent, arena: self.arena ) - } else if (segment.content.tokenText == "" || segment.content.tokenText.triviaPieceIfNewline != nil) && segment.content.trailingTriviaPieces.allSatisfy({ $0.isNewline }) { + } else if (segment.content.tokenText == "" || segment.content.tokenText.triviaPieceIfNewline != nil) + && segment.content.trailingTriviaPieces.allSatisfy({ $0.isNewline }) + { // Empty lines don't need to be indented and there's no indentation we need to strip away. } else { let actualIndentation = SyntaxText(rebasing: segment.content.tokenText.prefix(while: { $0 == UInt8(ascii: " ") || $0 == UInt8(ascii: "\t") })) @@ -556,7 +562,12 @@ extension Parser { let (unexpectedBeforeCloseDelimiter, closeDelimiter) = self.parsePoundDelimiter(.rawStringDelimiter, matching: openDelimiter) if openQuote.tokenKind == .multilineStringQuote, !openQuote.isMissing, !closeQuote.isMissing { - let postProcessed = postProcessMultilineStringLiteral(rawStringDelimitersToken: openDelimiter, openQuote: openQuote, segments: segments, closeQuote: closeQuote) + let postProcessed = postProcessMultilineStringLiteral( + rawStringDelimitersToken: openDelimiter, + openQuote: openQuote, + segments: segments, + closeQuote: closeQuote + ) return RawStringLiteralExprSyntax( openDelimiter: openDelimiter, RawUnexpectedNodesSyntax(combining: unexpectedBeforeOpenQuote, postProcessed.unexpectedBeforeOpenQuote, arena: self.arena), diff --git a/Sources/SwiftParser/SyntaxUtils.swift b/Sources/SwiftParser/SyntaxUtils.swift index c8cc852d545..93841d566b4 100644 --- a/Sources/SwiftParser/SyntaxUtils.swift +++ b/Sources/SwiftParser/SyntaxUtils.swift @@ -77,11 +77,22 @@ extension RawUnexpectedNodesSyntax { self.init(syntax1.elements + syntax2.elements, arena: arena) } - init?(combining syntax1: some UnexpectedNodesCombinable, _ syntax2: some UnexpectedNodesCombinable, _ syntax3: some UnexpectedNodesCombinable, arena: __shared SyntaxArena) { + init?( + combining syntax1: some UnexpectedNodesCombinable, + _ syntax2: some UnexpectedNodesCombinable, + _ syntax3: some UnexpectedNodesCombinable, + arena: __shared SyntaxArena + ) { self.init(syntax1.elements + syntax2.elements + syntax3.elements, arena: arena) } - init?(combining syntax1: some UnexpectedNodesCombinable, _ syntax2: some UnexpectedNodesCombinable, _ syntax3: some UnexpectedNodesCombinable, _ syntax4: some UnexpectedNodesCombinable, arena: __shared SyntaxArena) { + init?( + combining syntax1: some UnexpectedNodesCombinable, + _ syntax2: some UnexpectedNodesCombinable, + _ syntax3: some UnexpectedNodesCombinable, + _ syntax4: some UnexpectedNodesCombinable, + arena: __shared SyntaxArena + ) { self.init(syntax1.elements + syntax2.elements + syntax3.elements + syntax4.elements, arena: arena) } } diff --git a/Sources/SwiftParser/TokenPrecedence.swift b/Sources/SwiftParser/TokenPrecedence.swift index ea99e5d462e..a05995c0d67 100644 --- a/Sources/SwiftParser/TokenPrecedence.swift +++ b/Sources/SwiftParser/TokenPrecedence.swift @@ -219,7 +219,8 @@ enum TokenPrecedence: Comparable { // Operator stuff .operator, .precedencegroup, // Declaration Modifiers - .__consuming, .final, .required, .optional, .lazy, .dynamic, .infix, .postfix, .prefix, .mutating, .nonmutating, .convenience, .override, .package, .open, .__setter_access, .indirect, .nonisolated, .distributed, ._local, + .__consuming, .final, .required, .optional, .lazy, .dynamic, .infix, .postfix, .prefix, .mutating, .nonmutating, .convenience, .override, .package, .open, + .__setter_access, .indirect, .nonisolated, .distributed, ._local, // Misc .import: self = .declKeyword diff --git a/Sources/SwiftParser/TopLevel.swift b/Sources/SwiftParser/TopLevel.swift index 13648386019..90baaeb7ea0 100644 --- a/Sources/SwiftParser/TopLevel.swift +++ b/Sources/SwiftParser/TopLevel.swift @@ -58,7 +58,11 @@ extension Parser { } extension Parser { - mutating func parseCodeBlockItemList(isAtTopLevel: Bool = false, allowInitDecl: Bool = true, until stopCondition: (inout Parser) -> Bool) -> RawCodeBlockItemListSyntax { + mutating func parseCodeBlockItemList( + isAtTopLevel: Bool = false, + allowInitDecl: Bool = true, + until stopCondition: (inout Parser) -> Bool + ) -> RawCodeBlockItemListSyntax { var elements = [RawCodeBlockItemSyntax]() var loopProgress = LoopProgressCondition() while !stopCondition(&self), loopProgress.evaluate(currentToken) { diff --git a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift index 5c528d9e503..44fcbe84d69 100644 --- a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift @@ -51,7 +51,8 @@ public enum StaticTokenError: String, DiagnosticMessage { case invalidIdentifierStartCharacter = "an identifier cannot begin with this character" case invalidNumberOfHexDigitsInUnicodeEscape = #"\u{...} escape sequence expects between 1 and 8 hex digits"# case invalidUtf8 = "invalid UTF-8 found in source file" - case tokenDiagnosticOffsetOverflow = "the lexer dicovered an error in this token but was not able to represent its offset due to overflow; please split the token" + case tokenDiagnosticOffsetOverflow = + "the lexer dicovered an error in this token but was not able to represent its offset due to overflow; please split the token" case sourceConflictMarker = "source control conflict marker in source file" case unexpectedBlockCommentEnd = "unexpected end of block comment" case unicodeCurlyQuote = #"unicode curly quote found; use '"' instead"# diff --git a/Sources/SwiftParserDiagnostics/MissingNodesError.swift b/Sources/SwiftParserDiagnostics/MissingNodesError.swift index ecd5252a2ae..5e0845a892b 100644 --- a/Sources/SwiftParserDiagnostics/MissingNodesError.swift +++ b/Sources/SwiftParserDiagnostics/MissingNodesError.swift @@ -398,7 +398,10 @@ extension ParseDiagnosticsGenerator { if missingNodes.count == 1, let token = missingNodes.last?.as(TokenSyntax.self), let matchingStartMarkerKind = token.tokenKind.matchingStartMarkerKind, - let startToken = token.parent?.children(viewMode: .sourceAccurate).lazy.compactMap({ $0.as(TokenSyntax.self) }).first(where: { $0.tokenKind == matchingStartMarkerKind }) + let startToken = token.parent?.children(viewMode: .sourceAccurate) + .lazy + .compactMap({ $0.as(TokenSyntax.self) }) + .first(where: { $0.tokenKind == matchingStartMarkerKind }) { notes.append(Note(node: Syntax(startToken), message: MatchingOpeningTokenNote(openingToken: startToken))) } diff --git a/Sources/SwiftParserDiagnostics/MissingTokenError.swift b/Sources/SwiftParserDiagnostics/MissingTokenError.swift index c4870877034..90d0f5df6ad 100644 --- a/Sources/SwiftParserDiagnostics/MissingTokenError.swift +++ b/Sources/SwiftParserDiagnostics/MissingTokenError.swift @@ -56,7 +56,9 @@ extension ParseDiagnosticsGenerator { changes: [ .replace( oldNode: Syntax(invalidToken), - newNode: Syntax(TokenSyntax.identifier("`\(invalidToken.text)`", leadingTrivia: invalidToken.leadingTrivia, trailingTrivia: invalidToken.trailingTrivia)) + newNode: Syntax( + TokenSyntax.identifier("`\(invalidToken.text)`", leadingTrivia: invalidToken.leadingTrivia, trailingTrivia: invalidToken.trailingTrivia) + ) ) ] ) diff --git a/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift b/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift index 4dbd9cb7fd4..ecc795a82ba 100644 --- a/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift +++ b/Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift @@ -344,7 +344,12 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { FixIt( message: .joinIdentifiers, changes: [ - FixIt.MultiNodeChange(.replace(oldNode: Syntax(previousToken), newNode: Syntax(TokenSyntax(.identifier(joined), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)))), + FixIt.MultiNodeChange( + .replace( + oldNode: Syntax(previousToken), + newNode: Syntax(TokenSyntax(.identifier(joined), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)) + ) + ), .makeMissing(tokens), ] ) @@ -355,7 +360,12 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { FixIt( message: .joinIdentifiersWithCamelCase, changes: [ - FixIt.MultiNodeChange(.replace(oldNode: Syntax(previousToken), newNode: Syntax(TokenSyntax(.identifier(joinedUsingCamelCase), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)))), + FixIt.MultiNodeChange( + .replace( + oldNode: Syntax(previousToken), + newNode: Syntax(TokenSyntax(.identifier(joinedUsingCamelCase), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)) + ) + ), .makeMissing(tokens), ] ) @@ -500,7 +510,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { AvailabilityConditionAsExpression(availabilityToken: node.availabilityKeyword, negatedAvailabilityToken: negatedAvailabilityKeyword), fixIts: [ FixIt( - message: ReplaceTokensFixIt(replaceTokens: getTokens(between: node.availabilityKeyword, and: falseKeyword), replacements: getTokens(between: negatedAvailability.availabilityKeyword, and: negatedAvailability.rightParen)), + message: ReplaceTokensFixIt( + replaceTokens: getTokens(between: node.availabilityKeyword, and: falseKeyword), + replacements: getTokens(between: negatedAvailability.availabilityKeyword, and: negatedAvailability.rightParen) + ), changes: [ .replace(oldNode: Syntax(node), newNode: Syntax(negatedAvailability)) ] @@ -728,7 +741,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return .skipChildren } if node.floatingDigits.presence == .missing, - let (period, integerLiteral) = node.unexpectedAfterFloatingDigits?.twoTokens(firstSatisfying: { $0.tokenKind == .period }, secondSatisfying: { $0.tokenKind.isIntegerLiteral }) + let (period, integerLiteral) = node.unexpectedAfterFloatingDigits?.twoTokens( + firstSatisfying: { $0.tokenKind == .period }, + secondSatisfying: { $0.tokenKind.isIntegerLiteral } + ) { addDiagnostic( node, @@ -954,7 +970,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return .skipChildren } - if node.conditions.count == 1, node.conditions.first?.as(ConditionElementSyntax.self)?.condition.is(MissingExprSyntax.self) == true, !node.body.leftBrace.isMissingAllTokens { + if node.conditions.count == 1, + node.conditions.first?.as(ConditionElementSyntax.self)?.condition.is(MissingExprSyntax.self) == true, + !node.body.leftBrace.isMissingAllTokens + { addDiagnostic(node.conditions, MissingConditionInStatement(node: node), handledNodes: [node.conditions.id]) } @@ -1122,8 +1141,14 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { .missingFixityInOperatorDeclaration, fixIts: [ FixIt(message: InsertFixIt(tokenToBeInserted: .keyword(.prefix)), changes: .makePresent(node.fixity)), - FixIt(message: InsertFixIt(tokenToBeInserted: .keyword(.infix)), changes: [FixIt.MultiNodeChange(.replace(oldNode: Syntax(node.fixity), newNode: Syntax(TokenSyntax(.keyword(.infix), presence: .present))))]), - FixIt(message: InsertFixIt(tokenToBeInserted: .keyword(.postfix)), changes: [FixIt.MultiNodeChange(.replace(oldNode: Syntax(node.fixity), newNode: Syntax(TokenSyntax(.keyword(.postfix), presence: .present))))]), + FixIt( + message: InsertFixIt(tokenToBeInserted: .keyword(.infix)), + changes: [FixIt.MultiNodeChange(.replace(oldNode: Syntax(node.fixity), newNode: Syntax(TokenSyntax(.keyword(.infix), presence: .present))))] + ), + FixIt( + message: InsertFixIt(tokenToBeInserted: .keyword(.postfix)), + changes: [FixIt.MultiNodeChange(.replace(oldNode: Syntax(node.fixity), newNode: Syntax(TokenSyntax(.keyword(.postfix), presence: .present))))] + ), ], handledNodes: [node.fixity.id] ) @@ -1650,7 +1675,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return .skipChildren } - if node.conditions.count == 1, node.conditions.first?.as(ConditionElementSyntax.self)?.condition.is(MissingExprSyntax.self) == true, !node.body.leftBrace.isMissingAllTokens { + if node.conditions.count == 1, + node.conditions.first?.as(ConditionElementSyntax.self)?.condition.is(MissingExprSyntax.self) == true, + !node.body.leftBrace.isMissingAllTokens + { addDiagnostic(node.conditions, MissingConditionInStatement(node: node), handledNodes: [node.conditions.id]) } diff --git a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift index 75e10e74c2b..dc25ddc4839 100644 --- a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift @@ -426,7 +426,8 @@ public struct NegatedAvailabilityCondition: ParserError { public let negatedAvailabilityKeyword: TokenSyntax public var message: String { - return "\(nodesDescription([avaialabilityCondition], format: false)) cannot be used in an expression; did you mean \(nodesDescription([negatedAvailabilityKeyword], format: false))?" + return + "\(nodesDescription([avaialabilityCondition], format: false)) cannot be used in an expression; did you mean \(nodesDescription([negatedAvailabilityKeyword], format: false))?" } } @@ -486,7 +487,9 @@ public struct UnexpectedNodesError: ParserError { public var message: String { var message = "unexpected \(unexpectedNodes.shortSingleLineContentDescription)" if let parent = unexpectedNodes.parent { - if let parentTypeName = parent.nodeTypeNameForDiagnostics(allowBlockNames: false), parent.children(viewMode: .sourceAccurate).first?.id == unexpectedNodes.id { + if let parentTypeName = parent.nodeTypeNameForDiagnostics(allowBlockNames: false), + parent.children(viewMode: .sourceAccurate).first?.id == unexpectedNodes.id + { message += " before \(parentTypeName)" } else if let parentTypeName = parent.ancestorOrSelf(mapping: { $0.nodeTypeNameForDiagnostics(allowBlockNames: false) }) { message += " in \(parentTypeName)" diff --git a/Sources/SwiftSyntax/Raw/RawSyntax.swift b/Sources/SwiftSyntax/Raw/RawSyntax.swift index 68ced4fa8ae..f8be702e513 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntax.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntax.swift @@ -110,7 +110,15 @@ internal struct RawSyntaxData { private var tokenDiagnosticKind: TokenDiagnostic.Kind? private var tokenDiagnosticByteOffset: UInt16 - init(tokenKind: RawTokenKind, tokenText: SyntaxText, triviaPieces: RawTriviaPieceBuffer, numLeadingTrivia: UInt32, byteLength: UInt32, presence: SourcePresence, tokenDiagnostic: TokenDiagnostic?) { + init( + tokenKind: RawTokenKind, + tokenText: SyntaxText, + triviaPieces: RawTriviaPieceBuffer, + numLeadingTrivia: UInt32, + byteLength: UInt32, + presence: SourcePresence, + tokenDiagnostic: TokenDiagnostic? + ) { self.tokenKind = tokenKind self.tokenText = tokenText self.triviaPieces = triviaPieces diff --git a/Sources/SwiftSyntax/SourceLength.swift b/Sources/SwiftSyntax/SourceLength.swift index 1879bb7eb7f..46e88e38521 100644 --- a/Sources/SwiftSyntax/SourceLength.swift +++ b/Sources/SwiftSyntax/SourceLength.swift @@ -61,9 +61,7 @@ public struct SourceLength: Comparable { extension AbsolutePosition { /// Determine the AbsolutePosition by advancing the `lhs` by the given source /// length. - public static func + (lhs: AbsolutePosition, rhs: SourceLength) - -> AbsolutePosition - { + public static func + (lhs: AbsolutePosition, rhs: SourceLength) -> AbsolutePosition { let utf8Offset = lhs.utf8Offset + rhs.utf8Length return AbsolutePosition(utf8Offset: utf8Offset) } diff --git a/Sources/SwiftSyntax/SyntaxChildren.swift b/Sources/SwiftSyntax/SyntaxChildren.swift index ff0b68faae2..e9cd45ff6fe 100644 --- a/Sources/SwiftSyntax/SyntaxChildren.swift +++ b/Sources/SwiftSyntax/SyntaxChildren.swift @@ -86,9 +86,7 @@ public struct SyntaxChildrenIndex: Comparable, ExpressibleByNilLiteral { } /// Returns `true` if `lhs` occurs before `rhs`. - public static func < (lhs: SyntaxChildrenIndex, rhs: SyntaxChildrenIndex) - -> Bool - { + public static func < (lhs: SyntaxChildrenIndex, rhs: SyntaxChildrenIndex) -> Bool { switch (lhs.data, rhs.data) { case (.some(let lhsData), .some(let rhsData)): return lhsData < rhsData @@ -233,9 +231,7 @@ struct RawSyntaxChildren: BidirectionalCollection { } } - func distance(from start: SyntaxChildrenIndex, to end: SyntaxChildrenIndex) - -> Int - { + func distance(from start: SyntaxChildrenIndex, to end: SyntaxChildrenIndex) -> Int { switch (start.data, end.data) { case (.some(let start), .some(let end)): return Int(end.indexInParent - start.indexInParent) @@ -248,9 +244,7 @@ struct RawSyntaxChildren: BidirectionalCollection { } } - subscript(index: SyntaxChildrenIndex) - -> (raw: RawSyntax?, syntaxInfo: AbsoluteSyntaxInfo) - { + subscript(index: SyntaxChildrenIndex) -> (raw: RawSyntax?, syntaxInfo: AbsoluteSyntaxInfo) { // Accessing the end index is undefined. So we can assume a non-end index. let index = index.data! @@ -334,9 +328,7 @@ struct NonNilRawSyntaxChildren: BidirectionalCollection { after index: SyntaxChildrenIndex, in children: RawSyntaxChildren, viewMode: SyntaxTreeViewMode - ) - -> SyntaxChildrenIndex - { + ) -> SyntaxChildrenIndex { var advancedIndex = index while true { if advancedIndex != children.endIndex { @@ -361,9 +353,7 @@ struct NonNilRawSyntaxChildren: BidirectionalCollection { before index: SyntaxChildrenIndex, in children: RawSyntaxChildren, viewMode: SyntaxTreeViewMode - ) - -> SyntaxChildrenIndex - { + ) -> SyntaxChildrenIndex { var reversedIndex = index while true { if reversedIndex < children.endIndex, diff --git a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift index b6ff4b16bde..64c02c866eb 100644 --- a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift +++ b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift @@ -318,7 +318,10 @@ extension StringLiteralExprSyntax { } } - let escapedContent = content.escapingForStringLiteral(usingDelimiter: closeDelimiter?.text ?? "", isMultiline: openQuote.tokenView.rawKind == .multilineStringQuote) + let escapedContent = content.escapingForStringLiteral( + usingDelimiter: closeDelimiter?.text ?? "", + isMultiline: openQuote.tokenView.rawKind == .multilineStringQuote + ) let contentToken = TokenSyntax.stringSegment(escapedContent) let segment = StringSegmentSyntax(content: contentToken) let segments = StringLiteralSegmentsSyntax([.stringSegment(segment)]) diff --git a/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift b/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift index 07fff38f243..5b5fb0628b2 100644 --- a/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift +++ b/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift @@ -197,7 +197,11 @@ public extension IfExprSyntax { /// This function takes care of inserting the braces as well. /// /// Throws an error if `header` does not start an `if` expression. E.g. if calling `try IfExprSyntax("while true") {}` - init(_ header: PartialSyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax, @CodeBlockItemListBuilder `else` elseBuilder: () throws -> CodeBlockItemListSyntax? = { nil }) throws { + init( + _ header: PartialSyntaxNodeString, + @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax, + @CodeBlockItemListBuilder `else` elseBuilder: () throws -> CodeBlockItemListSyntax? = { nil } + ) throws { let expr = ExprSyntax("\(header) {}") guard let ifExpr = expr.as(Self.self) else { throw SyntaxStringInterpolationError.producedInvalidNodeType(expectedType: Self.self, actualNode: expr) diff --git a/Sources/SwiftSyntaxMacros/MacroSystem.swift b/Sources/SwiftSyntaxMacros/MacroSystem.swift index 311d253ac2e..3e474271c79 100644 --- a/Sources/SwiftSyntaxMacros/MacroSystem.swift +++ b/Sources/SwiftSyntaxMacros/MacroSystem.swift @@ -109,7 +109,12 @@ class MacroApplication: SyntaxRewriter { return true } - return !(macro is PeerMacro.Type || macro is MemberMacro.Type || macro is AccessorMacro.Type || macro is MemberAttributeMacro.Type || macro is ConformanceMacro.Type) + return + !(macro is PeerMacro.Type + || macro is MemberMacro.Type + || macro is AccessorMacro.Type + || macro is MemberAttributeMacro.Type + || macro is ConformanceMacro.Type) } if newAttributes.isEmpty { diff --git a/Sources/swift-parser-cli/swift-parser-cli.swift b/Sources/swift-parser-cli/swift-parser-cli.swift index e0c45d50f59..4be717db553 100644 --- a/Sources/swift-parser-cli/swift-parser-cli.swift +++ b/Sources/swift-parser-cli/swift-parser-cli.swift @@ -157,7 +157,8 @@ class VerifyRoundTrip: ParsableCommand { class PerformanceTest: ParsableCommand { static var configuration = CommandConfiguration( commandName: "performance-test", - abstract: "Parse all .swift files in '--directory' and its subdirectories '--iteration' times and output the average time (in milliseconds) one iteration took." + abstract: + "Parse all .swift files in '--directory' and its subdirectories '--iteration' times and output the average time (in milliseconds) one iteration took." ) required init() {} diff --git a/Tests/SwiftParserDiagnosticsTest/DiagnosticInfrastructureTests.swift b/Tests/SwiftParserDiagnosticsTest/DiagnosticInfrastructureTests.swift index 3c7a43fcd3c..f45306e82aa 100644 --- a/Tests/SwiftParserDiagnosticsTest/DiagnosticInfrastructureTests.swift +++ b/Tests/SwiftParserDiagnosticsTest/DiagnosticInfrastructureTests.swift @@ -25,7 +25,10 @@ public class DiagnosticInfrastructureTests: XCTestCase { XCTAssertEqual(diag.message, "My test diagnostic") XCTAssertEqual(diag.severity, .error) - XCTAssertEqual(StaticParserError.caseOutsideOfSwitchOrEnum.diagnosticID, MessageID(domain: "SwiftParser", id: "StaticParserError.caseOutsideOfSwitchOrEnum")) + XCTAssertEqual( + StaticParserError.caseOutsideOfSwitchOrEnum.diagnosticID, + MessageID(domain: "SwiftParser", id: "StaticParserError.caseOutsideOfSwitchOrEnum") + ) XCTAssertEqual(StaticParserError.caseOutsideOfSwitchOrEnum.severity, .error) XCTAssertEqual( diff --git a/Tests/SwiftParserTest/Assertions.swift b/Tests/SwiftParserTest/Assertions.swift index cbd466b77bb..682969e5e75 100644 --- a/Tests/SwiftParserTest/Assertions.swift +++ b/Tests/SwiftParserTest/Assertions.swift @@ -337,7 +337,11 @@ func assertLocation( let actualLocation = location let expectedLocation = locationConverter.location(for: AbsolutePosition(utf8Offset: markerLoc)) if actualLocation.line != expectedLocation.line || actualLocation.column != expectedLocation.column { - XCTFail("Expected location \(expectedLocation.line):\(expectedLocation.column) but got \(actualLocation.line):\(actualLocation.column)", file: file, line: line) + XCTFail( + "Expected location \(expectedLocation.line):\(expectedLocation.column) but got \(actualLocation.line):\(actualLocation.column)", + file: file, + line: line + ) } } else { XCTFail("Did not find marker \(locationMarker) in the source code", file: file, line: line) @@ -578,7 +582,13 @@ func assertParse( if let expectedSubstructure { let subtreeMatcher = SubtreeMatcher(Syntax(tree), markers: markerLocations) do { - try subtreeMatcher.assertSameStructure(afterMarker: substructureAfterMarker, Syntax(expectedSubstructure), includeTrivia: options.contains(.substructureCheckTrivia), file: file, line: line) + try subtreeMatcher.assertSameStructure( + afterMarker: substructureAfterMarker, + Syntax(expectedSubstructure), + includeTrivia: options.contains(.substructureCheckTrivia), + file: file, + line: line + ) } catch { XCTFail("Matching for a subtree failed with error: \(error)", file: file, line: line) } diff --git a/Tests/SwiftParserTest/DeclarationTests.swift b/Tests/SwiftParserTest/DeclarationTests.swift index 2bfd92d4933..9bfa5b54206 100644 --- a/Tests/SwiftParserTest/DeclarationTests.swift +++ b/Tests/SwiftParserTest/DeclarationTests.swift @@ -53,7 +53,11 @@ final class DeclarationTests: XCTestCase { r3️⃣ """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "keyword 'where' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "keyword 'where' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected '(' to start parameter clause", fixIts: ["insert '('"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected ':' and type in parameter", fixIts: ["insert ':' and type"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected ')' to end parameter clause", fixIts: ["insert ')'"]), @@ -2149,7 +2153,10 @@ final class DeclarationTests: XCTestCase { Syntax( SuppressedTypeSyntax( withoutTilde: .prefixOperator("~"), - patternType: FunctionTypeSyntax(arguments: [TupleTypeElementSyntax(type: TypeSyntax("Int"))], output: ReturnClauseSyntax(returnType: TypeSyntax("Bool"))) + patternType: FunctionTypeSyntax( + arguments: [TupleTypeElementSyntax(type: TypeSyntax("Int"))], + output: ReturnClauseSyntax(returnType: TypeSyntax("Bool")) + ) ) ) ) @@ -2177,7 +2184,12 @@ final class DeclarationTests: XCTestCase { DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected code before modifier"), DiagnosticSpec(locationMarker: "2️⃣", message: "expected 'func' in function", fixIts: ["insert 'func'"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]), - DiagnosticSpec(locationMarker: "4️⃣", message: "expected '}' to end class", notes: [NoteSpec(message: "to match this opening '{'")], fixIts: ["insert '}'"]), + DiagnosticSpec( + locationMarker: "4️⃣", + message: "expected '}' to end class", + notes: [NoteSpec(message: "to match this opening '{'")], + fixIts: ["insert '}'"] + ), ], fixedSource: """ diff --git a/Tests/SwiftParserTest/ExpressionTests.swift b/Tests/SwiftParserTest/ExpressionTests.swift index fdc62a4e23f..1d739f8bc46 100644 --- a/Tests/SwiftParserTest/ExpressionTests.swift +++ b/Tests/SwiftParserTest/ExpressionTests.swift @@ -1201,7 +1201,9 @@ final class ExpressionTests: XCTestCase { StringLiteralExprSyntax( openQuote: .multilineStringQuoteToken(leadingTrivia: .spaces(2), trailingTrivia: .newline), segments: StringLiteralSegmentsSyntax([ - .stringSegment(StringSegmentSyntax(content: .stringSegment("line 1 ", leadingTrivia: .spaces(2), trailingTrivia: [.backslashes(1), .newlines(1)]))), + .stringSegment( + StringSegmentSyntax(content: .stringSegment("line 1 ", leadingTrivia: .spaces(2), trailingTrivia: [.backslashes(1), .newlines(1)])) + ), .stringSegment(StringSegmentSyntax(content: .stringSegment("line 2", leadingTrivia: .spaces(2), trailingTrivia: .newline))), ]), closeQuote: .multilineStringQuoteToken(leadingTrivia: .spaces(2)) @@ -1384,7 +1386,11 @@ final class ExpressionTests: XCTestCase { assertParse( "a 1️⃣\u{a0}+ 2", diagnostics: [ - DiagnosticSpec(message: "non-breaking space (U+00A0) used instead of regular space", severity: .warning, fixIts: ["replace non-breaking space with ' '"]) + DiagnosticSpec( + message: "non-breaking space (U+00A0) used instead of regular space", + severity: .warning, + fixIts: ["replace non-breaking space with ' '"] + ) ], fixedSource: "a + 2" ) diff --git a/Tests/SwiftParserTest/Parser+EntryTests.swift b/Tests/SwiftParserTest/Parser+EntryTests.swift index 7323f990de6..b8fb9231c35 100644 --- a/Tests/SwiftParserTest/Parser+EntryTests.swift +++ b/Tests/SwiftParserTest/Parser+EntryTests.swift @@ -62,7 +62,11 @@ public class EntryTests: XCTestCase { ), substructureAfterMarker: "3️⃣", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "operator must be declared as 'prefix', 'postfix', or 'infix'", fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "operator must be declared as 'prefix', 'postfix', or 'infix'", + fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "'test' is considered an identifier and must not appear within an operator name"), DiagnosticSpec(locationMarker: "3️⃣", message: "operator should not be declared with body", fixIts: ["remove operator body"]), ], diff --git a/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift b/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift index 5c0cd63b8cb..9e738ac3fbe 100644 --- a/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift +++ b/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift @@ -65,7 +65,10 @@ final class AvailabilityQueryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "availability condition cannot be used in an expression; did you mean '#unavailable'?", fixIts: ["replace '!#available' with '#unavailable'"]) + DiagnosticSpec( + message: "availability condition cannot be used in an expression; did you mean '#unavailable'?", + fixIts: ["replace '!#available' with '#unavailable'"] + ) ], fixedSource: """ if #unavailable(OSX 10.52, *) { @@ -81,7 +84,10 @@ final class AvailabilityQueryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "availability condition cannot be used in an expression; did you mean '#unavailable'?", fixIts: ["replace '!#available' with '#unavailable'"]) + DiagnosticSpec( + message: "availability condition cannot be used in an expression; did you mean '#unavailable'?", + fixIts: ["replace '!#available' with '#unavailable'"] + ) ], fixedSource: """ if let _ = Optional(5), #unavailable(OSX 10.52, *) { diff --git a/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift b/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift index 6f95868f186..6e0171bc0c1 100644 --- a/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift +++ b/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift @@ -32,7 +32,10 @@ final class DiagnoseDynamicReplacementTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected '(', @_dynamicReplacement argument, and ')' in attribute", fixIts: ["insert '(', @_dynamicReplacement argument, and ')'"]) + DiagnosticSpec( + message: "expected '(', @_dynamicReplacement argument, and ')' in attribute", + fixIts: ["insert '(', @_dynamicReplacement argument, and ')'"] + ) ], fixedSource: """ @_dynamicReplacement(for: <#identifier#>) diff --git a/Tests/SwiftParserTest/translated/IdentifiersTests.swift b/Tests/SwiftParserTest/translated/IdentifiersTests.swift index e369a6ed213..e02a268d451 100644 --- a/Tests/SwiftParserTest/translated/IdentifiersTests.swift +++ b/Tests/SwiftParserTest/translated/IdentifiersTests.swift @@ -166,7 +166,11 @@ final class IdentifiersTests: XCTestCase { func 2️⃣_(_ x: Int) {} """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "keyword 'public' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "keyword 'public' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "'_' cannot be used as an identifier here"), ], fixedSource: """ diff --git a/Tests/SwiftParserTest/translated/OperatorDeclTests.swift b/Tests/SwiftParserTest/translated/OperatorDeclTests.swift index c182335d2f5..8ef7683afd2 100644 --- a/Tests/SwiftParserTest/translated/OperatorDeclTests.swift +++ b/Tests/SwiftParserTest/translated/OperatorDeclTests.swift @@ -135,7 +135,10 @@ final class OperatorDeclTests: XCTestCase { 1️⃣operator ++*** : A """, diagnostics: [ - DiagnosticSpec(message: "operator must be declared as 'prefix', 'postfix', or 'infix'", fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"]) + DiagnosticSpec( + message: "operator must be declared as 'prefix', 'postfix', or 'infix'", + fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"] + ) ], fixedSource: """ @@ -150,7 +153,11 @@ final class OperatorDeclTests: XCTestCase { 1️⃣operator +*+++ 2️⃣{ } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "operator must be declared as 'prefix', 'postfix', or 'infix'", fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "operator must be declared as 'prefix', 'postfix', or 'infix'", + fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "operator should not be declared with body", fixIts: ["remove operator body"]), ], fixedSource: """ @@ -165,7 +172,11 @@ final class OperatorDeclTests: XCTestCase { 1️⃣operator +*++* : A 2️⃣{ } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "operator must be declared as 'prefix', 'postfix', or 'infix'", fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "operator must be declared as 'prefix', 'postfix', or 'infix'", + fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "operator should not be declared with body", fixIts: ["remove operator body"]), ], fixedSource: """ @@ -589,7 +600,11 @@ final class OperatorDeclTests: XCTestCase { """, diagnostics: [ DiagnosticSpec(message: "unexpected code 'dynamic' before operator declaration"), - DiagnosticSpec(locationMarker: "2️⃣", message: "operator must be declared as 'prefix', 'postfix', or 'infix'", fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "operator must be declared as 'prefix', 'postfix', or 'infix'", + fixIts: ["insert 'prefix'", "insert 'infix'", "insert 'postfix'"] + ), ], fixedSource: """ diff --git a/Tests/SwiftParserTest/translated/RecoveryTests.swift b/Tests/SwiftParserTest/translated/RecoveryTests.swift index 5cfed060d3d..a39fc0afcbe 100644 --- a/Tests/SwiftParserTest/translated/RecoveryTests.swift +++ b/Tests/SwiftParserTest/translated/RecoveryTests.swift @@ -504,7 +504,11 @@ final class RecoveryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected pattern, 'in', and expression in 'for' statement", fixIts: ["insert pattern, 'in', and expression"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected pattern, 'in', and expression in 'for' statement", + fixIts: ["insert pattern, 'in', and expression"] + ) ], fixedSource: """ for <#pattern#> in <#expression#> { @@ -521,7 +525,11 @@ final class RecoveryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected pattern, 'in', and expression in 'for' statement", fixIts: ["insert pattern, 'in', and expression"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected pattern, 'in', and expression in 'for' statement", + fixIts: ["insert pattern, 'in', and expression"] + ) ], fixedSource: """ for <#pattern#> in <#expression#> @@ -570,7 +578,11 @@ final class RecoveryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "keyword 'in' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "keyword 'in' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected 'in' and expression in 'for' statement", fixIts: ["insert 'in' and expression"]), ], fixedSource: """ @@ -603,7 +615,11 @@ final class RecoveryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "keyword 'for' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "keyword 'for' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected Sequence expression for for-each loop", fixIts: ["insert expression"]), ], fixedSource: """ @@ -656,7 +672,11 @@ final class RecoveryTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected pattern, 'in', and expression in 'for' statement", fixIts: ["insert pattern, 'in', and expression"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected pattern, 'in', and expression in 'for' statement", + fixIts: ["insert pattern, 'in', and expression"] + ), DiagnosticSpec(locationMarker: "1️⃣", message: "expected '{' in 'for' statement", fixIts: ["insert '{'"]), DiagnosticSpec(locationMarker: "2️⃣", message: "standalone ';' statements are not allowed", fixIts: ["remove ';'"]), ], diff --git a/Tests/SwiftParserTest/translated/SwitchTests.swift b/Tests/SwiftParserTest/translated/SwitchTests.swift index bfcb21e39c7..7a81e9267eb 100644 --- a/Tests/SwiftParserTest/translated/SwitchTests.swift +++ b/Tests/SwiftParserTest/translated/SwitchTests.swift @@ -34,7 +34,11 @@ final class SwitchTests: XCTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected expression and '{}' to end 'switch' statement", fixIts: ["insert expression and '{}'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier and function signature in function", fixIts: ["insert identifier and function signature"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier and function signature in function", + fixIts: ["insert identifier and function signature"] + ), ], fixedSource: """ func parseError1(x: Int) { diff --git a/Tests/SwiftRefactorTest/ReformatIntegerLiteral.swift b/Tests/SwiftRefactorTest/ReformatIntegerLiteral.swift index ccc7cdf555f..c3958eb8fe6 100644 --- a/Tests/SwiftRefactorTest/ReformatIntegerLiteral.swift +++ b/Tests/SwiftRefactorTest/ReformatIntegerLiteral.swift @@ -20,16 +20,30 @@ import _SwiftSyntaxTestSupport final class ReformatIntegerLiteralTest: XCTestCase { func testSeparatorPlacement() throws { let tests = [ - (#line, literal: ExprSyntax("0b101010101").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0b1_0101_0101").cast(IntegerLiteralExprSyntax.self)), - (#line, literal: ExprSyntax("0xFFFFFFFF").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xFFFF_FFFF").cast(IntegerLiteralExprSyntax.self)), + ( + #line, literal: ExprSyntax("0b101010101").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("0b1_0101_0101").cast(IntegerLiteralExprSyntax.self) + ), + ( + #line, literal: ExprSyntax("0xFFFFFFFF").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xFFFF_FFFF").cast(IntegerLiteralExprSyntax.self) + ), (#line, literal: ExprSyntax("0xFFFFF").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xF_FFFF").cast(IntegerLiteralExprSyntax.self)), (#line, literal: ExprSyntax("0o777777").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0o777_777").cast(IntegerLiteralExprSyntax.self)), - (#line, literal: ExprSyntax("424242424242").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("424_242_424_242").cast(IntegerLiteralExprSyntax.self)), + ( + #line, literal: ExprSyntax("424242424242").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("424_242_424_242").cast(IntegerLiteralExprSyntax.self) + ), (#line, literal: ExprSyntax("100").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("100").cast(IntegerLiteralExprSyntax.self)), - (#line, literal: ExprSyntax("0xF_F_F_F_F_F_F_F").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xFFFF_FFFF").cast(IntegerLiteralExprSyntax.self)), + ( + #line, literal: ExprSyntax("0xF_F_F_F_F_F_F_F").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("0xFFFF_FFFF").cast(IntegerLiteralExprSyntax.self) + ), (#line, literal: ExprSyntax("0xFF_F_FF").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xF_FFFF").cast(IntegerLiteralExprSyntax.self)), (#line, literal: ExprSyntax("0o7_77777").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0o777_777").cast(IntegerLiteralExprSyntax.self)), - (#line, literal: ExprSyntax("4_24242424242").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("424_242_424_242").cast(IntegerLiteralExprSyntax.self)), + ( + #line, literal: ExprSyntax("4_24242424242").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("424_242_424_242").cast(IntegerLiteralExprSyntax.self) + ), ] for (line, literal, expectation) in tests { @@ -40,11 +54,20 @@ final class ReformatIntegerLiteralTest: XCTestCase { func testSeparatorRemoval() throws { let tests = [ - (#line, literal: ExprSyntax("0b1_0_1_0_1_0_1_0_1").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0b101010101").cast(IntegerLiteralExprSyntax.self)), - (#line, literal: ExprSyntax("0xFFF_F_FFFF").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xFFFFFFFF").cast(IntegerLiteralExprSyntax.self)), + ( + #line, literal: ExprSyntax("0b1_0_1_0_1_0_1_0_1").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("0b101010101").cast(IntegerLiteralExprSyntax.self) + ), + ( + #line, literal: ExprSyntax("0xFFF_F_FFFF").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("0xFFFFFFFF").cast(IntegerLiteralExprSyntax.self) + ), (#line, literal: ExprSyntax("0xFF_FFF").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0xFFFFF").cast(IntegerLiteralExprSyntax.self)), (#line, literal: ExprSyntax("0o777_777").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("0o777777").cast(IntegerLiteralExprSyntax.self)), - (#line, literal: ExprSyntax("424_242_424_242").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("424242424242").cast(IntegerLiteralExprSyntax.self)), + ( + #line, literal: ExprSyntax("424_242_424_242").cast(IntegerLiteralExprSyntax.self), + expectation: ExprSyntax("424242424242").cast(IntegerLiteralExprSyntax.self) + ), (#line, literal: ExprSyntax("100").cast(IntegerLiteralExprSyntax.self), expectation: ExprSyntax("100").cast(IntegerLiteralExprSyntax.self)), ] diff --git a/Tests/SwiftSyntaxBuilderTest/Assertions.swift b/Tests/SwiftSyntaxBuilderTest/Assertions.swift index d7fe0aee3b0..b548e78faac 100644 --- a/Tests/SwiftSyntaxBuilderTest/Assertions.swift +++ b/Tests/SwiftSyntaxBuilderTest/Assertions.swift @@ -16,7 +16,13 @@ import _SwiftSyntaxTestSupport import XCTest -func assertBuildResult(_ buildable: T, _ expectedResult: String, trimTrailingWhitespace: Bool = true, file: StaticString = #file, line: UInt = #line) { +func assertBuildResult( + _ buildable: T, + _ expectedResult: String, + trimTrailingWhitespace: Bool = true, + file: StaticString = #file, + line: UInt = #line +) { var buildableDescription = buildable.formatted().description var expectedResult = expectedResult if trimTrailingWhitespace { diff --git a/Tests/SwiftSyntaxTest/VisitorTests.swift b/Tests/SwiftSyntaxTest/VisitorTests.swift index ac481ac229d..e602ca964ab 100644 --- a/Tests/SwiftSyntaxTest/VisitorTests.swift +++ b/Tests/SwiftSyntaxTest/VisitorTests.swift @@ -66,7 +66,9 @@ public class VisitorTests: XCTestCase { UnexpectedNodesSyntax([Syntax(TokenSyntax.identifier("starting")), Syntax(TokenSyntax.integerLiteral("unexpected"))]), returnKeyword: .keyword(.return, trailingTrivia: [.spaces(1)]), UnexpectedNodesSyntax([Syntax(TokenSyntax.identifier("middle"))]), - expression: ExprSyntax(NilLiteralExprSyntax(UnexpectedNodesSyntax([Syntax(TokenSyntax.identifier("end"))]), nilKeyword: TokenSyntax.keyword(.nil, trailingTrivia: []))) + expression: ExprSyntax( + NilLiteralExprSyntax(UnexpectedNodesSyntax([Syntax(TokenSyntax.identifier("end"))]), nilKeyword: TokenSyntax.keyword(.nil, trailingTrivia: [])) + ) ) // This is more real-world where the user wrote null instead of nil.