From 4fae6c4a59442f4c085feb2dbadc363b1f09412f Mon Sep 17 00:00:00 2001 From: Alex Hoppen Date: Fri, 15 Mar 2024 12:08:13 -0700 Subject: [PATCH] Change swift-format configuration to 120 columns This makes the format the same as the one in sourcekit-lsp, converging towards a single format style. rdar://123241356 --- .swift-format | 2 +- .../SyntaxSupport/AttributeNodes.swift | 29 ++- .../SyntaxSupport/AvailabilityNodes.swift | 15 +- .../Sources/SyntaxSupport/Child.swift | 12 +- .../Sources/SyntaxSupport/CommonNodes.swift | 18 +- .../Sources/SyntaxSupport/DeclNodes.swift | 60 +++-- .../Sources/SyntaxSupport/ExprNodes.swift | 21 +- .../Sources/SyntaxSupport/GenericNodes.swift | 12 +- .../Sources/SyntaxSupport/Node.swift | 17 +- .../Sources/SyntaxSupport/Traits.swift | 17 +- .../Sources/SyntaxSupport/TypeNodes.swift | 9 +- .../Sources/Utils/CodeGenerationFormat.swift | 30 ++- .../Sources/Utils/SyntaxBuildableChild.swift | 14 +- .../GenerateSwiftSyntax.swift | 54 +++- .../LayoutNode+Extensions.swift | 18 +- .../swiftparser/ParserTokenSpecSetFile.swift | 10 +- .../swiftsyntax/RawSyntaxNodesFile.swift | 20 +- .../swiftsyntax/RawSyntaxValidationFile.swift | 8 +- .../RenamedChildrenCompatibilityFile.swift | 11 +- .../swiftsyntax/RenamedSyntaxNodesFile.swift | 3 +- .../swiftsyntax/SwiftSyntaxDoccIndex.swift | 17 +- .../swiftsyntax/SyntaxNodesFile.swift | 13 +- .../swiftsyntax/SyntaxRewriterFile.swift | 3 +- .../swiftsyntax/SyntaxTraitsFile.swift | 4 +- .../swiftsyntax/SyntaxVisitorFile.swift | 4 +- .../templates/swiftsyntax/TokenKindFile.swift | 4 +- .../ValidateSyntaxNodes.swift | 139 ++++++++--- .../CommandDiscovery.swift | 11 +- .../ComplexMacros/OptionSetMacro.swift | 19 +- .../Implementation/Member/CustomCodable.swift | 10 +- .../Implementation/Peer/AddAsyncMacro.swift | 22 +- .../Interface/ComplexMacros.swift | 16 +- .../Interface/ExpressionMacros.swift | 6 +- .../Interface/MemberAttributeMacros.swift | 3 +- .../MacroExamples/Interface/PeerMacros.swift | 6 +- .../Member/MetaEnumMacroTests.swift | 9 +- Package.swift | 38 ++- Sources/SwiftBasicFormat/BasicFormat.swift | 34 ++- .../SwiftBasicFormat/InferIndentation.swift | 4 +- .../SwiftCompilerPlugin/CompilerPlugin.swift | 5 +- .../PluginMacroExpansionContext.swift | 6 +- .../PluginMessages.swift | 9 +- .../ANSIDiagnosticDecorator.swift | 20 +- .../BasicDiagnosticDecorator.swift | 9 +- .../DiagnosticsFormatter.swift | 16 +- .../SwiftDiagnostics/GroupedDiagnostics.swift | 12 +- Sources/SwiftIDEUtils/DeclNameLocation.swift | 5 +- Sources/SwiftIDEUtils/FixItApplier.swift | 8 +- Sources/SwiftIDEUtils/NameMatcher.swift | 33 ++- Sources/SwiftParser/Attributes.swift | 47 +++- Sources/SwiftParser/Availability.swift | 5 +- .../CollectionNodes+Parsable.swift | 6 +- Sources/SwiftParser/Declarations.swift | 94 +++++-- Sources/SwiftParser/Directives.swift | 30 ++- Sources/SwiftParser/Expressions.swift | 78 ++++-- .../IncrementalParseTransition.swift | 8 +- Sources/SwiftParser/Lexer/Cursor.swift | 84 +++++-- .../SwiftParser/Lexer/LexemeSequence.swift | 34 ++- .../SwiftParser/Lexer/RegexLiteralLexer.swift | 3 +- .../Lexer/UnicodeScalarExtensions.swift | 4 +- Sources/SwiftParser/Modifiers.swift | 13 +- Sources/SwiftParser/Names.swift | 11 +- Sources/SwiftParser/Nominals.swift | 5 +- Sources/SwiftParser/Parameters.swift | 15 +- Sources/SwiftParser/ParseSourceFile.swift | 6 +- Sources/SwiftParser/Parser.swift | 25 +- Sources/SwiftParser/Patterns.swift | 14 +- Sources/SwiftParser/Recovery.swift | 4 +- Sources/SwiftParser/Specifiers.swift | 53 +++- Sources/SwiftParser/Statements.swift | 25 +- Sources/SwiftParser/StringLiterals.swift | 90 +++++-- Sources/SwiftParser/SyntaxUtils.swift | 6 +- Sources/SwiftParser/TokenConsumer.swift | 4 +- Sources/SwiftParser/TokenPrecedence.swift | 6 +- Sources/SwiftParser/TokenSpec.swift | 10 +- Sources/SwiftParser/TokenSpecSet.swift | 9 +- Sources/SwiftParser/TopLevel.swift | 5 +- Sources/SwiftParser/Types.swift | 39 ++- .../LexerDiagnosticMessages.swift | 25 +- .../MissingNodesError.swift | 19 +- .../MissingTokenError.swift | 69 +++++- ...ineStringLiteralDiagnosticsGenerator.swift | 21 +- .../ParseDiagnosticsGenerator.swift | 232 ++++++++++++++---- .../ParserDiagnosticMessages.swift | 26 +- .../SyntaxExtensions.swift | 4 +- .../CallToTrailingClosures.swift | 5 +- .../ExpandEditorPlaceholder.swift | 21 +- Sources/SwiftSyntax/Raw/RawSyntax.swift | 23 +- Sources/SwiftSyntax/SourceLocation.swift | 4 +- Sources/SwiftSyntax/Syntax.swift | 35 ++- .../SyntaxArenaAllocatedBuffer.swift | 8 +- Sources/SwiftSyntax/SyntaxChildren.swift | 5 +- Sources/SwiftSyntax/SyntaxCollection.swift | 8 +- Sources/SwiftSyntax/TokenSequence.swift | 6 +- Sources/SwiftSyntax/TokenSyntax.swift | 4 +- .../ConvenienceInitializers.swift | 4 +- .../Syntax+StringInterpolation.swift | 6 +- .../SyntaxNodeWithBody.swift | 31 ++- .../MacroExpansion.swift | 17 +- .../MacroReplacement.swift | 6 +- .../MacroSystem.swift | 54 +++- .../MacroExpansionContext.swift | 5 +- .../Assertions.swift | 73 +++++- .../IncrementalParseTestUtils.swift | 11 +- .../String+TrimmingTrailingWhitespace.swift | 5 +- .../Syntax+Assertions.swift | 29 ++- .../SyntaxComparison.swift | 5 +- .../SyntaxProtocol+Initializer.swift | 24 +- .../swift-parser-cli/BasicFormat.swift | 4 +- .../swift-parser-cli/Commands/Reduce.swift | 6 +- .../commands/Build.swift | 12 +- .../commands/Format.swift | 12 +- .../commands/LocalPrPrecheck.swift | 8 +- .../swift-syntax-dev-utils/common/Utils.swift | 7 +- .../InstructionsCountAssertion.swift | 7 +- .../GroupDiagnosticsFormatterTests.swift | 12 +- .../SwiftIDEUtilsTest/NameMatcherTests.swift | 7 +- Tests/SwiftParserTest/Assertions.swift | 30 ++- Tests/SwiftParserTest/AttributeTests.swift | 14 +- Tests/SwiftParserTest/DeclarationTests.swift | 193 ++++++++++++--- Tests/SwiftParserTest/ExpressionTests.swift | 108 ++++++-- .../IsValidIdentifierTests.swift | 16 +- Tests/SwiftParserTest/LexerTests.swift | 171 +++++++++++-- Tests/SwiftParserTest/Parser+EntryTests.swift | 11 +- Tests/SwiftParserTest/RegexLiteralTests.swift | 27 +- ...tialToConcurrentEditTranslationTests.swift | 8 +- Tests/SwiftParserTest/StatementTests.swift | 37 ++- ...gLiteralRepresentedLiteralValueTests.swift | 10 +- Tests/SwiftParserTest/TypeMemberTests.swift | 4 +- Tests/SwiftParserTest/TypeTests.swift | 29 ++- .../translated/AvailabilityQueryTests.swift | 37 ++- ...AvailabilityQueryUnavailabilityTests.swift | 5 +- .../ConsecutiveStatementsTests.swift | 30 ++- .../DiagnoseDynamicReplacementTests.swift | 5 +- ...agnoseInitializerAsTypedPatternTests.swift | 80 ++++-- .../translated/DollarIdentifierTests.swift | 42 +++- .../translated/EnumTests.swift | 11 +- .../translated/ErrorsTests.swift | 49 +++- .../translated/ForwardSlashRegexTests.swift | 27 +- .../translated/IdentifiersTests.swift | 20 +- .../translated/IfconfigExprTests.swift | 8 +- .../translated/InitDeinitTests.swift | 76 ++++-- .../translated/InvalidIfExprTests.swift | 35 ++- .../translated/InvalidTests.swift | 108 ++++++-- .../translated/MultilineErrorsTests.swift | 70 ++++-- .../translated/MultilineStringTests.swift | 14 +- .../NumberIdentifierErrorsTests.swift | 60 ++++- .../translated/ObjectLiteralsTests.swift | 36 ++- .../translated/OperatorDeclTests.swift | 38 ++- .../translated/OperatorsTests.swift | 5 +- .../translated/PoundAssertTests.swift | 10 +- .../translated/RawStringErrorsTests.swift | 48 +++- .../translated/RecoveryTests.swift | 195 ++++++++++++--- .../translated/RegexParseErrorTests.swift | 12 +- .../translated/SelfRebindingTests.swift | 5 +- .../translated/SubscriptingTests.swift | 12 +- .../translated/SwitchTests.swift | 31 ++- .../translated/ToplevelLibraryTests.swift | 5 +- .../translated/TrailingSemiTests.swift | 20 +- .../SwiftParserTest/translated/TryTests.swift | 46 +++- .../translated/TypealiasTests.swift | 17 +- .../UnclosedStringInterpolationTests.swift | 6 +- .../ExpandEditorPlaceholderTests.swift | 10 +- .../FormatRawStringLiteral.swift | 13 +- .../MigrateToNewIfLetSyntax.swift | 7 +- .../SwiftSyntaxBuilderTest/DoStmtTests.swift | 10 +- .../FunctionTests.swift | 45 +++- .../FunctionTypeSyntaxTests.swift | 5 +- .../SwiftSyntaxBuilderTest/IfStmtTests.swift | 6 +- .../StringInterpolationTests.swift | 5 +- .../StringLiteralExprSyntaxTests.swift | 38 ++- .../VariableTests.swift | 24 +- .../DeclarationMacroTests.swift | 14 +- .../ExtensionMacroTests.swift | 4 +- .../MemberMacroTests.swift | 4 +- .../MultiRoleMacroTests.swift | 13 +- .../PeerMacroTests.swift | 4 +- .../StringInterpolationErrorTests.swift | 8 +- .../DebugDescriptionTests.swift | 1 + .../SwiftSyntaxTest/SyntaxCreationTests.swift | 12 +- .../SwiftSyntaxTest/SyntaxVisitorTests.swift | 10 +- Tests/SwiftSyntaxTest/VisitorTests.swift | 24 +- 182 files changed, 3603 insertions(+), 933 deletions(-) diff --git a/.swift-format b/.swift-format index 6c125bef6ee..22b48e0903d 100644 --- a/.swift-format +++ b/.swift-format @@ -1,6 +1,6 @@ { "version": 1, - "lineLength": 160, + "lineLength": 120, "indentation": { "spaces": 2 }, diff --git a/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift b/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift index 9cdec68b1f3..9a7098b04c4 100644 --- a/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift @@ -180,7 +180,11 @@ public let ATTRIBUTE_NODES: [Node] = [ Child( name: "availabilityArguments", deprecatedName: "availabilityList", - kind: .collection(kind: .availabilityArgumentList, collectionElementName: "AvailabilityArgument", deprecatedCollectionElementName: "Availability") + kind: .collection( + kind: .availabilityArgumentList, + collectionElementName: "AvailabilityArgument", + deprecatedCollectionElementName: "Availability" + ) ), Child( name: "semicolon", @@ -236,7 +240,11 @@ public let ATTRIBUTE_NODES: [Node] = [ Child( name: "platforms", deprecatedName: "versionList", - kind: .collection(kind: .platformVersionItemList, collectionElementName: "Platform", deprecatedCollectionElementName: "Availability"), + kind: .collection( + kind: .platformVersionItemList, + collectionElementName: "Platform", + deprecatedCollectionElementName: "Availability" + ), documentation: "The list of OS versions in which the declaration became ABI stable." ), ] @@ -357,7 +365,8 @@ public let ATTRIBUTE_NODES: [Node] = [ kind: .differentiabilityArgument, base: .syntax, nameForDiagnostics: "differentiability argument", - documentation: "A differentiability argument: either the \"self\" identifier, a function parameter name, or a function parameter index.", + documentation: + "A differentiability argument: either the \"self\" identifier, a function parameter name, or a function parameter index.", traits: [ "WithTrailingComma" ], @@ -471,7 +480,8 @@ public let ATTRIBUTE_NODES: [Node] = [ name: "genericWhereClause", deprecatedName: "whereClause", kind: .node(kind: .genericWhereClause), - documentation: "A `where` clause that places additional constraints on generic parameters like `where T: Differentiable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where T: Differentiable`.", isOptional: true ), ] @@ -588,7 +598,8 @@ public let ATTRIBUTE_NODES: [Node] = [ kind: .implementsAttributeArguments, base: .syntax, nameForDiagnostics: "@_implements arguemnts", - documentation: "The arguments for the `@_implements` attribute of the form `Type, methodName(arg1Label:arg2Label:)`", + documentation: + "The arguments for the `@_implements` attribute of the form `Type, methodName(arg1Label:arg2Label:)`", children: [ Child( name: "type", @@ -738,14 +749,18 @@ public let ATTRIBUTE_NODES: [Node] = [ base: .syntaxCollection, nameForDiagnostics: "argument to '@_specialize", documentation: "A collection of arguments for the `@_specialize` attribute", - elementChoices: [.labeledSpecializeArgument, .specializeAvailabilityArgument, .specializeTargetFunctionArgument, .genericWhereClause] + elementChoices: [ + .labeledSpecializeArgument, .specializeAvailabilityArgument, .specializeTargetFunctionArgument, + .genericWhereClause, + ] ), Node( kind: .specializeTargetFunctionArgument, base: .syntax, nameForDiagnostics: "attribute argument", - documentation: "A labeled argument for the `@_specialize` attribute with a function decl value like `target: myFunc(_:)`", + documentation: + "A labeled argument for the `@_specialize` attribute with a function decl value like `target: myFunc(_:)`", traits: [ "WithTrailingComma" ], diff --git a/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift b/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift index 8e1a2470d28..f7d12324a79 100644 --- a/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/AvailabilityNodes.swift @@ -15,7 +15,8 @@ public let AVAILABILITY_NODES: [Node] = [ kind: .availabilityArgument, base: .syntax, nameForDiagnostics: "availability argument", - documentation: "A single argument to an `@available` argument like `*`, `iOS 10.1`, or `message: \"This has been deprecated\"`.", + documentation: + "A single argument to an `@available` argument like `*`, `iOS 10.1`, or `message: \"This has been deprecated\"`.", traits: ["WithTrailingComma"], children: [ Child( @@ -54,7 +55,8 @@ public let AVAILABILITY_NODES: [Node] = [ kind: .availabilityLabeledArgument, base: .syntax, nameForDiagnostics: "availability argument", - documentation: "An argument to an `@available` attribute that consists of a label and a value, e.g. `message: \"This has been deprecated\"`.", + documentation: + "An argument to an `@available` attribute that consists of a label and a value, e.g. `message: \"This has been deprecated\"`.", children: [ Child( name: "label", @@ -102,7 +104,8 @@ public let AVAILABILITY_NODES: [Node] = [ kind: .platformVersion, base: .syntax, nameForDiagnostics: "version restriction", - documentation: "An argument to `@available` that restricts the availability on a certain platform to a version, e.g. `iOS 10` or `swift 3.4`.", + documentation: + "An argument to `@available` that restricts the availability on a certain platform to a version, e.g. `iOS 10` or `swift 3.4`.", children: [ Child( name: "platform", @@ -157,7 +160,8 @@ public let AVAILABILITY_NODES: [Node] = [ kind: .versionTuple, base: .syntax, nameForDiagnostics: "version tuple", - documentation: "A version number like `1.2.0`. Only the first version component is required. There might be an arbitrary number of following components.", + documentation: + "A version number like `1.2.0`. Only the first version component is required. There might be an arbitrary number of following components.", parserFunction: "parseVersionTuple", children: [ Child( @@ -168,7 +172,8 @@ public let AVAILABILITY_NODES: [Node] = [ Child( name: "components", kind: .collection(kind: .versionComponentList, collectionElementName: "VersionComponent"), - documentation: "Any version components that are not the major version . For example, for `1.2.0`, this will contain `.2.0`." + documentation: + "Any version components that are not the major version . For example, for `1.2.0`, this will contain `.2.0`." ), ] ), diff --git a/CodeGeneration/Sources/SyntaxSupport/Child.swift b/CodeGeneration/Sources/SyntaxSupport/Child.swift index 45afefc632c..74b7e3f3a6a 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Child.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Child.swift @@ -41,7 +41,12 @@ public enum ChildKind { /// The child always contains a node that matches one of the `choices`. case nodeChoices(choices: [Child]) /// The child is a collection of `kind`. - case collection(kind: SyntaxNodeKind, collectionElementName: String, defaultsToEmpty: Bool = false, deprecatedCollectionElementName: String? = nil) + case collection( + kind: SyntaxNodeKind, + collectionElementName: String, + defaultsToEmpty: Bool = false, + deprecatedCollectionElementName: String? = nil + ) /// The child is a token that matches one of the given `choices`. /// If `requiresLeadingSpace` or `requiresTrailingSpace` is not `nil`, it /// overrides the default leading/trailing space behavior of the token. @@ -259,7 +264,10 @@ public class Child { isOptional: Bool = false ) { precondition(name.first?.isLowercase ?? true, "The first letter of a child’s name should be lowercase") - precondition(deprecatedName?.first?.isLowercase ?? true, "The first letter of a child’s deprecatedName should be lowercase") + precondition( + deprecatedName?.first?.isLowercase ?? true, + "The first letter of a child’s deprecatedName should be lowercase" + ) self.name = name self.deprecatedName = deprecatedName self.kind = kind diff --git a/CodeGeneration/Sources/SyntaxSupport/CommonNodes.swift b/CodeGeneration/Sources/SyntaxSupport/CommonNodes.swift index 9b9f51160e0..7247e17a909 100644 --- a/CodeGeneration/Sources/SyntaxSupport/CommonNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/CommonNodes.swift @@ -191,7 +191,8 @@ public let COMMON_NODES: [Node] = [ kind: .missingDecl, base: .decl, nameForDiagnostics: "declaration", - documentation: "In case the source code is missing a declaration, this node stands in place of the missing declaration.", + documentation: + "In case the source code is missing a declaration, this node stands in place of the missing declaration.", traits: [ "MissingNode", "WithAttributes", @@ -201,12 +202,14 @@ public let COMMON_NODES: [Node] = [ Child( name: "attributes", kind: .collection(kind: .attributeList, collectionElementName: "Attribute", defaultsToEmpty: true), - documentation: "If there were standalone attributes without a declaration to attach them to, the ``MissingDeclSyntax`` will contain these." + documentation: + "If there were standalone attributes without a declaration to attach them to, the ``MissingDeclSyntax`` will contain these." ), Child( name: "modifiers", kind: .collection(kind: .declModifierList, collectionElementName: "Modifier", defaultsToEmpty: true), - documentation: "If there were standalone modifiers without a declaration to attach them to, the ``MissingDeclSyntax`` will contain these." + documentation: + "If there were standalone modifiers without a declaration to attach them to, the ``MissingDeclSyntax`` will contain these." ), Child( name: "placeholder", @@ -224,7 +227,8 @@ public let COMMON_NODES: [Node] = [ kind: .missingExpr, base: .expr, nameForDiagnostics: "expression", - documentation: "In case the source code is missing an expression, this node stands in place of the missing expression.", + documentation: + "In case the source code is missing an expression, this node stands in place of the missing expression.", traits: [ "MissingNode" ], @@ -266,7 +270,8 @@ public let COMMON_NODES: [Node] = [ kind: .missingStmt, base: .stmt, nameForDiagnostics: "statement", - documentation: "In case the source code is missing a statement, this node stands in place of the missing statement.", + documentation: + "In case the source code is missing a statement, this node stands in place of the missing statement.", traits: [ "MissingNode" ], @@ -372,7 +377,8 @@ public let COMMON_NODES: [Node] = [ kind: .unexpectedNodes, base: .syntaxCollection, nameForDiagnostics: nil, - documentation: "A collection of syntax nodes that occurred in the source code but could not be used to form a valid syntax tree.", + documentation: + "A collection of syntax nodes that occurred in the source code but could not be used to form a valid syntax tree.", elementChoices: [.syntax] ), diff --git a/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift b/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift index acd632ef266..b11a846279d 100644 --- a/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/DeclNodes.swift @@ -219,7 +219,8 @@ public let DECL_NODES: [Node] = [ name: "genericWhereClause", kind: .node(kind: .genericWhereClause), nameForDiagnostics: "generic where clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), Child( @@ -299,7 +300,8 @@ public let DECL_NODES: [Node] = [ Child( name: "initializer", kind: .node(kind: .typeInitializerClause), - documentation: "The type initializer clause for this associated type declaration which represents a default type assignment for the associated type.", + documentation: + "The type initializer clause for this associated type declaration which represents a default type assignment for the associated type.", isOptional: true ), Child( @@ -571,12 +573,14 @@ public let DECL_NODES: [Node] = [ Child( name: "attributes", kind: .collection(kind: .attributeList, collectionElementName: "Attribute", defaultsToEmpty: true), - documentation: "If there were attributes before the editor placeholder, the ``EditorPlaceholderDeclSyntax`` will contain these." + documentation: + "If there were attributes before the editor placeholder, the ``EditorPlaceholderDeclSyntax`` will contain these." ), Child( name: "modifiers", kind: .collection(kind: .declModifierList, collectionElementName: "Modifier", defaultsToEmpty: true), - documentation: "If there were modifiers before the editor placeholder, the `EditorPlaceholderDecl` will contain these." + documentation: + "If there were modifiers before the editor placeholder, the `EditorPlaceholderDecl` will contain these." ), Child( name: "placeholder", @@ -679,7 +683,8 @@ public let DECL_NODES: [Node] = [ kind: .enumCaseDecl, base: .decl, nameForDiagnostics: "enum case", - documentation: "A `case` declaration of a Swift `enum`. It can have 1 or more `EnumCaseElement`s inside, each declaring a different case of the enum.", + documentation: + "A `case` declaration of a Swift `enum`. It can have 1 or more `EnumCaseElement`s inside, each declaring a different case of the enum.", traits: [ "WithAttributes", "WithModifiers", @@ -723,7 +728,8 @@ public let DECL_NODES: [Node] = [ kind: .enumCaseElement, base: .syntax, nameForDiagnostics: nil, - documentation: "An element of an enum case, containing the name of the case and, optionally, either associated values or an assignment to a raw value.", + documentation: + "An element of an enum case, containing the name of the case and, optionally, either associated values or an assignment to a raw value.", traits: [ "WithTrailingComma" ], @@ -791,7 +797,8 @@ public let DECL_NODES: [Node] = [ name: "name", deprecatedName: "identifier", kind: .token(choices: [.token(.identifier)]), - documentation: "Declares the name of this enum. If the name matches a reserved keyword use backticks to escape it." + documentation: + "Declares the name of this enum. If the name matches a reserved keyword use backticks to escape it." ), Child( name: "genericParameterClause", @@ -863,7 +870,8 @@ public let DECL_NODES: [Node] = [ name: "genericWhereClause", kind: .node(kind: .genericWhereClause), nameForDiagnostics: "generic where clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), Child( @@ -929,7 +937,8 @@ public let DECL_NODES: [Node] = [ name: "genericWhereClause", kind: .node(kind: .genericWhereClause), nameForDiagnostics: "generic where clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), Child( @@ -1122,7 +1131,8 @@ public let DECL_NODES: [Node] = [ name: "modifiers", kind: .collection(kind: .declModifierList, collectionElementName: "Modifier", defaultsToEmpty: true), nameForDiagnostics: "modifiers", - documentation: "Modifiers that are attached to the import declaration. Currently, no modifiers are supported by Swift." + documentation: + "Modifiers that are attached to the import declaration. Currently, no modifiers are supported by Swift." ), Child( name: "importKeyword", @@ -1263,7 +1273,8 @@ public let DECL_NODES: [Node] = [ name: "signature", kind: .node(kind: .functionSignature), nameForDiagnostics: "function signature", - documentation: "The arguments of the initializer. While the function signature allows specifying a return clause, doing so is not semantically valid." + documentation: + "The arguments of the initializer. While the function signature allows specifying a return clause, doing so is not semantically valid." ), Child( name: "genericWhereClause", @@ -1333,7 +1344,8 @@ public let DECL_NODES: [Node] = [ name: "genericWhereClause", kind: .node(kind: .genericWhereClause), nameForDiagnostics: "generic where clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), ] @@ -1399,7 +1411,11 @@ public let DECL_NODES: [Node] = [ ), Child( name: "additionalTrailingClosures", - kind: .collection(kind: .multipleTrailingClosureElementList, collectionElementName: "AdditionalTrailingClosure", defaultsToEmpty: true) + kind: .collection( + kind: .multipleTrailingClosureElementList, + collectionElementName: "AdditionalTrailingClosure", + defaultsToEmpty: true + ) ), ] ), @@ -1498,7 +1514,8 @@ public let DECL_NODES: [Node] = [ kind: .operatorPrecedenceAndTypes, base: .syntax, nameForDiagnostics: nil, - documentation: "A clause to specify precedence group in infix operator declarations, and designated types in any operator declaration.", + documentation: + "A clause to specify precedence group in infix operator declarations, and designated types in any operator declaration.", children: [ Child( name: "colon", @@ -1715,7 +1732,8 @@ public let DECL_NODES: [Node] = [ kind: .precedenceGroupAssociativity, base: .syntax, nameForDiagnostics: "'associativity' property of precedencegroup", - documentation: "Specifies how a sequence of operators with the same precedence level are grouped together in the absence of grouping parentheses.", + documentation: + "Specifies how a sequence of operators with the same precedence level are grouped together in the absence of grouping parentheses.", children: [ Child( name: "associativityLabel", @@ -2051,7 +2069,8 @@ public let DECL_NODES: [Node] = [ name: "name", deprecatedName: "identifier", kind: .token(choices: [.token(.identifier)]), - documentation: "Declares the name of this struct. If the name matches a reserved keyword use backticks to escape it." + documentation: + "Declares the name of this struct. If the name matches a reserved keyword use backticks to escape it." ), Child( name: "genericParameterClause", @@ -2064,7 +2083,8 @@ public let DECL_NODES: [Node] = [ name: "inheritanceClause", kind: .node(kind: .inheritanceClause), nameForDiagnostics: "inheritance clause", - documentation: "The struct declaration inheritance clause describing one or more conformances for this struct declaration.", + documentation: + "The struct declaration inheritance clause describing one or more conformances for this struct declaration.", isOptional: true ), Child( @@ -2128,7 +2148,8 @@ public let DECL_NODES: [Node] = [ name: "genericWhereClause", kind: .node(kind: .genericWhereClause), nameForDiagnostics: "generic where clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), Child( @@ -2219,7 +2240,8 @@ public let DECL_NODES: [Node] = [ name: "genericWhereClause", kind: .node(kind: .genericWhereClause), nameForDiagnostics: "generic where clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), ] diff --git a/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift b/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift index 25adea287dd..bbe76f8e776 100644 --- a/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift @@ -915,7 +915,11 @@ public let EXPR_NODES: [Node] = [ ), Child( name: "additionalTrailingClosures", - kind: .collection(kind: .multipleTrailingClosureElementList, collectionElementName: "AdditionalTrailingClosure", defaultsToEmpty: true), + kind: .collection( + kind: .multipleTrailingClosureElementList, + collectionElementName: "AdditionalTrailingClosure", + defaultsToEmpty: true + ), nameForDiagnostics: "trailing closures" ), ] @@ -1084,7 +1088,8 @@ public let EXPR_NODES: [Node] = [ name: "type", deprecatedName: "typeName", kind: .node(kind: .type), - documentation: "The type against which the expression will be checked to see if the expression can be cast to it." + documentation: + "The type against which the expression will be checked to see if the expression can be cast to it." ), ] ), @@ -1263,7 +1268,11 @@ public let EXPR_NODES: [Node] = [ ), Child( name: "additionalTrailingClosures", - kind: .collection(kind: .multipleTrailingClosureElementList, collectionElementName: "AdditionalTrailingClosure", defaultsToEmpty: true) + kind: .collection( + kind: .multipleTrailingClosureElementList, + collectionElementName: "AdditionalTrailingClosure", + defaultsToEmpty: true + ) ), ] ), @@ -1688,7 +1697,11 @@ public let EXPR_NODES: [Node] = [ ), Child( name: "additionalTrailingClosures", - kind: .collection(kind: .multipleTrailingClosureElementList, collectionElementName: "AdditionalTrailingClosure", defaultsToEmpty: true), + kind: .collection( + kind: .multipleTrailingClosureElementList, + collectionElementName: "AdditionalTrailingClosure", + defaultsToEmpty: true + ), nameForDiagnostics: "trailing closures" ), ] diff --git a/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift b/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift index b2b8657cd81..0b155c0bf01 100644 --- a/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/GenericNodes.swift @@ -49,13 +49,18 @@ public let GENERIC_NODES: [Node] = [ Child( name: "parameters", deprecatedName: "genericParameterList", - kind: .collection(kind: .genericParameterList, collectionElementName: "Parameter", deprecatedCollectionElementName: "GenericParameter"), + kind: .collection( + kind: .genericParameterList, + collectionElementName: "Parameter", + deprecatedCollectionElementName: "GenericParameter" + ), documentation: "The list of generic parameters in the clause." ), Child( name: "genericWhereClause", kind: .node(kind: .genericWhereClause), - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), Child( @@ -163,7 +168,8 @@ public let GENERIC_NODES: [Node] = [ kind: .genericWhereClause, base: .syntax, nameForDiagnostics: "'where' clause", - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", children: [ Child( name: "whereKeyword", diff --git a/CodeGeneration/Sources/SyntaxSupport/Node.swift b/CodeGeneration/Sources/SyntaxSupport/Node.swift index 0d77eef567d..ee3b3f5adfe 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Node.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Node.swift @@ -155,7 +155,11 @@ public class Node { let childrenWithUnexpected: [Child] if children.isEmpty { childrenWithUnexpected = [ - Child(name: "unexpected", kind: .collection(kind: .unexpectedNodes, collectionElementName: "Unexpected"), isOptional: true) + Child( + name: "unexpected", + kind: .collection(kind: .unexpectedNodes, collectionElementName: "Unexpected"), + isOptional: true + ) ] } else { // Add implicitly generated UnexpectedNodes children between @@ -173,9 +177,11 @@ public class Node { } else { unexpectedName = "unexpectedBetween\(children[i - 1].name.withFirstCharacterUppercased)And\(childName)" if let deprecatedName = children[i - 1].deprecatedName?.withFirstCharacterUppercased { - unexpectedDeprecatedName = "unexpectedBetween\(deprecatedName)And\(child.deprecatedName?.withFirstCharacterUppercased ?? childName)" + unexpectedDeprecatedName = + "unexpectedBetween\(deprecatedName)And\(child.deprecatedName?.withFirstCharacterUppercased ?? childName)" } else if let deprecatedName = child.deprecatedName?.withFirstCharacterUppercased { - unexpectedDeprecatedName = "unexpectedBetween\(children[i - 1].name.withFirstCharacterUppercased)And\(deprecatedName)" + unexpectedDeprecatedName = + "unexpectedBetween\(children[i - 1].name.withFirstCharacterUppercased)And\(deprecatedName)" } else { unexpectedDeprecatedName = nil } @@ -191,7 +197,10 @@ public class Node { Child( name: "unexpectedAfter\(children.last!.name.withFirstCharacterUppercased)", deprecatedName: children.last!.deprecatedName.map { "unexpectedAfter\($0.withFirstCharacterUppercased)" }, - kind: .collection(kind: .unexpectedNodes, collectionElementName: "UnexpectedAfter\(children.last!.name.withFirstCharacterUppercased)"), + kind: .collection( + kind: .unexpectedNodes, + collectionElementName: "UnexpectedAfter\(children.last!.name.withFirstCharacterUppercased)" + ), isOptional: true ) ] diff --git a/CodeGeneration/Sources/SyntaxSupport/Traits.swift b/CodeGeneration/Sources/SyntaxSupport/Traits.swift index 614873702af..8838ecb7ad5 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Traits.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Traits.swift @@ -49,14 +49,18 @@ public let TRAITS: [Trait] = [ Child(name: "modifiers", kind: .node(kind: .declModifierList)), Child( name: "introducer", - kind: .token(choices: [.keyword(.actor), .keyword(.class), .keyword(.enum), .keyword(.extension), .keyword(.protocol), .keyword(.struct)]), + kind: .token(choices: [ + .keyword(.actor), .keyword(.class), .keyword(.enum), .keyword(.extension), .keyword(.protocol), + .keyword(.struct), + ]), documentation: "The token that introduces this declaration, eg. `class` for a class declaration." ), Child(name: "inheritanceClause", kind: .node(kind: .inheritanceClause), isOptional: true), Child( name: "genericWhereClause", kind: .node(kind: .genericWhereClause), - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), Child(name: "memberBlock", kind: .node(kind: .memberBlock)), @@ -67,7 +71,11 @@ public let TRAITS: [Trait] = [ children: [ Child(name: "unexpectedBeforeAsyncSpecifier", kind: .node(kind: .unexpectedNodes), isOptional: true), Child(name: "asyncSpecifier", kind: .token(choices: [.keyword(.async), .keyword(.reasync)]), isOptional: true), - Child(name: "unexpectedBetweenAsyncSpecifierAndThrowsClause", kind: .node(kind: .unexpectedNodes), isOptional: true), + Child( + name: "unexpectedBetweenAsyncSpecifierAndThrowsClause", + kind: .node(kind: .unexpectedNodes), + isOptional: true + ), Child(name: "throwsClause", kind: .node(kind: .throwsClause), isOptional: true), Child(name: "unexpectedAfterThrowsClause", kind: .node(kind: .unexpectedNodes), isOptional: true), ] @@ -145,7 +153,8 @@ public let TRAITS: [Trait] = [ Child( name: "genericWhereClause", kind: .node(kind: .genericWhereClause), - documentation: "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", + documentation: + "A `where` clause that places additional constraints on generic parameters like `where Element: Hashable`.", isOptional: true ), ] diff --git a/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift b/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift index 93a2598645d..f337aa226f3 100644 --- a/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/TypeNodes.swift @@ -45,7 +45,8 @@ public let TYPE_NODES: [Node] = [ Child( name: "specifiers", kind: .collection(kind: .typeSpecifierList, collectionElementName: "Specifier", defaultsToEmpty: true), - documentation: "A list of specifiers that can be attached to the type, such as `inout`, `isolated`, or `consuming`." + documentation: + "A list of specifiers that can be attached to the type, such as `inout`, `isolated`, or `consuming`." ), Child( name: "attributes", @@ -174,7 +175,11 @@ public let TYPE_NODES: [Node] = [ Child( name: "parameters", deprecatedName: "arguments", - kind: .collection(kind: .tupleTypeElementList, collectionElementName: "Parameter", deprecatedCollectionElementName: "Argument") + kind: .collection( + kind: .tupleTypeElementList, + collectionElementName: "Parameter", + deprecatedCollectionElementName: "Argument" + ) ), Child( name: "rightParen", diff --git a/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift b/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift index 36b5d970264..70b88f5f419 100644 --- a/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift +++ b/CodeGeneration/Sources/Utils/CodeGenerationFormat.swift @@ -32,7 +32,9 @@ public class CodeGenerationFormat: BasicFormat { let children = node.children(viewMode: .all) // Short array literals are presented on one line, list each element on a different line. if children.count > maxElementsOnSameLine { - return ArrayElementListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: ArrayElementSyntax.self)) + return ArrayElementListSyntax( + formatChildrenSeparatedByNewline(children: children, elementType: ArrayElementSyntax.self) + ) } else { return super.visit(node) } @@ -51,7 +53,9 @@ public class CodeGenerationFormat: BasicFormat { let children = node.children(viewMode: .all) // Short dictionary literals are presented on one line, list each element on a different line. if children.count > maxElementsOnSameLine { - return DictionaryElementListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: DictionaryElementSyntax.self)) + return DictionaryElementListSyntax( + formatChildrenSeparatedByNewline(children: children, elementType: DictionaryElementSyntax.self) + ) } else { return super.visit(node) } @@ -61,7 +65,9 @@ public class CodeGenerationFormat: BasicFormat { let children = node.children(viewMode: .all) // Short function parameter literals are presented on one line, list each element on a different line. if children.count > maxElementsOnSameLine { - return FunctionParameterListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: FunctionParameterSyntax.self)) + return FunctionParameterListSyntax( + formatChildrenSeparatedByNewline(children: children, elementType: FunctionParameterSyntax.self) + ) } else { return super.visit(node) } @@ -77,7 +83,9 @@ public class CodeGenerationFormat: BasicFormat { public override func visit(_ node: MemberBlockItemSyntax) -> MemberBlockItemSyntax { let formatted = super.visit(node) - if node != node.parent?.children(viewMode: .sourceAccurate).first?.as(MemberBlockItemSyntax.self) && !node.decl.is(EnumCaseDeclSyntax.self) { + if node != node.parent?.children(viewMode: .sourceAccurate).first?.as(MemberBlockItemSyntax.self) + && !node.decl.is(EnumCaseDeclSyntax.self) + { return ensuringTwoLeadingNewlines(node: formatted) } else { return formatted @@ -88,7 +96,9 @@ public class CodeGenerationFormat: BasicFormat { let children = node.children(viewMode: .all) // Short tuple element list literals are presented on one line, list each element on a different line. if children.count > maxElementsOnSameLine { - return LabeledExprListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: LabeledExprSyntax.self)) + return LabeledExprListSyntax( + formatChildrenSeparatedByNewline(children: children, elementType: LabeledExprSyntax.self) + ) } else { return super.visit(node) } @@ -110,7 +120,10 @@ public class CodeGenerationFormat: BasicFormat { } } - private func formatChildrenSeparatedByNewline(children: SyntaxChildren, elementType: SyntaxType.Type) -> [SyntaxType] { + private func formatChildrenSeparatedByNewline( + children: SyntaxChildren, + elementType: SyntaxType.Type + ) -> [SyntaxType] { increaseIndentationLevel() var formattedChildren = children.map { self.rewrite($0.cast(SyntaxType.self)).cast(SyntaxType.self) @@ -124,7 +137,10 @@ public class CodeGenerationFormat: BasicFormat { } decreaseIndentationLevel() if !formattedChildren.isEmpty { - formattedChildren[formattedChildren.count - 1] = formattedChildren[formattedChildren.count - 1].with(\.trailingTrivia, indentedNewline) + formattedChildren[formattedChildren.count - 1] = formattedChildren[formattedChildren.count - 1].with( + \.trailingTrivia, + indentedNewline + ) } return formattedChildren } diff --git a/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift b/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift index 6899dd5785f..0b7851514eb 100644 --- a/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift +++ b/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift @@ -87,7 +87,10 @@ public extension Child { /// function parameter. Otherwise, return `nil`. var defaultInitialization: InitializerClauseSyntax? { if let defaultValue { - return InitializerClauseSyntax(equal: .equalToken(leadingTrivia: .space, trailingTrivia: .space), value: defaultValue) + return InitializerClauseSyntax( + equal: .equalToken(leadingTrivia: .space, trailingTrivia: .space), + value: defaultValue + ) } else { return nil } @@ -143,14 +146,19 @@ public extension Child { preconditionChoices.append( ExprSyntax( SequenceExprSyntax { - MemberAccessExprSyntax(base: buildableType.forceUnwrappedIfNeeded(expr: DeclReferenceExprSyntax(baseName: .identifier(varName))), name: "text") + MemberAccessExprSyntax( + base: buildableType.forceUnwrappedIfNeeded(expr: DeclReferenceExprSyntax(baseName: .identifier(varName))), + name: "text" + ) BinaryOperatorExprSyntax(text: "==") StringLiteralExprSyntax(content: textChoice) } ) ) } - let disjunction = ExprListSyntax(preconditionChoices.flatMap { [$0, ExprSyntax(BinaryOperatorExprSyntax(text: "||"))] }.dropLast()) + let disjunction = ExprListSyntax( + preconditionChoices.flatMap { [$0, ExprSyntax(BinaryOperatorExprSyntax(text: "||"))] }.dropLast() + ) return FunctionCallExprSyntax(callee: ExprSyntax("precondition")) { LabeledExprSyntax(expression: SequenceExprSyntax(elements: disjunction)) } diff --git a/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift b/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift index 2df84516c6e..4889bf1d639 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/GenerateSwiftSyntax.swift @@ -47,7 +47,11 @@ struct GeneratedFileSpec { self.contentsGenerator = contents } - init(_ pathComponents: [String], _ contents: @escaping @autoclosure () -> SourceFileSyntax, format: CodeGenerationFormat = CodeGenerationFormat()) { + init( + _ pathComponents: [String], + _ contents: @escaping @autoclosure () -> SourceFileSyntax, + format: CodeGenerationFormat = CodeGenerationFormat() + ) { self.init(pathComponents, "\(contents().formatted(using: format))\n") } } @@ -69,7 +73,9 @@ struct TemplateSpec { @main struct GenerateSwiftSyntax: AsyncParsableCommand { - @Argument(help: "The path to the source directory (i.e. 'swift-syntax/Sources') where the source files are to be generated") + @Argument( + help: "The path to the source directory (i.e. 'swift-syntax/Sources') where the source files are to be generated" + ) var destination: String = { let sourcesURL = URL(fileURLWithPath: #filePath) .deletingLastPathComponent() @@ -95,15 +101,27 @@ struct GenerateSwiftSyntax: AsyncParsableCommand { GeneratedFileSpec(swiftParserGeneratedDir + ["TokenSpecStaticMembers.swift"], tokenSpecStaticMembersFile), // SwiftParserDiagnostics - GeneratedFileSpec(swiftParserDiagnosticsGeneratedDir + ["ChildNameForDiagnostics.swift"], childNameForDiagnosticFile), - GeneratedFileSpec(swiftParserDiagnosticsGeneratedDir + ["SyntaxKindNameForDiagnostics.swift"], syntaxKindNameForDiagnosticFile), - GeneratedFileSpec(swiftParserDiagnosticsGeneratedDir + ["TokenNameForDiagnostics.swift"], tokenNameForDiagnosticFile), + GeneratedFileSpec( + swiftParserDiagnosticsGeneratedDir + ["ChildNameForDiagnostics.swift"], + childNameForDiagnosticFile + ), + GeneratedFileSpec( + swiftParserDiagnosticsGeneratedDir + ["SyntaxKindNameForDiagnostics.swift"], + syntaxKindNameForDiagnosticFile + ), + GeneratedFileSpec( + swiftParserDiagnosticsGeneratedDir + ["TokenNameForDiagnostics.swift"], + tokenNameForDiagnosticFile + ), // SwiftSyntax GeneratedFileSpec(swiftSyntaxGeneratedDir + ["ChildNameForKeyPath.swift"], childNameForKeyPathFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["Keyword.swift"], keywordFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["raw", "RawSyntaxValidation.swift"], rawSyntaxValidationFile), - GeneratedFileSpec(swiftSyntaxGeneratedDir + ["RenamedChildrenCompatibility.swift"], renamedChildrenCompatibilityFile), + GeneratedFileSpec( + swiftSyntaxGeneratedDir + ["RenamedChildrenCompatibility.swift"], + renamedChildrenCompatibilityFile + ), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["RenamedNodesCompatibility.swift"], renamedSyntaxNodesFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxAnyVisitor.swift"], syntaxAnyVisitorFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxBaseNodes.swift"], syntaxBaseNodesFile), @@ -112,7 +130,11 @@ struct GenerateSwiftSyntax: AsyncParsableCommand { GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxKind.swift"], syntaxKindFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxRewriter.swift"], syntaxRewriterFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxTraits.swift"], syntaxTraitsFile), - GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxVisitor.swift"], syntaxVisitorFile, format: CodeGenerationFormat(maxElementsOnSameLine: 4)), + GeneratedFileSpec( + swiftSyntaxGeneratedDir + ["SyntaxVisitor.swift"], + syntaxVisitorFile, + format: CodeGenerationFormat(maxElementsOnSameLine: 4) + ), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["TokenKind.swift"], tokenKindFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["Tokens.swift"], tokensFile), GeneratedFileSpec(swiftSyntaxGeneratedDir + ["TriviaPieces.swift"], triviaPiecesFile), @@ -125,14 +147,24 @@ struct GenerateSwiftSyntax: AsyncParsableCommand { swiftSyntaxBuilderGeneratedDir + ["SyntaxExpressibleByStringInterpolationConformances.swift"], syntaxExpressibleByStringInterpolationConformancesFile ), - GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["RenamedChildrenBuilderCompatibility.swift"], renamedChildrenBuilderCompatibilityFile), + GeneratedFileSpec( + swiftSyntaxBuilderGeneratedDir + ["RenamedChildrenBuilderCompatibility.swift"], + renamedChildrenBuilderCompatibilityFile + ), ] // This split of letters produces files for the syntax nodes that have about equal size, which improves compile time - fileSpecs += ["AB", "C", "D", "EF", "GHI", "JKLMN", "OP", "QRS", "TUVWXYZ"].flatMap { (letters: String) -> [GeneratedFileSpec] in + fileSpecs += ["AB", "C", "D", "EF", "GHI", "JKLMN", "OP", "QRS", "TUVWXYZ"].flatMap { + (letters: String) -> [GeneratedFileSpec] in [ - GeneratedFileSpec(swiftSyntaxGeneratedDir + ["syntaxNodes", "SyntaxNodes\(letters).swift"], syntaxNode(nodesStartingWith: Array(letters))), - GeneratedFileSpec(swiftSyntaxGeneratedDir + ["raw", "RawSyntaxNodes\(letters).swift"], rawSyntaxNodesFile(nodesStartingWith: Array(letters))), + GeneratedFileSpec( + swiftSyntaxGeneratedDir + ["syntaxNodes", "SyntaxNodes\(letters).swift"], + syntaxNode(nodesStartingWith: Array(letters)) + ), + GeneratedFileSpec( + swiftSyntaxGeneratedDir + ["raw", "RawSyntaxNodes\(letters).swift"], + rawSyntaxNodesFile(nodesStartingWith: Array(letters)) + ), ] } diff --git a/CodeGeneration/Sources/generate-swift-syntax/LayoutNode+Extensions.swift b/CodeGeneration/Sources/generate-swift-syntax/LayoutNode+Extensions.swift index dd26dd1e0c7..b70e14624d5 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/LayoutNode+Extensions.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/LayoutNode+Extensions.swift @@ -126,9 +126,13 @@ extension LayoutNode { if child.buildableType.builderInitializableType != child.buildableType { let param = Node.from(type: child.buildableType).layoutNode!.singleNonDefaultedChild if child.isOptional { - produceExpr = ExprSyntax("\(childName)Builder().map { \(child.buildableType.syntaxBaseName)(\(param.varOrCaseName): $0) }") + produceExpr = ExprSyntax( + "\(childName)Builder().map { \(child.buildableType.syntaxBaseName)(\(param.varOrCaseName): $0) }" + ) } else { - produceExpr = ExprSyntax("\(child.buildableType.syntaxBaseName)(\(param.varOrCaseName): \(childName)Builder())") + produceExpr = ExprSyntax( + "\(child.buildableType.syntaxBaseName)(\(param.varOrCaseName): \(childName)Builder())" + ) } } else { produceExpr = ExprSyntax("\(childName)Builder()") @@ -139,7 +143,10 @@ extension LayoutNode { ) ) } else { - produceExpr = convertFromSyntaxProtocolToSyntaxType(child: child, useDeprecatedChildName: useDeprecatedChildName) + produceExpr = convertFromSyntaxProtocolToSyntaxType( + child: child, + useDeprecatedChildName: useDeprecatedChildName + ) normalParameters.append( FunctionParameterSyntax( firstName: childName, @@ -187,7 +194,10 @@ extension LayoutNode { } } -fileprivate func convertFromSyntaxProtocolToSyntaxType(child: Child, useDeprecatedChildName: Bool = false) -> ExprSyntax { +fileprivate func convertFromSyntaxProtocolToSyntaxType( + child: Child, + useDeprecatedChildName: Bool = false +) -> ExprSyntax { let childName: TokenSyntax if useDeprecatedChildName, let deprecatedVarName = child.deprecatedVarName { childName = deprecatedVarName diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/ParserTokenSpecSetFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/ParserTokenSpecSetFile.swift index 3856c25ad6a..bdad6664548 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/ParserTokenSpecSetFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/ParserTokenSpecSetFile.swift @@ -15,7 +15,11 @@ import SwiftSyntaxBuilder import SyntaxSupport import Utils -func tokenCaseMatch(_ caseName: TokenSyntax, experimentalFeature: ExperimentalFeature?, experimentalFeature2: ExperimentalFeature?) -> SwitchCaseSyntax { +func tokenCaseMatch( + _ caseName: TokenSyntax, + experimentalFeature: ExperimentalFeature?, + experimentalFeature2: ExperimentalFeature? +) -> SwitchCaseSyntax { var whereClause = "" if let feature = experimentalFeature { whereClause += "where experimentalFeatures.contains(.\(feature.token))" @@ -61,7 +65,9 @@ let parserTokenSpecSetFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { } } - try InitializerDeclSyntax("init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures)") { + try InitializerDeclSyntax( + "init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures)" + ) { try SwitchExprSyntax("switch PrepareForKeywordMatch(lexeme)") { for choice in choices { switch choice { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift index c9dda02030f..18f72a77a4a 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift @@ -19,7 +19,8 @@ fileprivate extension Node { var childrenChoicesEnums: [(name: TypeSyntax, choices: [(caseName: TokenSyntax, kind: SyntaxNodeKind)])] { let node = self if let node = node.layoutNode { - return node.children.compactMap { child -> (name: TypeSyntax, choices: [(caseName: TokenSyntax, kind: SyntaxNodeKind)])? in + return node.children.compactMap { + child -> (name: TypeSyntax, choices: [(caseName: TokenSyntax, kind: SyntaxNodeKind)])? in switch child.kind { case .nodeChoices(let choices): return (child.syntaxChoicesType, choices.map { ($0.varOrCaseName, $0.syntaxNodeKind) }) @@ -40,7 +41,8 @@ fileprivate extension Node { func rawSyntaxNodesFile(nodesStartingWith: [Character]) -> SourceFileSyntax { return SourceFileSyntax(leadingTrivia: copyrightHeader) { - for node in SYNTAX_NODES where node.kind.isBase && nodesStartingWith.contains(node.kind.syntaxType.description.first!) { + for node in SYNTAX_NODES + where node.kind.isBase && nodesStartingWith.contains(node.kind.syntaxType.description.first!) { DeclSyntax( """ \(node.apiAttributes(forRaw: true))\ @@ -220,8 +222,10 @@ func rawSyntaxNodesFile(nodesStartingWith: [Character]) -> SourceFileSyntax { for (index, child) in node.children.enumerated() { let optionalMark = child.isOptional ? "?" : "" - ExprSyntax("layout[\(raw: index)] = \(child.varOrCaseName.backtickedIfNeeded)\(raw: optionalMark).raw") - .with(\.leadingTrivia, .newline) + ExprSyntax( + "layout[\(raw: index)] = \(child.varOrCaseName.backtickedIfNeeded)\(raw: optionalMark).raw" + ) + .with(\.leadingTrivia, .newline) } } @@ -240,13 +244,17 @@ func rawSyntaxNodesFile(nodesStartingWith: [Character]) -> SourceFileSyntax { } for (index, child) in node.children.enumerated() { - try VariableDeclSyntax("public var \(child.varOrCaseName.backtickedIfNeeded): Raw\(child.buildableType.buildable)") { + try VariableDeclSyntax( + "public var \(child.varOrCaseName.backtickedIfNeeded): Raw\(child.buildableType.buildable)" + ) { let exclamationMark = child.isOptional ? "" : "!" if child.syntaxNodeKind == .syntax { ExprSyntax("layoutView.children[\(raw: index)]\(raw: exclamationMark)") } else { - ExprSyntax("layoutView.children[\(raw: index)].map(\(child.syntaxNodeKind.rawType).init(raw:))\(raw: exclamationMark)") + ExprSyntax( + "layoutView.children[\(raw: index)].map(\(child.syntaxNodeKind.rawType).init(raw:))\(raw: exclamationMark)" + ) } } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxValidationFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxValidationFile.swift index a635fe8b08a..466374e82de 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxValidationFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxValidationFile.swift @@ -208,7 +208,9 @@ let rawSyntaxValidationFile = try! SourceFileSyntax(leadingTrivia: copyrightHead let verifiedChoices = ArrayExprSyntax { ArrayElementSyntax( leadingTrivia: .newline, - expression: ExprSyntax("verify(layout[\(raw: index)], as: Raw\(child.buildableType.buildable).self)") + expression: ExprSyntax( + "verify(layout[\(raw: index)], as: Raw\(child.buildableType.buildable).self)" + ) ) } @@ -229,7 +231,9 @@ let rawSyntaxValidationFile = try! SourceFileSyntax(leadingTrivia: copyrightHead ) ExprSyntax("assertNoError(kind, \(raw: index), \(verifyCall))") default: - ExprSyntax("assertNoError(kind, \(raw: index), verify(layout[\(raw: index)], as: Raw\(child.buildableType.buildable).self))") + ExprSyntax( + "assertNoError(kind, \(raw: index), verify(layout[\(raw: index)], as: Raw\(child.buildableType.buildable).self))" + ) } } } else if let node = node.collectionNode { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedChildrenCompatibilityFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedChildrenCompatibilityFile.swift index 117f855320b..ffa617a30e0 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedChildrenCompatibilityFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedChildrenCompatibilityFile.swift @@ -20,7 +20,8 @@ let renamedChildrenCompatibilityFile = try! SourceFileSyntax(leadingTrivia: copy try ExtensionDeclSyntax("extension \(layoutNode.type.syntaxBaseName)") { for child in layoutNode.children { if let deprecatedVarName = child.deprecatedVarName { - let childType: TypeSyntax = child.kind.isNodeChoicesEmpty ? child.syntaxNodeKind.syntaxType : child.syntaxChoicesType + let childType: TypeSyntax = + child.kind.isNodeChoicesEmpty ? child.syntaxNodeKind.syntaxType : child.syntaxChoicesType let type = child.isOptional ? TypeSyntax("\(childType)?") : childType DeclSyntax( @@ -38,8 +39,12 @@ let renamedChildrenCompatibilityFile = try! SourceFileSyntax(leadingTrivia: copy ) if let childNode = SYNTAX_NODE_MAP[child.syntaxNodeKind]?.collectionNode, !child.isUnexpectedNodes, - case .collection(_, collectionElementName: let collectionElementName, _, deprecatedCollectionElementName: let deprecatedCollectionElementName) = - child.kind, + case .collection( + kind: _, + collectionElementName: let collectionElementName, + defaultsToEmpty: _, + deprecatedCollectionElementName: let deprecatedCollectionElementName + ) = child.kind, let deprecatedCollectionElementName { let childEltType = childNode.collectionElementType.syntaxBaseName diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedSyntaxNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedSyntaxNodesFile.swift index 56e09a17bbb..ff1edd72331 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedSyntaxNodesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedSyntaxNodesFile.swift @@ -28,7 +28,8 @@ let renamedSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { } try! ExtensionDeclSyntax("public extension SyntaxKind") { - for syntaxKind in SyntaxNodeKind.allCases.sorted(by: { $0.deprecatedRawValue ?? "" < $1.deprecatedRawValue ?? "" }) { + let syntaxKinds = SyntaxNodeKind.allCases.sorted(by: { $0.deprecatedRawValue ?? "" < $1.deprecatedRawValue ?? "" }) + for syntaxKind in syntaxKinds { if let deprecatedName = syntaxKind.deprecatedRawValue { DeclSyntax( """ diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SwiftSyntaxDoccIndex.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SwiftSyntaxDoccIndex.swift index 65699262d7e..69c4282b85f 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SwiftSyntaxDoccIndex.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SwiftSyntaxDoccIndex.swift @@ -37,7 +37,10 @@ let nodesSections: String = { for (baseKind, heading) in nodeKinds { let baseTypes = ["\(baseKind.syntaxType)", "\(baseKind.syntaxType)Protocol", "Missing\(baseKind.syntaxType)"] - let leafTypes = SYNTAX_NODES.filter({ $0.base == baseKind && !$0.kind.isMissing && !$0.isExperimental }).map(\.kind.syntaxType.description) + let leafTypes = + SYNTAX_NODES + .filter({ $0.base == baseKind && !$0.kind.isMissing && !$0.isExperimental }) + .map(\.kind.syntaxType.description) addSection(heading: heading, types: baseTypes + leafTypes) } @@ -59,11 +62,16 @@ let nodesSections: String = { }) ) - addSection(heading: "Attributes", types: ATTRIBUTE_NODES.filter({ !$0.isExperimental }).map(\.kind.syntaxType.description).sorted()) + addSection( + heading: "Attributes", + types: ATTRIBUTE_NODES.filter({ !$0.isExperimental }).map(\.kind.syntaxType.description).sorted() + ) addSection( heading: "Miscellaneous Syntax", - types: SYNTAX_NODES.filter({ !$0.isExperimental }).map(\.kind.syntaxType.description).filter({ !handledSyntaxTypes.contains($0) }) + types: SYNTAX_NODES.filter({ !$0.isExperimental }).map(\.kind.syntaxType.description).filter({ + !handledSyntaxTypes.contains($0) + }) ) addSection(heading: "Traits", types: TRAITS.map { "\($0.protocolName)" }) @@ -84,7 +92,8 @@ var contributingDocs: String = { .appendingPathComponent("Documentation.docc") .appendingPathComponent("Contributing") - let files = (try? FileManager.default.contentsOfDirectory(at: contributingDocsFolder, includingPropertiesForKeys: nil)) ?? [] + let files = + (try? FileManager.default.contentsOfDirectory(at: contributingDocsFolder, includingPropertiesForKeys: nil)) ?? [] return files.compactMap { file in if file.pathExtension != "md" { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift index b9cb1c69a59..ca435890dbb 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift @@ -21,7 +21,8 @@ import Utils /// It then only emits those syntax nodes whose base kind are that specified kind. func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax { SourceFileSyntax(leadingTrivia: copyrightHeader) { - for node in SYNTAX_NODES.compactMap(\.layoutNode) where nodesStartingWith.contains(node.kind.syntaxType.description.first!) { + for node in SYNTAX_NODES.compactMap(\.layoutNode) + where nodesStartingWith.contains(node.kind.syntaxType.description.first!) { // We are actually handling this node now try! StructDeclSyntax( """ @@ -79,7 +80,9 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax { for child in node.children { ArrayElementSyntax( expression: MemberAccessExprSyntax( - base: child.buildableType.optionalChained(expr: ExprSyntax("\(child.varOrCaseName.backtickedIfNeeded)")), + base: child.buildableType.optionalChained( + expr: ExprSyntax("\(child.varOrCaseName.backtickedIfNeeded)") + ), period: .periodToken(), name: "raw" ) @@ -132,7 +135,8 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax { // Children properties // =================== - let childType: TypeSyntax = child.kind.isNodeChoicesEmpty ? child.syntaxNodeKind.syntaxType : child.syntaxChoicesType + let childType: TypeSyntax = + child.kind.isNodeChoicesEmpty ? child.syntaxNodeKind.syntaxType : child.syntaxChoicesType let type = child.isOptional ? TypeSyntax("\(childType)?") : TypeSyntax("\(childType)") try! VariableDeclSyntax( @@ -142,7 +146,8 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax { """ ) { AccessorDeclSyntax(accessorSpecifier: .keyword(.get)) { - let optionalityMarker: TokenSyntax = child.isOptional ? .infixQuestionMarkToken() : .exclamationMarkToken() + let optionalityMarker: TokenSyntax = + child.isOptional ? .infixQuestionMarkToken() : .exclamationMarkToken() StmtSyntax("return Syntax(self).child(at: \(raw: index))\(optionalityMarker).cast(\(childType).self)") } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift index 3b6cada55c6..799c8771413 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift @@ -146,7 +146,8 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { } } - for baseNode in SYNTAX_NODES where baseNode.kind.isBase && baseNode.kind != .syntax && baseNode.kind != .syntaxCollection { + for baseNode in SYNTAX_NODES + where baseNode.kind.isBase && baseNode.kind != .syntax && baseNode.kind != .syntaxCollection { let baseKind = baseNode.kind DeclSyntax( """ diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxTraitsFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxTraitsFile.swift index 87f2f3bcaae..e7b08785d0f 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxTraitsFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxTraitsFile.swift @@ -80,6 +80,8 @@ let syntaxTraitsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { } for node in SYNTAX_NODES.compactMap(\.layoutNode) where !node.traits.isEmpty { - DeclSyntax("extension \(node.kind.syntaxType): \(raw: node.traits.map { $0 + "Syntax" }.joined(separator: ", ")) {}") + DeclSyntax( + "extension \(node.kind.syntaxType): \(raw: node.traits.map { $0 + "Syntax" }.joined(separator: ", ")) {}" + ) } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift index 1516c583335..40ea9049bb6 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift @@ -204,7 +204,9 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { for node in NON_BASE_SYNTAX_NODES { SwitchCaseSyntax("case .\(node.varOrCaseName):") { - StmtSyntax("return { self.visitImpl(&$0, \(node.kind.syntaxType).self, self.visit, self.visitPost) }") + StmtSyntax( + "return { self.visitImpl(&$0, \(node.kind.syntaxType).self, self.visit, self.visitPost) }" + ) } } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TokenKindFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TokenKindFile.swift index 242e0952e81..11e2415b1ce 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TokenKindFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/TokenKindFile.swift @@ -130,7 +130,9 @@ let tokenKindFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { StmtSyntax("return true") } } else { - SwitchCaseSyntax("case (.\(tokenSpec.varOrCaseName)(let lhsText), .\(tokenSpec.varOrCaseName)(let rhsText)):") { + SwitchCaseSyntax( + "case (.\(tokenSpec.varOrCaseName)(let lhsText), .\(tokenSpec.varOrCaseName)(let rhsText)):" + ) { StmtSyntax("return lhsText == rhsText") } } diff --git a/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift b/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift index 5a590359b90..49028b06247 100644 --- a/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift +++ b/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift @@ -80,11 +80,13 @@ 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 + return varOrCaseName.description == other.varOrCaseName.description && kind.hasSameType(as: other.kind) + && isOptional == other.isOptional } func isFollowedByColonToken(in node: LayoutNode) -> Bool { - guard let childIndex = node.children.firstIndex(where: { $0.varOrCaseName.description == self.varOrCaseName.description }) else { + let childIndex = node.children.firstIndex(where: { $0.varOrCaseName.description == self.varOrCaseName.description }) + guard let childIndex else { preconditionFailure("\(self.varOrCaseName) is not a child of \(node.kind.syntaxType)") } guard childIndex + 2 < node.children.count else { @@ -121,7 +123,11 @@ class ValidateSyntaxNodes: XCTestCase { for node in SYNTAX_NODES where node.base != .syntaxCollection { if !node.kind.syntaxType.description.hasSuffix(node.base.syntaxType.description) { failures.append( - ValidationFailure(node: node.kind, message: "has base kind '\(node.base.syntaxType)' but type name doesn’t have '\(node.base.syntaxType)' suffix") + ValidationFailure( + node: node.kind, + message: + "has base kind '\(node.base.syntaxType)' but type name doesn’t have '\(node.base.syntaxType)' suffix" + ) ) } } @@ -129,8 +135,14 @@ class ValidateSyntaxNodes: XCTestCase { assertFailuresMatchXFails( failures, expectedFailures: [ - ValidationFailure(node: .canImportVersionInfo, message: "has base kind 'ExprSyntax' but type name doesn’t have 'ExprSyntax' suffix"), - ValidationFailure(node: .poundSourceLocation, message: "has base kind 'DeclSyntax' but type name doesn’t have 'DeclSyntax' suffix"), + ValidationFailure( + node: .canImportVersionInfo, + message: "has base kind 'ExprSyntax' but type name doesn’t have 'ExprSyntax' suffix" + ), + ValidationFailure( + node: .poundSourceLocation, + message: "has base kind 'DeclSyntax' but type name doesn’t have 'DeclSyntax' suffix" + ), ] ) } @@ -175,7 +187,8 @@ class ValidateSyntaxNodes: XCTestCase { } } else { if child.varOrCaseName.description != "\(keywordName)Keyword" { - return "child '\(child.varOrCaseName)' has a single keyword as its only token choice and should thus be named '\(keywordName)Keyword'" + return + "child '\(child.varOrCaseName)' has a single keyword as its only token choice and should thus be named '\(keywordName)Keyword'" } } @@ -184,7 +197,8 @@ class ValidateSyntaxNodes: XCTestCase { break case .token(.comma): if child.varOrCaseName.description != "trailingComma" && child.varOrCaseName.description != "comma" { - return "child '\(child.varOrCaseName)' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" + return + "child '\(child.varOrCaseName)' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" } case .token(let token): let expectedChildName = @@ -196,7 +210,8 @@ class ValidateSyntaxNodes: XCTestCase { .dropPrefix("binary") .withFirstCharacterLowercased if child.varOrCaseName.description != expectedChildName { - return "child '\(child.varOrCaseName)' has a token as its only token choice and should thus be named '\(expectedChildName)'" + return + "child '\(child.varOrCaseName)' has a token as its only token choice and should thus be named '\(expectedChildName)'" } } return nil @@ -222,17 +237,20 @@ class ValidateSyntaxNodes: XCTestCase { // Even though these nodes only accept e.g. 'async' name them consistently with properties that accept 'async' and 'reasync' ValidationFailure( node: .accessorEffectSpecifiers, - message: "child 'asyncSpecifier' has a single keyword as its only token choice and should thus be named 'asyncKeyword'" + message: + "child 'asyncSpecifier' has a single keyword as its only token choice and should thus be named 'asyncKeyword'" // To be consistent with AsyncSpecifier properties that can be both 'async' and 'reasync' ), ValidationFailure( node: .deinitializerEffectSpecifiers, - message: "child 'asyncSpecifier' has a single keyword as its only token choice and should thus be named 'asyncKeyword'" + message: + "child 'asyncSpecifier' has a single keyword as its only token choice and should thus be named 'asyncKeyword'" // To be consistent with AsyncSpecifier properties that can be both 'async' and 'reasync' ), ValidationFailure( node: .typeEffectSpecifiers, - message: "child 'asyncSpecifier' has a single keyword as its only token choice and should thus be named 'asyncKeyword'" + message: + "child 'asyncSpecifier' has a single keyword as its only token choice and should thus be named 'asyncKeyword'" // To be consistent with AsyncSpecifier properties that can be both 'async' and 'reasync' ), @@ -240,11 +258,13 @@ class ValidateSyntaxNodes: XCTestCase { // If there are two tokens of the same kind in a node, we can't follow the naming rule without conflict ValidationFailure( node: .differentiableAttributeArguments, - message: "child 'kindSpecifierComma' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" + message: + "child 'kindSpecifierComma' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" ), ValidationFailure( node: .differentiableAttributeArguments, - message: "child 'argumentsComma' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" + message: + "child 'argumentsComma' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" ), ValidationFailure( node: .poundSourceLocationArguments, @@ -257,7 +277,8 @@ class ValidateSyntaxNodes: XCTestCase { ), ValidationFailure( node: .regexLiteralExpr, - message: "child 'openingPounds' has a token as its only token choice and should thus be named 'regexPoundDelimiter'" + message: + "child 'openingPounds' has a token as its only token choice and should thus be named 'regexPoundDelimiter'" ), ValidationFailure( node: .regexLiteralExpr, @@ -270,28 +291,36 @@ class ValidateSyntaxNodes: XCTestCase { ), ValidationFailure( node: .regexLiteralExpr, - message: "child 'closingPounds' has a token as its only token choice and should thus be named 'regexPoundDelimiter'" + message: + "child 'closingPounds' has a token as its only token choice and should thus be named 'regexPoundDelimiter'" // There are the opening and closing ExtendedRegexDelimiter in the node ), // We should explicitly mention token here because it’s not obvious that the end of a file is represented by a token - ValidationFailure(node: .sourceFile, message: "child 'endOfFileToken' has a token as its only token choice and should thus be named 'endOfFile'"), + ValidationFailure( + node: .sourceFile, + message: "child 'endOfFileToken' has a token as its only token choice and should thus be named 'endOfFile'" + ), ValidationFailure( node: .stringLiteralExpr, - message: "child 'openingPounds' has a token as its only token choice and should thus be named 'rawStringPoundDelimiter'" + message: + "child 'openingPounds' has a token as its only token choice and should thus be named 'rawStringPoundDelimiter'" ), ValidationFailure( node: .stringLiteralExpr, - message: "child 'closingPounds' has a token as its only token choice and should thus be named 'rawStringPoundDelimiter'" + message: + "child 'closingPounds' has a token as its only token choice and should thus be named 'rawStringPoundDelimiter'" ), ValidationFailure( node: .expressionSegment, - message: "child 'pounds' has a token as its only token choice and should thus be named 'rawStringPoundDelimiter'" + message: + "child 'pounds' has a token as its only token choice and should thus be named 'rawStringPoundDelimiter'" ), // MARK: Tokens that contain underscores ValidationFailure( node: .borrowExpr, - message: "child 'borrowKeyword' has a single keyword as its only token choice and should thus be named '_borrowKeyword'" + message: + "child 'borrowKeyword' has a single keyword as its only token choice and should thus be named '_borrowKeyword'" // _borrow is underscored and thus BorrowKeyword is the correct spelling ), ValidationFailure( @@ -318,7 +347,8 @@ class ValidateSyntaxNodes: XCTestCase { // This is the only place where we use LeadingComma, similar to 'TrailingComma' ValidationFailure( node: .designatedType, - message: "child 'leadingComma' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" + message: + "child 'leadingComma' has a comma keyword as its only token choice and should thus be named 'comma' or 'trailingComma'" ), // This is similar to `TrailingComma` ValidationFailure( @@ -333,7 +363,8 @@ class ValidateSyntaxNodes: XCTestCase { // default is not a function argument label here but a proper keyword ValidationFailure( node: .switchDefaultLabel, - message: "child 'defaultKeyword' has a single keyword as its only token choice and is followed by a colon. It should thus be named 'defaultLabel'" + message: + "child 'defaultKeyword' has a single keyword as its only token choice and is followed by a colon. It should thus be named 'defaultLabel'" ), ] ) @@ -355,11 +386,13 @@ class ValidateSyntaxNodes: XCTestCase { var failureMessage: String? if child.isFollowedByColonToken(in: node) { if child.varOrCaseName.description != "label" && !child.varOrCaseName.description.hasSuffix("Label") { - failureMessage = "child '\(child.varOrCaseName)' only has keywords as its token choices, is followed by a colon and should thus end with 'Label'" + failureMessage = + "child '\(child.varOrCaseName)' only has keywords as its token choices, is followed by a colon and should thus end with 'Label'" } } else { if child.varOrCaseName.description != "specifier" && !child.varOrCaseName.description.hasSuffix("Specifier") { - failureMessage = "child '\(child.varOrCaseName)' only has keywords as its token choices and should thus end with 'Specifier'" + failureMessage = + "child '\(child.varOrCaseName)' only has keywords as its token choices and should thus end with 'Specifier'" } } if let failureMessage { @@ -469,7 +502,8 @@ class ValidateSyntaxNodes: XCTestCase { // MARK: Miscellaneous ValidationFailure( node: .multipleTrailingClosureElement, - message: "child 'closure' is named inconsistently with 'FunctionCallExprSyntax.trailingClosure', which has the same type ('ClosureExprSyntax')" + message: + "child 'closure' is named inconsistently with 'FunctionCallExprSyntax.trailingClosure', which has the same type ('ClosureExprSyntax')" ), ] ) @@ -502,14 +536,20 @@ class ValidateSyntaxNodes: XCTestCase { ValidationFailure(node: .accessorParameters, message: "could conform to trait 'NamedDecl' but does not"), ValidationFailure(node: .availabilityCondition, message: "could conform to trait 'Parenthesized' but does not"), ValidationFailure(node: .canImportExpr, message: "could conform to trait 'Parenthesized' but does not"), - ValidationFailure(node: .differentiabilityArguments, message: "could conform to trait 'Parenthesized' but does not"), + ValidationFailure( + node: .differentiabilityArguments, + message: "could conform to trait 'Parenthesized' but does not" + ), ValidationFailure(node: .editorPlaceholderDecl, message: "could conform to trait 'MissingNode' but does not"), ValidationFailure(node: .editorPlaceholderExpr, message: "could conform to trait 'MissingNode' but does not"), ValidationFailure(node: .enumCaseElement, message: "could conform to trait 'NamedDecl' but does not"), ValidationFailure(node: .genericParameter, message: "could conform to trait 'NamedDecl' but does not"), ValidationFailure(node: .precedenceGroupName, message: "could conform to trait 'NamedDecl' but does not"), ValidationFailure(node: .primaryAssociatedType, message: "could conform to trait 'NamedDecl' but does not"), - ValidationFailure(node: .yieldedExpressionsClause, message: "could conform to trait 'Parenthesized' but does not"), + ValidationFailure( + node: .yieldedExpressionsClause, + message: "could conform to trait 'Parenthesized' but does not" + ), ] ) } @@ -581,7 +621,10 @@ class ValidateSyntaxNodes: XCTestCase { failures, expectedFailures: [ // The child is singular here, the path just consists of multiple components - ValidationFailure(node: .importDecl, message: "child 'path' is a collection and should thus be named as a plural") + ValidationFailure( + node: .importDecl, + message: "child 'path' is a collection and should thus be named as a plural" + ) ] ) } @@ -592,7 +635,9 @@ class ValidateSyntaxNodes: XCTestCase { for node in SYNTAX_NODES.compactMap(\.layoutNode) { for child in node.nonUnexpectedChildren { - if child.varOrCaseName.description.contains("identifier") || child.varOrCaseName.description.contains("Identifier") { + if child.varOrCaseName.description.contains("identifier") + || child.varOrCaseName.description.contains("Identifier") + { failures.append( ValidationFailure( node: node.kind, @@ -607,7 +652,10 @@ class ValidateSyntaxNodes: XCTestCase { failures, expectedFailures: [ // The identifier expr / pattern nodes do actually have a child that’s the identifier - ValidationFailure(node: .identifierPattern, message: "child 'identifier' should generally not contain 'Identifier'") + ValidationFailure( + node: .identifierPattern, + message: "child 'identifier' should generally not contain 'Identifier'" + ) ] ) } @@ -639,12 +687,16 @@ class ValidateSyntaxNodes: XCTestCase { func testChildrenDontEndWithNodeKind() { var failures: [ValidationFailure] = [] - let forbiddenSuffixes = ["Decl", "Declaration", "Expr", "Expression", "Pattern", "Stmt", "Statement", "Syntax", "Type"] + let forbiddenSuffixes = [ + "Decl", "Declaration", "Expr", "Expression", "Pattern", "Stmt", "Statement", "Syntax", "Type", + ] for node in SYNTAX_NODES.compactMap(\.layoutNode) { for child in node.nonUnexpectedChildren { for forbiddenSuffix in forbiddenSuffixes { - if child.varOrCaseName.description.hasSuffix(forbiddenSuffix) && child.varOrCaseName.description != forbiddenSuffix.withFirstCharacterLowercased { + if child.varOrCaseName.description.hasSuffix(forbiddenSuffix) + && child.varOrCaseName.description != forbiddenSuffix.withFirstCharacterLowercased + { failures.append( ValidationFailure( node: node.kind, @@ -666,18 +718,30 @@ class ValidateSyntaxNodes: XCTestCase { ValidationFailure(node: .conformanceRequirement, message: "child 'rightType' should not end with 'Type'"), ValidationFailure(node: .extensionDecl, message: "child 'extendedType' should not end with 'Type'"), ValidationFailure(node: .genericParameter, message: "child 'inheritedType' should not end with 'Type'"), - ValidationFailure(node: .implicitlyUnwrappedOptionalType, message: "child 'wrappedType' should not end with 'Type'"), + ValidationFailure( + node: .implicitlyUnwrappedOptionalType, + message: "child 'wrappedType' should not end with 'Type'" + ), ValidationFailure(node: .memberType, message: "child 'baseType' should not end with 'Type'"), ValidationFailure(node: .metatypeType, message: "child 'baseType' should not end with 'Type'"), ValidationFailure(node: .optionalType, message: "child 'wrappedType' should not end with 'Type'"), ValidationFailure(node: .sameTypeRequirement, message: "child 'leftType' should not end with 'Type'"), ValidationFailure(node: .sameTypeRequirement, message: "child 'rightType' should not end with 'Type'"), // MARK: Adjective + Expr - ValidationFailure(node: .functionCallExpr, message: "child 'calledExpression' should not end with 'Expression'"), - ValidationFailure(node: .subscriptCallExpr, message: "child 'calledExpression' should not end with 'Expression'"), + ValidationFailure( + node: .functionCallExpr, + message: "child 'calledExpression' should not end with 'Expression'" + ), + ValidationFailure( + node: .subscriptCallExpr, + message: "child 'calledExpression' should not end with 'Expression'" + ), ValidationFailure(node: .ternaryExpr, message: "child 'thenExpression' should not end with 'Expression'"), ValidationFailure(node: .ternaryExpr, message: "child 'elseExpression' should not end with 'Expression'"), - ValidationFailure(node: .unresolvedTernaryExpr, message: "child 'thenExpression' should not end with 'Expression'"), + ValidationFailure( + node: .unresolvedTernaryExpr, + message: "child 'thenExpression' should not end with 'Expression'" + ), // MARK: Other // Even though the repetition pattern is not a PatternSyntax, pattern is the correct term here ValidationFailure(node: .packExpansionExpr, message: "child 'repetitionPattern' should not end with 'Pattern'"), @@ -755,7 +819,8 @@ class ValidateSyntaxNodes: XCTestCase { failures.append( ValidationFailure( node: node.kind, - message: "child '\(child.name)' is an optional syntax collection. All syntax collections should be non-optional." + message: + "child '\(child.name)' is an optional syntax collection. All syntax collections should be non-optional." ) ) } diff --git a/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift b/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift index ab7095fbdfb..6ffc4fd6829 100644 --- a/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift +++ b/EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift @@ -39,7 +39,8 @@ extension SourceEditorExtension { continue } - guard let typeMetadata = context.metadata(), let provider = typeMetadata as? any SyntaxRefactoringProvider.Type else { + guard let typeMetadata = context.metadata(), let provider = typeMetadata as? any SyntaxRefactoringProvider.Type + else { continue } @@ -57,7 +58,9 @@ struct Conformance { var raw: UnsafeRawPointer var `protocol`: Context { - let maybeProtocol = RelativeIndirectablePointer(offset: self.raw.load(as: ConformanceDescriptor.self).protocol) + let maybeProtocol = RelativeIndirectablePointer( + offset: self.raw.load(as: ConformanceDescriptor.self).protocol + ) return Context(raw: maybeProtocol.address(from: self.raw)) } @@ -95,7 +98,9 @@ struct Context: Hashable { var raw: UnsafeRawPointer var parent: Context? { - let parent = RelativeIndirectablePointer(offset: self.raw.load(as: ContextDescriptor.self).parent) + let parent = RelativeIndirectablePointer( + offset: self.raw.load(as: ContextDescriptor.self).parent + ) guard parent.offset != 0 else { return nil diff --git a/Examples/Sources/MacroExamples/Implementation/ComplexMacros/OptionSetMacro.swift b/Examples/Sources/MacroExamples/Implementation/ComplexMacros/OptionSetMacro.swift index 8fe8bdb6199..5b7eed9de30 100644 --- a/Examples/Sources/MacroExamples/Implementation/ComplexMacros/OptionSetMacro.swift +++ b/Examples/Sources/MacroExamples/Implementation/ComplexMacros/OptionSetMacro.swift @@ -93,7 +93,11 @@ public struct OptionSetMacro { case let .stringSegment(optionsEnumNameString)? = stringLiteral.segments.first else { if emitDiagnostics { - context.diagnose(OptionSetMacroDiagnostic.requiresStringLiteral(optionsEnumNameArgumentLabel).diagnose(at: optionEnumNameArg.expression)) + context.diagnose( + OptionSetMacroDiagnostic.requiresStringLiteral(optionsEnumNameArgumentLabel).diagnose( + at: optionEnumNameArg.expression + ) + ) } return nil } @@ -152,7 +156,9 @@ extension OptionSetMacro: ExtensionMacro { in context: some MacroExpansionContext ) throws -> [ExtensionDeclSyntax] { // Decode the expansion arguments. - guard let (structDecl, _, _) = decodeExpansion(of: node, attachedTo: declaration, in: context, emitDiagnostics: false) else { + guard + let (structDecl, _, _) = decodeExpansion(of: node, attachedTo: declaration, in: context, emitDiagnostics: false) + else { return [] } @@ -174,7 +180,14 @@ extension OptionSetMacro: MemberMacro { in context: some MacroExpansionContext ) throws -> [DeclSyntax] { // Decode the expansion arguments. - guard let (_, optionsEnum, rawType) = decodeExpansion(of: attribute, attachedTo: decl, in: context, emitDiagnostics: true) else { + guard + let (_, optionsEnum, rawType) = decodeExpansion( + of: attribute, + attachedTo: decl, + in: context, + emitDiagnostics: true + ) + else { return [] } diff --git a/Examples/Sources/MacroExamples/Implementation/Member/CustomCodable.swift b/Examples/Sources/MacroExamples/Implementation/Member/CustomCodable.swift index 1b4fffeb0b2..d7410da7398 100644 --- a/Examples/Sources/MacroExamples/Implementation/Member/CustomCodable.swift +++ b/Examples/Sources/MacroExamples/Implementation/Member/CustomCodable.swift @@ -24,7 +24,10 @@ public enum CustomCodable: MemberMacro { let cases = memberList.compactMap({ member -> String? in // is a property guard - let propertyName = member.decl.as(VariableDeclSyntax.self)?.bindings.first?.pattern.as(IdentifierPatternSyntax.self)?.identifier.text + let propertyName = member + .decl.as(VariableDeclSyntax.self)? + .bindings.first? + .pattern.as(IdentifierPatternSyntax.self)?.identifier.text else { return nil } @@ -35,7 +38,10 @@ public enum CustomCodable: MemberMacro { }) { // Uses the value in the Macro - let customKeyValue = customKeyMacro.as(AttributeSyntax.self)!.arguments!.as(LabeledExprListSyntax.self)!.first!.expression + let customKeyValue = customKeyMacro.as(AttributeSyntax.self)! + .arguments!.as(LabeledExprListSyntax.self)! + .first! + .expression return "case \(propertyName) = \(customKeyValue)" } else { diff --git a/Examples/Sources/MacroExamples/Implementation/Peer/AddAsyncMacro.swift b/Examples/Sources/MacroExamples/Implementation/Peer/AddAsyncMacro.swift index 2f9011368b9..4e25660cff8 100644 --- a/Examples/Sources/MacroExamples/Implementation/Peer/AddAsyncMacro.swift +++ b/Examples/Sources/MacroExamples/Implementation/Peer/AddAsyncMacro.swift @@ -49,9 +49,13 @@ public struct AddAsyncMacro: PeerMacro { } // Requires a completion handler block as last parameter - guard let completionHandlerParameterAttribute = funcDecl.signature.parameterClause.parameters.last?.type.as(AttributedTypeSyntax.self), - let completionHandlerParameter = completionHandlerParameterAttribute.baseType.as(FunctionTypeSyntax.self) - else { + let completionHandlerParameter = funcDecl + .signature + .parameterClause + .parameters.last? + .type.as(AttributedTypeSyntax.self)? + .baseType.as(FunctionTypeSyntax.self) + guard let completionHandlerParameter else { throw CustomError.message( "@addAsync requires an function that has a completion handler as last parameter" ) @@ -67,7 +71,12 @@ public struct AddAsyncMacro: PeerMacro { let returnType = completionHandlerParameter.parameters.first?.type let isResultReturn = returnType?.children(viewMode: .all).first?.description == "Result" - let successReturnType = isResultReturn ? returnType!.as(IdentifierTypeSyntax.self)!.genericArgumentClause?.arguments.first!.argument : returnType + let successReturnType = + if isResultReturn { + returnType!.as(IdentifierTypeSyntax.self)!.genericArgumentClause?.arguments.first!.argument + } else { + returnType + } // Remove completionHandler and comma from the previous parameter var newParameterList = funcDecl.signature.parameterClause.parameters @@ -132,7 +141,10 @@ public struct AddAsyncMacro: PeerMacro { // add result type if let successReturnType { - funcDecl.signature.returnClause = ReturnClauseSyntax(leadingTrivia: .space, type: successReturnType.with(\.leadingTrivia, .space)) + funcDecl.signature.returnClause = ReturnClauseSyntax( + leadingTrivia: .space, + type: successReturnType.with(\.leadingTrivia, .space) + ) } else { funcDecl.signature.returnClause = nil } diff --git a/Examples/Sources/MacroExamples/Interface/ComplexMacros.swift b/Examples/Sources/MacroExamples/Interface/ComplexMacros.swift index 49bec94696e..da160c99317 100644 --- a/Examples/Sources/MacroExamples/Interface/ComplexMacros.swift +++ b/Examples/Sources/MacroExamples/Interface/ComplexMacros.swift @@ -25,7 +25,8 @@ public macro DictionaryStorage() = #externalMacro(module: "MacroExamplesImplementation", type: "DictionaryStorageMacro") @attached(accessor) -public macro DictionaryStorageProperty() = #externalMacro(module: "MacroExamplesImplementation", type: "DictionaryStoragePropertyMacro") +public macro DictionaryStorageProperty() = + #externalMacro(module: "MacroExamplesImplementation", type: "DictionaryStoragePropertyMacro") // MARK: - Observable @@ -63,13 +64,22 @@ public struct ObservationRegistrar { } } -@attached(member, names: named(Storage), named(_storage), named(_registrar), named(addObserver), named(removeObserver), named(withTransaction)) +@attached( + member, + names: named(Storage), + named(_storage), + named(_registrar), + named(addObserver), + named(removeObserver), + named(withTransaction) +) @attached(memberAttribute) @attached(extension, conformances: Observable) public macro Observable() = #externalMacro(module: "MacroExamplesImplementation", type: "ObservableMacro") @attached(accessor) -public macro ObservableProperty() = #externalMacro(module: "MacroExamplesImplementation", type: "ObservablePropertyMacro") +public macro ObservableProperty() = + #externalMacro(module: "MacroExamplesImplementation", type: "ObservablePropertyMacro") // MARK: - Option Set diff --git a/Examples/Sources/MacroExamples/Interface/ExpressionMacros.swift b/Examples/Sources/MacroExamples/Interface/ExpressionMacros.swift index 647171d76ee..033526fa86d 100644 --- a/Examples/Sources/MacroExamples/Interface/ExpressionMacros.swift +++ b/Examples/Sources/MacroExamples/Interface/ExpressionMacros.swift @@ -46,14 +46,16 @@ public macro fontLiteral(name: String, size: Int, weight: FontWeight) -> T = /// "Stringify" the provided value and produce a tuple that includes both the /// original value as well as the source code that generated it. @freestanding(expression) -public macro stringify(_ value: T) -> (T, String) = #externalMacro(module: "MacroExamplesImplementation", type: "StringifyMacro") +public macro stringify(_ value: T) -> (T, String) = + #externalMacro(module: "MacroExamplesImplementation", type: "StringifyMacro") // MARK: - URL /// Check if provided string literal is a valid URL and produce a non-optional /// URL value. Emit error otherwise. @freestanding(expression) -public macro URL(_ stringLiteral: String) -> URL = #externalMacro(module: "MacroExamplesImplementation", type: "URLMacro") +public macro URL(_ stringLiteral: String) -> URL = + #externalMacro(module: "MacroExamplesImplementation", type: "URLMacro") // MARK: - Warning diff --git a/Examples/Sources/MacroExamples/Interface/MemberAttributeMacros.swift b/Examples/Sources/MacroExamples/Interface/MemberAttributeMacros.swift index bdfe4a64372..7790c7f8bd1 100644 --- a/Examples/Sources/MacroExamples/Interface/MemberAttributeMacros.swift +++ b/Examples/Sources/MacroExamples/Interface/MemberAttributeMacros.swift @@ -21,4 +21,5 @@ public macro memberDeprecated() = #externalMacro(module: "MacroExamplesImplement /// type or member to which the macro is attached. The string can be /// any attribute (without the `@`). @attached(memberAttribute) -public macro wrapStoredProperties(_ attributeName: String) = #externalMacro(module: "MacroExamplesImplementation", type: "WrapStoredPropertiesMacro") +public macro wrapStoredProperties(_ attributeName: String) = + #externalMacro(module: "MacroExamplesImplementation", type: "WrapStoredPropertiesMacro") diff --git a/Examples/Sources/MacroExamples/Interface/PeerMacros.swift b/Examples/Sources/MacroExamples/Interface/PeerMacros.swift index 458ccb5d230..7eec83b1a5c 100644 --- a/Examples/Sources/MacroExamples/Interface/PeerMacros.swift +++ b/Examples/Sources/MacroExamples/Interface/PeerMacros.swift @@ -21,9 +21,11 @@ public macro AddAsync() = #externalMacro(module: "MacroExamplesImplementation", /// task , calls the original async function, and delivers its result to the completion /// handler. @attached(peer, names: overloaded) -public macro AddCompletionHandler() = #externalMacro(module: "MacroExamplesImplementation", type: "AddCompletionHandlerMacro") +public macro AddCompletionHandler() = + #externalMacro(module: "MacroExamplesImplementation", type: "AddCompletionHandlerMacro") // MARK: - Peer Value With Suffix Name @attached(peer, names: suffixed(_peer)) -public macro PeerValueWithSuffixName() = #externalMacro(module: "MacroExamplesImplementation", type: "PeerValueWithSuffixNameMacro") +public macro PeerValueWithSuffixName() = + #externalMacro(module: "MacroExamplesImplementation", type: "PeerValueWithSuffixNameMacro") diff --git a/Examples/Tests/MacroExamples/Implementation/Member/MetaEnumMacroTests.swift b/Examples/Tests/MacroExamples/Implementation/Member/MetaEnumMacroTests.swift index e7035fb9880..34f38d16359 100644 --- a/Examples/Tests/MacroExamples/Implementation/Member/MetaEnumMacroTests.swift +++ b/Examples/Tests/MacroExamples/Implementation/Member/MetaEnumMacroTests.swift @@ -113,7 +113,14 @@ final class MetaEnumMacroTests: XCTestCase { let boolean: Bool } """, - diagnostics: [DiagnosticSpec(message: "'@MetaEnum' can only be attached to an enum, not a struct", line: 1, column: 1, severity: .error)], + diagnostics: [ + DiagnosticSpec( + message: "'@MetaEnum' can only be attached to an enum, not a struct", + line: 1, + column: 1, + severity: .error + ) + ], macros: macros, indentationWidth: .spaces(2) ) diff --git a/Package.swift b/Package.swift index 62d7a020d8d..ffd4fabb57b 100644 --- a/Package.swift +++ b/Package.swift @@ -87,7 +87,14 @@ let package = Package( .target( name: "SwiftCompilerPluginMessageHandling", - dependencies: ["SwiftDiagnostics", "SwiftOperators", "SwiftParser", "SwiftSyntax", "SwiftSyntaxMacros", "SwiftSyntaxMacroExpansion"], + dependencies: [ + "SwiftDiagnostics", + "SwiftOperators", + "SwiftParser", + "SwiftSyntax", + "SwiftSyntaxMacros", + "SwiftSyntaxMacroExpansion", + ], exclude: ["CMakeLists.txt"] ), @@ -183,8 +190,15 @@ let package = Package( .testTarget( name: "SwiftSyntaxMacroExpansionTest", dependencies: [ - "SwiftSyntax", "_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftOperators", "SwiftParser", "SwiftSyntaxBuilder", "SwiftSyntaxMacros", - "SwiftSyntaxMacroExpansion", "SwiftSyntaxMacrosTestSupport", + "SwiftSyntax", + "_SwiftSyntaxTestSupport", + "SwiftDiagnostics", + "SwiftOperators", + "SwiftParser", + "SwiftSyntaxBuilder", + "SwiftSyntaxMacros", + "SwiftSyntaxMacroExpansion", + "SwiftSyntaxMacrosTestSupport", ] ), @@ -192,7 +206,14 @@ let package = Package( .target( name: "SwiftSyntaxMacrosTestSupport", - dependencies: ["_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftIDEUtils", "SwiftParser", "SwiftSyntaxMacros", "SwiftSyntaxMacroExpansion"] + dependencies: [ + "_SwiftSyntaxTestSupport", + "SwiftDiagnostics", + "SwiftIDEUtils", + "SwiftParser", + "SwiftSyntaxMacros", + "SwiftSyntaxMacroExpansion", + ] ), .testTarget( @@ -211,7 +232,14 @@ let package = Package( .testTarget( name: "SwiftParserTest", - dependencies: ["_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftIDEUtils", "SwiftOperators", "SwiftParser", "SwiftSyntaxBuilder"], + dependencies: [ + "_SwiftSyntaxTestSupport", + "SwiftDiagnostics", + "SwiftIDEUtils", + "SwiftOperators", + "SwiftParser", + "SwiftSyntaxBuilder", + ], swiftSettings: swiftParserSwiftSettings ), diff --git a/Sources/SwiftBasicFormat/BasicFormat.swift b/Sources/SwiftBasicFormat/BasicFormat.swift index ee63614091a..b1449e05650 100644 --- a/Sources/SwiftBasicFormat/BasicFormat.swift +++ b/Sources/SwiftBasicFormat/BasicFormat.swift @@ -288,8 +288,10 @@ open class BasicFormat: SyntaxRewriter { case (.multilineStringQuote, .backslash), // string interpolation segment inside a multi-line string literal (.multilineStringQuote, .multilineStringQuote), // empty multi-line string literal (.multilineStringQuote, .stringSegment), // segment starting a multi-line string literal - (.stringSegment, .multilineStringQuote), // ending a multi-line string literal that has a string interpolation segment at its end - (.rightParen, .multilineStringQuote), // ending a multi-line string literal that has a string interpolation segment at its end + // ending a multi-line string literal that has a string interpolation segment at its end + (.stringSegment, .multilineStringQuote), + // ending a multi-line string literal that has a string interpolation segment at its end + (.rightParen, .multilineStringQuote), (.poundEndif, _), (_, .poundElse), (_, .poundElseif), @@ -332,7 +334,8 @@ open class BasicFormat: SyntaxRewriter { (.leftBrace, .rightBrace), // {} (.leftParen, _), (.leftSquare, _), - (.multilineStringQuote, .rawStringPoundDelimiter), // closing raw string delimiter should never be separate by a space + // closing raw string delimiter should never be separate by a space + (.multilineStringQuote, .rawStringPoundDelimiter), (.period, _), (.postfixQuestionMark, .leftAngle), // init?() (.postfixQuestionMark, .leftParen), // init?() or myOptionalClosure?() @@ -342,7 +345,8 @@ open class BasicFormat: SyntaxRewriter { (.prefixAmpersand, _), (.prefixOperator, _), (.rawStringPoundDelimiter, .leftParen), // opening raw string delimiter should never be separate by a space - (.rawStringPoundDelimiter, .multilineStringQuote), // opening raw string delimiter should never be separate by a space + // opening raw string delimiter should never be separate by a space + (.rawStringPoundDelimiter, .multilineStringQuote), (.rawStringPoundDelimiter, .singleQuote), // opening raw string delimiter should never be separate by a space (.rawStringPoundDelimiter, .stringQuote), // opening raw string delimiter should never be separate by a space (.rawStringPoundDelimiter, .period), // opening raw string delimiter should never be separate by a space @@ -378,9 +382,11 @@ open class BasicFormat: SyntaxRewriter { { return false } - case (.leftAngle, _) where second?.tokenKind != .rightAngle: // `<` and `>` need to be separated by a space because otherwise they become an operator + case (.leftAngle, _) where second?.tokenKind != .rightAngle: + // `<` and `>` need to be separated by a space because otherwise they become an operator return false - case (_, .rightAngle) where first?.tokenKind != .leftAngle: // `<` and `>` need to be separated by a space because otherwise they become an operator + case (_, .rightAngle) where first?.tokenKind != .leftAngle: + // `<` and `>` need to be separated by a space because otherwise they become an operator return false default: break @@ -533,7 +539,9 @@ open class BasicFormat: SyntaxRewriter { return true } else if token.text.first?.isNewline ?? false { return true - } else if (transformedTokenText ?? token.text).isEmpty && token.trailingTrivia.isEmpty && nextTokenWillStartWithNewline { + } else if (transformedTokenText ?? token.text).isEmpty && token.trailingTrivia.isEmpty + && nextTokenWillStartWithNewline + { return true } else { return false @@ -559,7 +567,9 @@ open class BasicFormat: SyntaxRewriter { } } - if leadingTrivia.indentation(isOnNewline: isInitialToken || previousTokenWillEndWithNewline) == [] && !token.isStringSegment { + if leadingTrivia.indentation(isOnNewline: isInitialToken || previousTokenWillEndWithNewline) == [] + && !token.isStringSegment + { // If the token starts on a new line and does not have indentation, this // is the last non-indented token. Store its indentation level. // But never consider string segments as anchor points since you can’t @@ -623,8 +633,12 @@ open class BasicFormat: SyntaxRewriter { addIndentationAfterLastNewline: false ) - leadingTrivia = leadingTrivia.trimmingTrailingWhitespaceBeforeNewline(isBeforeNewline: leadingTriviaIsFollowedByNewline) - trailingTrivia = trailingTrivia.trimmingTrailingWhitespaceBeforeNewline(isBeforeNewline: nextTokenWillStartWithNewline) + leadingTrivia = leadingTrivia.trimmingTrailingWhitespaceBeforeNewline( + isBeforeNewline: leadingTriviaIsFollowedByNewline + ) + trailingTrivia = trailingTrivia.trimmingTrailingWhitespaceBeforeNewline( + isBeforeNewline: nextTokenWillStartWithNewline + ) var result = token.detached if leadingTrivia != result.leadingTrivia { diff --git a/Sources/SwiftBasicFormat/InferIndentation.swift b/Sources/SwiftBasicFormat/InferIndentation.swift index 360cf059200..3fff63c04d6 100644 --- a/Sources/SwiftBasicFormat/InferIndentation.swift +++ b/Sources/SwiftBasicFormat/InferIndentation.swift @@ -56,8 +56,8 @@ private class IndentationInferrer: SyntaxVisitor { let triviaAtStartOfLine = (previousTokenTrailingTrivia + token.leadingTrivia) .drop(while: { !$0.isNewline }) // Ignore any trivia that's on the previous line - .split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) // Split trivia into the lines it occurs on - .dropFirst() // Drop the first empty array; exists because we dropped non-newline prefix and newline is separator + .split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) // Split trivia into lines + .dropFirst() // Drop the first empty array; because we dropped non-newline prefix and newline is separator LINE_TRIVIA_LOOP: for lineTrivia in triviaAtStartOfLine { switch lineTrivia.first { diff --git a/Sources/SwiftCompilerPlugin/CompilerPlugin.swift b/Sources/SwiftCompilerPlugin/CompilerPlugin.swift index 8787de36aab..9c8d7f9a58e 100644 --- a/Sources/SwiftCompilerPlugin/CompilerPlugin.swift +++ b/Sources/SwiftCompilerPlugin/CompilerPlugin.swift @@ -87,7 +87,10 @@ extension CompilerPlugin { } let pluginPath = CommandLine.arguments.first ?? Bundle.main.executablePath ?? ProcessInfo.processInfo.processName - throw CompilerPluginError(message: "macro implementation type '\(moduleName).\(typeName)' could not be found in executable plugin '\(pluginPath)'") + throw CompilerPluginError( + message: + "macro implementation type '\(moduleName).\(typeName)' could not be found in executable plugin '\(pluginPath)'" + ) } } diff --git a/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift b/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift index 469bcc56ddb..02ea6d3c43e 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift @@ -145,7 +145,11 @@ class SourceManager { /// Get location of `node` in the known root nodes. /// The root node of `node` must be one of the returned value from `add(_:)`. - func location(of node: Syntax, at kind: PositionInSyntaxNode, filePathMode: SourceLocationFilePathMode) -> SourceLocation? { + func location( + of node: Syntax, + at kind: PositionInSyntaxNode, + filePathMode: SourceLocationFilePathMode + ) -> SourceLocation? { guard let base = self.knownSourceSyntax[node.root.id] else { return nil } diff --git a/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift b/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift index be7d34fc421..da006ec77b2 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift @@ -226,7 +226,14 @@ public enum PluginMessage { public var notes: [Note] public var fixIts: [FixIt] - internal init(message: String, severity: Severity, position: Position, highlights: [PositionRange], notes: [Note], fixIts: [FixIt]) { + internal init( + message: String, + severity: Severity, + position: Position, + highlights: [PositionRange], + notes: [Note], + fixIts: [FixIt] + ) { self.message = message self.severity = severity self.position = position diff --git a/Sources/SwiftDiagnostics/DiagnosticDecorators/ANSIDiagnosticDecorator.swift b/Sources/SwiftDiagnostics/DiagnosticDecorators/ANSIDiagnosticDecorator.swift index 5d50df5d96e..41227012709 100644 --- a/Sources/SwiftDiagnostics/DiagnosticDecorators/ANSIDiagnosticDecorator.swift +++ b/Sources/SwiftDiagnostics/DiagnosticDecorators/ANSIDiagnosticDecorator.swift @@ -46,7 +46,10 @@ extension DiagnosticDecorator where Self == ANSIDiagnosticDecorator { /// ```bash /// printf "\e[1;31merror: \e[1;39mFile not found\e[0;0m\n" /// ``` - @_spi(Testing) public func decorateMessage(_ message: String, basedOnSeverity severity: DiagnosticSeverity) -> String { + @_spi(Testing) public func decorateMessage( + _ message: String, + basedOnSeverity severity: DiagnosticSeverity + ) -> String { let severityText: String let severityAnnotation: ANSIAnnotation @@ -68,7 +71,11 @@ extension DiagnosticDecorator where Self == ANSIDiagnosticDecorator { severityAnnotation = .remarkText } - let prefix = colorizeIfNotEmpty("\(severityText): ", usingAnnotation: severityAnnotation, resetAfterApplication: false) + let prefix = colorizeIfNotEmpty( + "\(severityText): ", + usingAnnotation: severityAnnotation, + resetAfterApplication: false + ) return prefix + colorizeIfNotEmpty(message, usingAnnotation: .diagnosticText) } @@ -102,8 +109,13 @@ extension DiagnosticDecorator where Self == ANSIDiagnosticDecorator { /// ```bash /// printf "\e[4;39mlet x = 10\e[0;0m\n" /// ``` - @_spi(Testing) public func decorateHighlight(_ highlight: String) -> (highlightedSourceCode: String, additionalHighlightedLine: String?) { - (highlightedSourceCode: colorizeIfNotEmpty(highlight, usingAnnotation: .sourceHighlight), additionalHighlightedLine: nil) + @_spi(Testing) public func decorateHighlight(_ highlight: String) -> ( + highlightedSourceCode: String, additionalHighlightedLine: String? + ) { + ( + highlightedSourceCode: colorizeIfNotEmpty(highlight, usingAnnotation: .sourceHighlight), + additionalHighlightedLine: nil + ) } /// Applies ANSI annotation to a given text segment, if the text is not empty. diff --git a/Sources/SwiftDiagnostics/DiagnosticDecorators/BasicDiagnosticDecorator.swift b/Sources/SwiftDiagnostics/DiagnosticDecorators/BasicDiagnosticDecorator.swift index 44dfafc90e1..a73fb60ad4e 100644 --- a/Sources/SwiftDiagnostics/DiagnosticDecorators/BasicDiagnosticDecorator.swift +++ b/Sources/SwiftDiagnostics/DiagnosticDecorators/BasicDiagnosticDecorator.swift @@ -32,7 +32,10 @@ extension DiagnosticDecorator where Self == BasicDiagnosticDecorator { /// - severity: The severity level associated with the diagnostic message. /// /// - Returns: A string that combines the severity-specific prefix and the original diagnostic message. - @_spi(Testing) public func decorateMessage(_ message: String, basedOnSeverity severity: DiagnosticSeverity) -> String { + @_spi(Testing) public func decorateMessage( + _ message: String, + basedOnSeverity severity: DiagnosticSeverity + ) -> String { let severityText: String switch severity { @@ -65,7 +68,9 @@ extension DiagnosticDecorator where Self == BasicDiagnosticDecorator { /// - Returns: A tuple containing: /// - `highlightedSourceCode`: The original text segment. /// - `additionalHighlightedLine`: Always nil. - @_spi(Testing) public func decorateHighlight(_ highlight: String) -> (highlightedSourceCode: String, additionalHighlightedLine: String?) { + @_spi(Testing) public func decorateHighlight(_ highlight: String) -> ( + highlightedSourceCode: String, additionalHighlightedLine: String? + ) { return (highlightedSourceCode: highlight, additionalHighlightedLine: nil) } } diff --git a/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift b/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift index 83573be6db3..3bbcee44f92 100644 --- a/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift +++ b/Sources/SwiftDiagnostics/DiagnosticsFormatter.swift @@ -232,7 +232,9 @@ public struct DiagnosticsFormatter { return nil }.joined() - annotatedSourceLines.append(AnnotatedSourceLine(diagnostics: diagsForLine, sourceString: sourceLine, suffixText: suffixText)) + annotatedSourceLines.append( + AnnotatedSourceLine(diagnostics: diagsForLine, sourceString: sourceLine, suffixText: suffixText) + ) } // Only lines with diagnostic messages should be printed, but including some context @@ -270,7 +272,9 @@ public struct DiagnosticsFormatter { // If necessary, print a line that indicates that there was lines skipped in the source code if hasLineBeenSkipped && !annotatedSource.isEmpty { - let lineMissingInfoLine = indentString + String(repeating: " ", count: maxNumberOfDigits) + " \(diagnosticDecorator.decorateBufferOutline("┆"))" + let lineMissingInfoLine = + indentString + String(repeating: " ", count: maxNumberOfDigits) + + " \(diagnosticDecorator.decorateBufferOutline("┆"))" annotatedSource.append("\(lineMissingInfoLine)\n") } hasLineBeenSkipped = false @@ -307,7 +311,9 @@ public struct DiagnosticsFormatter { for (column, diags) in diagsPerColumn { // compute the string that is shown before each message - var preMessage = indentString + String(repeating: " ", count: maxNumberOfDigits) + " " + diagnosticDecorator.decorateBufferOutline("│") + var preMessage = + indentString + String(repeating: " ", count: maxNumberOfDigits) + " " + + diagnosticDecorator.decorateBufferOutline("│") for c in 0.., in tree: some SyntaxProtocol) -> [DeclNameLocation] { + public static func resolve( + baseNamePositions: some Sequence, + in tree: some SyntaxProtocol + ) -> [DeclNameLocation] { let matcher = NameMatcher(baseNamePositions: baseNamePositions) matcher.walk(tree) return matcher.resolvedLocs @@ -172,7 +175,10 @@ public class NameMatcher: SyntaxAnyVisitor { return .labeled(firstName: additionalTrailingClosure.label, secondName: nil) } } - addResolvedLocIfRequested(baseName: baseName, argumentLabels: .call(argumentLabels, firstTrailingClosureIndex: firstTrailingClosureIndex)) + addResolvedLocIfRequested( + baseName: baseName, + argumentLabels: .call(argumentLabels, firstTrailingClosureIndex: firstTrailingClosureIndex) + ) } /// Try resolving a function-style declaration at `baseName`. @@ -199,20 +205,26 @@ public class NameMatcher: SyntaxAnyVisitor { } public override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { - while let baseNamePosition = firstPositionToResolve(in: token.leadingTriviaRange) ?? firstPositionToResolve(in: token.trailingTriviaRange) { + while let baseNamePosition = firstPositionToResolve(in: token.leadingTriviaRange) + ?? firstPositionToResolve(in: token.trailingTriviaRange) + { // Parse the comment from the position that we want to resolve. This should parse any function calls or compound decl names, the rest of // the comment will probably be parsed as garbage but that's OK because we don't actually care about it. let positionOffsetInToken = baseNamePosition.utf8Offset - token.position.utf8Offset - let commentTree = token.syntaxTextBytes[positionOffsetInToken...].withUnsafeBufferPointer { (buffer) -> ExprSyntax in - var parser = Parser(buffer) - return ExprSyntax.parse(from: &parser) - } + let commentTree = token.syntaxTextBytes[positionOffsetInToken...] + .withUnsafeBufferPointer { (buffer) -> ExprSyntax in + var parser = Parser(buffer) + return ExprSyntax.parse(from: &parser) + } // Run a new `NameMatcher`. Since the input of that name matcher is the text after the position to resolve, we // want to resolve the position at offset 0. let resolvedInComment = NameMatcher.resolve(baseNamePositions: [AbsolutePosition(utf8Offset: 0)], in: commentTree) let positionRemoved = removePositionToResolveIfExists(at: baseNamePosition) - precondition(positionRemoved, "Found a position with `firstPositionToResolve but didn't find it again to remove it?") + precondition( + positionRemoved, + "Found a position with `firstPositionToResolve but didn't find it again to remove it?" + ) // Adjust the positions to point back to the original tree, set the context as `comment` and record them. resolvedLocs += resolvedInComment.map { locationInComment in @@ -381,7 +393,10 @@ public class NameMatcher: SyntaxAnyVisitor { let argumentLabels = node.parameterClause.parameters.map { (argument) -> DeclNameLocation.Argument in return .labeled(firstName: argument.firstName, secondName: argument.secondName) } - addResolvedLocIfRequested(baseName: node.subscriptKeyword, argumentLabels: .noncollapsibleParameters(argumentLabels)) + addResolvedLocIfRequested( + baseName: node.subscriptKeyword, + argumentLabels: .noncollapsibleParameters(argumentLabels) + ) return .visitChildren } } diff --git a/Sources/SwiftParser/Attributes.swift b/Sources/SwiftParser/Attributes.swift index 2d02f58db4b..0d79d678a03 100644 --- a/Sources/SwiftParser/Attributes.swift +++ b/Sources/SwiftParser/Attributes.swift @@ -190,7 +190,9 @@ extension Parser { case .required: shouldParseArgument = true case .customAttribute: - shouldParseArgument = self.withLookahead { $0.atCustomAttributeArgument() } && self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)) + shouldParseArgument = + self.withLookahead { $0.atCustomAttributeArgument() } + && self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)) case .optional: shouldParseArgument = self.at(.leftParen) case .noArgument: @@ -198,7 +200,9 @@ extension Parser { } if shouldParseArgument { var (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen) - if unexpectedBeforeLeftParen == nil && (attributeName.raw.trailingTriviaByteLength > 0 || leftParen.leadingTriviaByteLength > 0) { + if unexpectedBeforeLeftParen == nil + && (attributeName.raw.trailingTriviaByteLength > 0 || leftParen.leadingTriviaByteLength > 0) + { let diagnostic = TokenDiagnostic( self.swiftVersion < .v6 ? .extraneousLeadingWhitespaceWarning : .extraneousLeadingWhitespaceError, byteOffset: 0 @@ -283,7 +287,8 @@ extension Parser { return parseAttribute(argumentMode: .required) { parser in return .documentationArguments(parser.parseDocumentationAttributeArguments()) } - case ._spi, ._objcRuntimeName, ._projectedValueProperty, ._swift_native_objc_runtime_base, ._typeEraser, ._optimize, .exclusivity, .inline, ._alignment: + 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: // - Arbitrary identifiers (e.g. `@_spi(RawSyntax)`) // - An integer literal (e.g. `@_alignment(4)`) @@ -352,7 +357,9 @@ extension Parser { unexpectedBeforeAtSign, atSign: atSign, unexpectedBeforeAttributeName, - attributeName: RawTypeSyntax(RawIdentifierTypeSyntax(name: attributeName, genericArgumentClause: nil, arena: self.arena)), + attributeName: RawTypeSyntax( + RawIdentifierTypeSyntax(name: attributeName, genericArgumentClause: nil, arena: self.arena) + ), leftParen: nil, arguments: nil, rightParen: nil, @@ -400,7 +407,11 @@ extension RawLabeledExprSyntax { extension Parser { mutating func parseMacroRoleArguments() -> [RawLabeledExprSyntax] { - let (unexpectedBeforeRole, role) = self.expect(.identifier, TokenSpec(.extension, remapping: .identifier), default: .identifier) + let (unexpectedBeforeRole, role) = self.expect( + .identifier, + TokenSpec(.extension, remapping: .identifier), + default: .identifier + ) let roleTrailingComma = self.consume(if: .comma) let roleElement = RawLabeledExprSyntax( @@ -417,7 +428,9 @@ extension Parser { extension Parser { mutating func parseDifferentiableAttribute() -> RawAttributeSyntax { let (unexpectedBeforeAtSign, atSign) = self.expect(.atSign) - let (unexpectedBeforeDifferentiable, differentiable) = self.expect(TokenSpec(.differentiable, remapping: .identifier)) + let (unexpectedBeforeDifferentiable, differentiable) = self.expect( + TokenSpec(.differentiable, remapping: .identifier) + ) let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen) let argument = self.parseDifferentiableAttributeArguments() @@ -427,7 +440,9 @@ extension Parser { unexpectedBeforeAtSign, atSign: atSign, unexpectedBeforeDifferentiable, - attributeName: RawTypeSyntax(RawIdentifierTypeSyntax(name: differentiable, genericArgumentClause: nil, arena: self.arena)), + attributeName: RawTypeSyntax( + RawIdentifierTypeSyntax(name: differentiable, genericArgumentClause: nil, arena: self.arena) + ), unexpectedBeforeLeftParen, leftParen: leftParen, arguments: .differentiableArguments(argument), @@ -569,7 +584,9 @@ extension Parser { unexpectedBeforeAtSign, atSign: atSign, unexpectedBeforeDerivative, - attributeName: RawTypeSyntax(RawIdentifierTypeSyntax(name: derivative, genericArgumentClause: nil, arena: self.arena)), + attributeName: RawTypeSyntax( + RawIdentifierTypeSyntax(name: derivative, genericArgumentClause: nil, arena: self.arena) + ), unexpectedBeforeLeftParen, leftParen: leftParen, arguments: .derivativeRegistrationArguments(argument), @@ -591,7 +608,9 @@ extension Parser { unexpectedBeforeAtSign, atSign: atSign, unexpectedBeforeTranspose, - attributeName: RawTypeSyntax(RawIdentifierTypeSyntax(name: transpose, genericArgumentClause: nil, arena: self.arena)), + attributeName: RawTypeSyntax( + RawIdentifierTypeSyntax(name: transpose, genericArgumentClause: nil, arena: self.arena) + ), unexpectedBeforeLeftParen, leftParen: leftParen, arguments: .derivativeRegistrationArguments(argument), @@ -1064,7 +1083,11 @@ extension Parser { var keepGoing: RawTokenSyntax? = nil repeat { - let (unexpectedBeforeLabel, label) = self.expect(.keyword(.visibility), .keyword(.metadata), default: .keyword(.visibility)) + let (unexpectedBeforeLabel, label) = self.expect( + .keyword(.visibility), + .keyword(.metadata), + default: .keyword(.visibility) + ) let (unexpectedBeforeColon, colon) = self.expect(.colon) let unexpectedBeforeValue: RawUnexpectedNodesSyntax? let value: RawDocumentationAttributeArgumentSyntax.Value @@ -1168,7 +1191,9 @@ extension Parser.Lookahead { return false } - if self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)) && self.withLookahead({ $0.atCustomAttributeArgument() }) { + if self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)) + && self.withLookahead({ $0.atCustomAttributeArgument() }) + { self.skipSingle() } diff --git a/Sources/SwiftParser/Availability.swift b/Sources/SwiftParser/Availability.swift index 449448a368e..2358d5e4107 100644 --- a/Sources/SwiftParser/Availability.swift +++ b/Sources/SwiftParser/Availability.swift @@ -257,7 +257,10 @@ extension Parser { { // The lexer generates a float literal '1.2' for the major and minor version. // Split it into two integers if possible - let major = self.consumePrefix(SyntaxText(rebasing: self.currentToken.tokenText[0..") { + if attributes.isEmpty && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing + && elements.isEmpty && !self.at(prefix: ">") + { break } @@ -952,7 +964,11 @@ extension Parser { // Parse the '!' or '?' for a failable initializer. let failable: RawTokenSyntax? - if let parsedFailable = self.consume(if: .exclamationMark, .postfixQuestionMark, TokenSpec(.infixQuestionMark, remapping: .postfixQuestionMark)) { + if let parsedFailable = self.consume( + if: .exclamationMark, + .postfixQuestionMark, + TokenSpec(.infixQuestionMark, remapping: .postfixQuestionMark) + ) { failable = parsedFailable } else if let parsedFailable = self.consumeIfContextualPunctuator("!", remapping: .exclamationMark) { failable = parsedFailable @@ -1046,9 +1062,10 @@ extension Parser { extension Parser { /// If a `throws` keyword appears right in front of the `arrow`, it is returned as `misplacedThrowsKeyword` so it can be synthesized in front of the arrow. - mutating func parseFunctionReturnClause(effectSpecifiers: inout (some RawMisplacedEffectSpecifiersTrait)?, allowNamedOpaqueResultType: Bool) - -> RawReturnClauseSyntax - { + mutating func parseFunctionReturnClause( + effectSpecifiers: inout (some RawMisplacedEffectSpecifiersTrait)?, + allowNamedOpaqueResultType: Bool + ) -> RawReturnClauseSyntax { let (unexpectedBeforeArrow, arrow) = self.expect(.arrow) let unexpectedBeforeReturnType = self.parseMisplacedEffectSpecifiers(&effectSpecifiers) let type: RawTypeSyntax @@ -1143,7 +1160,10 @@ extension Parser { /// Only allow recovery to the arrow with exprKeyword precedence so we only /// skip over misplaced identifiers and don't e.g. recover to an arrow in a 'where' clause. if self.canRecoverTo(TokenSpec(.arrow, recoveryPrecedence: .exprKeyword)) != nil { - returnClause = self.parseFunctionReturnClause(effectSpecifiers: &effectSpecifiers, allowNamedOpaqueResultType: true) + returnClause = self.parseFunctionReturnClause( + effectSpecifiers: &effectSpecifiers, + allowNamedOpaqueResultType: true + ) } else { returnClause = nil } @@ -1184,7 +1204,10 @@ extension Parser { } var misplacedEffectSpecifiers: RawFunctionEffectSpecifiersSyntax? - let returnClause = self.parseFunctionReturnClause(effectSpecifiers: &misplacedEffectSpecifiers, allowNamedOpaqueResultType: true) + let returnClause = self.parseFunctionReturnClause( + effectSpecifiers: &misplacedEffectSpecifiers, + allowNamedOpaqueResultType: true + ) // Parse a 'where' clause if present. let genericWhereClause: RawGenericWhereClauseSyntax? @@ -1309,7 +1332,10 @@ extension Parser { } let accessors: RawAccessorBlockSyntax? - if self.at(.leftBrace) || (inMemberDeclList && self.at(anyIn: AccessorDeclSyntax.AccessorSpecifierOptions.self) != nil && !self.at(.keyword(.`init`))) { + if self.at(.leftBrace) + || (inMemberDeclList && self.at(anyIn: AccessorDeclSyntax.AccessorSpecifierOptions.self) != nil + && !self.at(.keyword(.`init`))) + { accessors = self.parseAccessorBlock() } else { accessors = nil @@ -1399,7 +1425,9 @@ extension Parser { // 'set' and 'willSet' can have an optional name. This isn't valid in a // protocol, but we parse and then reject it for better QoI. let parameters: RawAccessorParametersSyntax? - if [AccessorDeclSyntax.AccessorSpecifierOptions.set, .willSet, .didSet, .`init`].contains(introducer.kind), let lparen = self.consume(if: .leftParen) { + if [AccessorDeclSyntax.AccessorSpecifierOptions.set, .willSet, .didSet, .`init`].contains(introducer.kind), + let lparen = self.consume(if: .leftParen) + { let (unexpectedBeforeName, name) = self.expectIdentifier() let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) parameters = RawAccessorParametersSyntax( @@ -1558,7 +1586,10 @@ extension Parser { } /// Parse an operator declaration. - mutating func parseOperatorDeclIntroducer(_ attrs: DeclAttributes, _ handle: RecoveryConsumptionHandle) -> OperatorDeclIntroducer { + mutating func parseOperatorDeclIntroducer( + _ attrs: DeclAttributes, + _ handle: RecoveryConsumptionHandle + ) -> OperatorDeclIntroducer { func isFixity(_ modifier: RawDeclModifierSyntax) -> Bool { switch modifier.name { case .keyword(.prefix), @@ -1605,7 +1636,11 @@ extension Parser { var (unexpectedBeforeOperatorKeyword, operatorKeyword) = self.expect(.keyword(.operator)) - unexpectedBeforeOperatorKeyword = RawUnexpectedNodesSyntax(combining: unexpectedAfterFixity, unexpectedBeforeOperatorKeyword, arena: self.arena) + unexpectedBeforeOperatorKeyword = RawUnexpectedNodesSyntax( + combining: unexpectedAfterFixity, + unexpectedBeforeOperatorKeyword, + arena: self.arena + ) return OperatorDeclIntroducer( unexpectedBeforeFixity: unexpectedBeforeFixity, @@ -1627,7 +1662,10 @@ extension Parser { case (_, let handle)?: (unexpectedBeforeName, name) = self.eat(handle) default: - if let identifier = self.consume(if: TokenSpec(.identifier, allowAtStartOfLine: false), TokenSpec(.dollarIdentifier, allowAtStartOfLine: false)) { + if let identifier = self.consume( + if: TokenSpec(.identifier, allowAtStartOfLine: false), + TokenSpec(.dollarIdentifier, allowAtStartOfLine: false) + ) { // Recover if the developer tried to use an identifier as the operator name unexpectedBeforeName = RawUnexpectedNodesSyntax([identifier], arena: self.arena) } else { @@ -1775,9 +1813,18 @@ extension Parser { case (.associativity, let handle)?: let associativity = self.eat(handle) let (unexpectedBeforeColon, colon) = self.expect(.colon) - var (unexpectedBeforeValue, value) = self.expect(.keyword(.left), .keyword(.right), .keyword(.none), default: .keyword(.none)) + var (unexpectedBeforeValue, value) = self.expect( + .keyword(.left), + .keyword(.right), + .keyword(.none), + default: .keyword(.none) + ) if value.isMissing, let identifier = self.consume(if: .identifier) { - unexpectedBeforeValue = RawUnexpectedNodesSyntax(combining: unexpectedBeforeValue, identifier, arena: self.arena) + unexpectedBeforeValue = RawUnexpectedNodesSyntax( + combining: unexpectedBeforeValue, + identifier, + arena: self.arena + ) } elements.append( .precedenceGroupAssociativity( @@ -1794,9 +1841,14 @@ extension Parser { case (.assignment, let handle)?: let assignmentKeyword = self.eat(handle) let (unexpectedBeforeColon, colon) = self.expect(.colon) - let (unexpectedBeforeValue, value) = self.expect(anyIn: PrecedenceGroupAssignmentSyntax.ValueOptions.self, default: .true) + let (unexpectedBeforeValue, value) = self.expect( + anyIn: PrecedenceGroupAssignmentSyntax.ValueOptions.self, + default: .true + ) let unexpectedAfterFlag: RawUnexpectedNodesSyntax? - if value.isMissing, let unexpectedIdentifier = self.consume(if: TokenSpec(.identifier, allowAtStartOfLine: false)) { + if value.isMissing, + let unexpectedIdentifier = self.consume(if: TokenSpec(.identifier, allowAtStartOfLine: false)) + { unexpectedAfterFlag = RawUnexpectedNodesSyntax([unexpectedIdentifier], arena: self.arena) } else { unexpectedAfterFlag = nil diff --git a/Sources/SwiftParser/Directives.swift b/Sources/SwiftParser/Directives.swift index 8e989a88c8c..381c8260a4a 100644 --- a/Sources/SwiftParser/Directives.swift +++ b/Sources/SwiftParser/Directives.swift @@ -54,7 +54,8 @@ extension Parser { /// into a syntax collection. mutating func parsePoundIfDirective( _ parseElement: (_ parser: inout Parser, _ isFirstElement: Bool) -> Element?, - addSemicolonIfNeeded: (_ lastElement: Element, _ newItemAtStartOfLine: Bool, _ parser: inout Parser) -> Element? = { _, _, _ in nil }, + addSemicolonIfNeeded: + (_ lastElement: Element, _ newItemAtStartOfLine: Bool, _ parser: inout Parser) -> Element? = { _, _, _ in nil }, syntax: (inout Parser, [Element]) -> RawIfConfigClauseSyntax.Elements? ) -> RawIfConfigDeclSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { @@ -86,7 +87,9 @@ extension Parser { // Proceed to parse #if continuation clauses (#elseif, #else, check #elif typo, #endif) var loopProgress = LoopProgressCondition() - LOOP: while let (match, handle) = self.canRecoverTo(anyIn: IfConfigContinuationClauseStartKeyword.self), self.hasProgressed(&loopProgress) { + LOOP: while let (match, handle) = self.canRecoverTo(anyIn: IfConfigContinuationClauseStartKeyword.self), + self.hasProgressed(&loopProgress) + { var unexpectedBeforePound: RawUnexpectedNodesSyntax? var pound: RawTokenSyntax let condition: RawExprSyntax? @@ -100,7 +103,12 @@ extension Parser { case .poundElse: (unexpectedBeforePound, pound) = self.eat(handle) if let ifToken = self.consume(if: .init(.if, allowAtStartOfLine: false)) { - unexpectedBeforePound = RawUnexpectedNodesSyntax(combining: unexpectedBeforePound, pound, ifToken, arena: self.arena) + unexpectedBeforePound = RawUnexpectedNodesSyntax( + combining: unexpectedBeforePound, + pound, + ifToken, + arena: self.arena + ) pound = self.missingToken(.poundElseif) condition = RawExprSyntax(self.parseSequenceExpression(flavor: .poundIfDirective)) } else { @@ -113,7 +121,12 @@ extension Parser { guard let elif = self.consume(if: TokenSpec(.identifier, allowAtStartOfLine: false)) else { preconditionFailure("The current token should be an identifier, guaranteed by the `atElifTypo` check.") } - unexpectedBeforePound = RawUnexpectedNodesSyntax(combining: unexpectedBeforePound, pound, elif, arena: self.arena) + unexpectedBeforePound = RawUnexpectedNodesSyntax( + combining: unexpectedBeforePound, + pound, + elif, + arena: self.arena + ) pound = self.missingToken(.poundElseif) condition = RawExprSyntax(self.parseSequenceExpression(flavor: .poundIfDirective)) unexpectedBetweenConditionAndElements = self.consumeRemainingTokenOnLine() @@ -128,7 +141,10 @@ extension Parser { poundKeyword: pound, condition: condition, unexpectedBetweenConditionAndElements, - elements: syntax(&self, parseIfConfigClauseElements(parseElement, addSemicolonIfNeeded: addSemicolonIfNeeded)), + elements: syntax( + &self, + parseIfConfigClauseElements(parseElement, addSemicolonIfNeeded: addSemicolonIfNeeded) + ), arena: self.arena ) ) @@ -178,7 +194,9 @@ extension Parser { guard let element = parseElement(&self, elements.isEmpty), !element.isEmpty else { break } - if let lastElement = elements.last, let fixedUpLastItem = addSemicolonIfNeeded(lastElement, newItemAtStartOfLine, &self) { + if let lastElement = elements.last, + let fixedUpLastItem = addSemicolonIfNeeded(lastElement, newItemAtStartOfLine, &self) + { elements[elements.count - 1] = fixedUpLastItem } elements.append(element) diff --git a/Sources/SwiftParser/Expressions.swift b/Sources/SwiftParser/Expressions.swift index c8e97fb7a73..6e01c41ff07 100644 --- a/Sources/SwiftParser/Expressions.swift +++ b/Sources/SwiftParser/Expressions.swift @@ -124,7 +124,8 @@ extension Parser { // expressions followed by (e.g.) let/var decls. if pattern != .none { switch self.at(anyIn: MatchingPatternStart.self) { - case (spec: .rhs(let bindingIntroducer), handle: _)? where self.withLookahead { $0.shouldParsePatternBinding(introducer: bindingIntroducer) }: + case (spec: .rhs(let bindingIntroducer), handle: _)? + where self.withLookahead { $0.shouldParsePatternBinding(introducer: bindingIntroducer) }: fallthrough case (spec: .lhs(_), handle: _)?: let pattern = self.parseMatchingPattern(context: .matching) @@ -747,7 +748,8 @@ extension Parser { // If we can parse trailing closures, do so. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax - if case .basic = flavor, self.at(.leftBrace), self.withLookahead({ $0.atValidTrailingClosure(flavor: flavor) }) { + if case .basic = flavor, self.at(.leftBrace), self.withLookahead({ $0.atValidTrailingClosure(flavor: flavor) }) + { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor: flavor) } else { trailingClosure = nil @@ -783,7 +785,8 @@ extension Parser { // If we can parse trailing closures, do so. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax - if case .basic = flavor, self.at(.leftBrace), self.withLookahead({ $0.atValidTrailingClosure(flavor: flavor) }) { + if case .basic = flavor, self.at(.leftBrace), self.withLookahead({ $0.atValidTrailingClosure(flavor: flavor) }) + { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor: flavor) } else { trailingClosure = nil @@ -806,7 +809,9 @@ extension Parser { } // Check for a trailing closure, if allowed. - if self.at(.leftBrace) && !leadingExpr.raw.kind.isLiteral && self.withLookahead({ $0.atValidTrailingClosure(flavor: flavor) }) { + if self.at(.leftBrace) && !leadingExpr.raw.kind.isLiteral + && self.withLookahead({ $0.atValidTrailingClosure(flavor: flavor) }) + { // Add dummy blank argument list to the call expression syntax. let list = RawLabeledExprListSyntax(elements: [], arena: self.arena) let (first, rest) = self.parseTrailingClosures(flavor: flavor) @@ -1132,7 +1137,8 @@ extension Parser { arena: self.arena ) ) - case (.identifier, let handle)?, (.self, let handle)?, (.`init`, let handle)?, (.`deinit`, let handle)?, (.`subscript`, let handle)?: + case (.identifier, let handle)?, (.self, let handle)?, (.`init`, let handle)?, (.`deinit`, let handle)?, + (.`subscript`, let handle)?: // If we have "case let x" followed by ".", "(", "[", or a generic // argument list, we parse x as a normal name, not a binding, because it // is the start of an enum or expr pattern. @@ -1186,7 +1192,9 @@ extension Parser { // developer almost certainly meant to use "0.4". Diagnose this, and // recover as if they wrote that. if let integerLiteral = self.consume(if: .integerLiteral) { - let text = arena.intern("0" + String(syntaxText: period.tokenText) + String(syntaxText: integerLiteral.tokenText)) + let text = arena.intern( + "0" + String(syntaxText: period.tokenText) + String(syntaxText: integerLiteral.tokenText) + ) return RawExprSyntax( RawFloatLiteralExprSyntax( literal: RawTokenSyntax( @@ -1377,7 +1385,10 @@ extension Parser { let closingSlash = self.expectWithoutRecoveryOrLeadingTrivia(.regexSlash) // Finally, parse a closing set of pounds. - let (unexpectedBeforeClosePounds, closingPounds) = parsePoundDelimiter(.regexPoundDelimiter, matching: openingPounds) + let (unexpectedBeforeClosePounds, closingPounds) = parsePoundDelimiter( + .regexPoundDelimiter, + matching: openingPounds + ) return RawRegexLiteralExprSyntax( openingPounds: openingPounds, @@ -1424,7 +1435,12 @@ extension Parser { extension Parser { enum CollectionKind { - case dictionary(key: RawExprSyntax, unexpectedBeforeColon: RawUnexpectedNodesSyntax?, colon: RawTokenSyntax, value: RawExprSyntax) + case dictionary( + key: RawExprSyntax, + unexpectedBeforeColon: RawUnexpectedNodesSyntax?, + colon: RawTokenSyntax, + value: RawExprSyntax + ) case array(RawExprSyntax) } @@ -1509,8 +1525,8 @@ extension Parser { // Parse the ',' if exists. if let token = self.consume(if: .comma) { keepGoing = token - } else if !self.at(.rightSquare, .endOfFile) && !self.atStartOfLine && !elementIsMissingExpression && !self.atStartOfDeclaration() - && !self.atStartOfStatement(preferExpr: false) + } else if !self.at(.rightSquare, .endOfFile) && !self.atStartOfLine && !elementIsMissingExpression + && !self.atStartOfDeclaration() && !self.atStartOfStatement(preferExpr: false) { keepGoing = missingToken(.comma) } else { @@ -1683,7 +1699,11 @@ extension Parser { let expression: RawExprSyntax if self.peek(isAt: .equal) { // The name is a new declaration. - (unexpectedBeforeName, name) = self.expect(.identifier, TokenSpec(.self, remapping: .identifier), default: .identifier) + (unexpectedBeforeName, name) = self.expect( + .identifier, + TokenSpec(.self, remapping: .identifier), + default: .identifier + ) (unexpectedBeforeEqual, equal) = self.expect(.equal) expression = self.parseExpression(flavor: .basic, pattern: .none) } else { @@ -1775,7 +1795,10 @@ extension Parser { effectSpecifiers = self.parseTypeEffectSpecifiers() if self.at(.arrow) { - returnClause = self.parseFunctionReturnClause(effectSpecifiers: &effectSpecifiers, allowNamedOpaqueResultType: false) + returnClause = self.parseFunctionReturnClause( + effectSpecifiers: &effectSpecifiers, + allowNamedOpaqueResultType: false + ) } } @@ -1837,7 +1860,10 @@ extension Parser { /// /// This is currently the same as parsing a tuple expression. In the future, /// this will be a dedicated argument list type. - mutating func parseArgumentListElements(pattern: PatternContext, flavor: ExprFlavor = .basic) -> [RawLabeledExprSyntax] { + mutating func parseArgumentListElements( + pattern: PatternContext, + flavor: ExprFlavor = .basic + ) -> [RawLabeledExprSyntax] { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return [ RawLabeledExprSyntax( @@ -1902,7 +1928,9 @@ extension Parser { extension Parser { /// Parse the trailing closure(s) following a call expression. - mutating func parseTrailingClosures(flavor: ExprFlavor) -> (RawClosureExprSyntax, RawMultipleTrailingClosureElementListSyntax) { + mutating func parseTrailingClosures( + flavor: ExprFlavor + ) -> (RawClosureExprSyntax, RawMultipleTrailingClosureElementListSyntax) { // Parse the closure. let closure = self.parseClosureExpression() @@ -2244,7 +2272,8 @@ extension Parser { mutating func parseSwitchCaseBody() -> RawCodeBlockItemListSyntax { parseCodeBlockItemList(until: { - $0.at(.rightBrace) || $0.at(.poundEndif, .poundElseif, .poundElse) || $0.withLookahead({ $0.atStartOfConditionalSwitchCases() }) + $0.at(.rightBrace) || $0.at(.poundEndif, .poundElseif, .poundElse) + || $0.withLookahead({ $0.atStartOfConditionalSwitchCases() }) }) } @@ -2257,7 +2286,9 @@ extension Parser { unknownAttr = RawAttributeSyntax( atSign: at, unexpectedBeforeIdent, - attributeName: RawTypeSyntax(RawIdentifierTypeSyntax(name: ident, genericArgumentClause: nil, arena: self.arena)), + attributeName: RawTypeSyntax( + RawIdentifierTypeSyntax(name: ident, genericArgumentClause: nil, arena: self.arena) + ), leftParen: nil, arguments: nil, rightParen: nil, @@ -2280,7 +2311,9 @@ extension Parser { caseItems: RawSwitchCaseItemListSyntax( elements: [ RawSwitchCaseItemSyntax( - pattern: RawPatternSyntax(RawIdentifierPatternSyntax(identifier: missingToken(.identifier), arena: self.arena)), + pattern: RawPatternSyntax( + RawIdentifierPatternSyntax(identifier: missingToken(.identifier), arena: self.arena) + ), whereClause: nil, trailingComma: nil, arena: self.arena @@ -2411,7 +2444,9 @@ extension Parser.Lookahead { if lookahead.at(.leftParen) { // Consume the '('. // While we don't have '->' or ')', eat balanced tokens. var skipProgress = LoopProgressCondition() - while !lookahead.at(.endOfFile, .rightBrace, .keyword(.in)) && !lookahead.at(.arrow) && lookahead.hasProgressed(&skipProgress) { + while !lookahead.at(.endOfFile, .rightBrace, .keyword(.in)) && !lookahead.at(.arrow) + && lookahead.hasProgressed(&skipProgress) + { lookahead.skipSingle() } } else if lookahead.at(.identifier) || lookahead.at(.wildcard) { @@ -2429,7 +2464,9 @@ extension Parser.Lookahead { } var parametersProgress = LoopProgressCondition() - while consumeOptionalTypeAnnotation() && lookahead.consume(if: .comma) != nil && lookahead.hasProgressed(¶metersProgress) { + while consumeOptionalTypeAnnotation() && lookahead.consume(if: .comma) != nil + && lookahead.hasProgressed(¶metersProgress) + { if lookahead.at(.identifier) || lookahead.at(.wildcard) { lookahead.consumeAnyToken() continue @@ -2499,7 +2536,8 @@ extension Parser.Lookahead { extension SyntaxKind { fileprivate var isLiteral: Bool { switch self { - case .arrayExpr, .booleanLiteralExpr, .dictionaryExpr, .floatLiteralExpr, .integerLiteralExpr, .nilLiteralExpr, .regexLiteralExpr, .stringLiteralExpr: + case .arrayExpr, .booleanLiteralExpr, .dictionaryExpr, .floatLiteralExpr, .integerLiteralExpr, .nilLiteralExpr, + .regexLiteralExpr, .stringLiteralExpr: return true default: return false diff --git a/Sources/SwiftParser/IncrementalParseTransition.swift b/Sources/SwiftParser/IncrementalParseTransition.swift index 43520f921e0..10ad4bdf159 100644 --- a/Sources/SwiftParser/IncrementalParseTransition.swift +++ b/Sources/SwiftParser/IncrementalParseTransition.swift @@ -166,7 +166,9 @@ struct IncrementalParseLookup { return true } - guard let nodeAffectRangeLength = transition.previousIncrementalParseResult.lookaheadRanges.lookaheadRanges[node.raw.id] else { + guard + let nodeAffectRangeLength = transition.previousIncrementalParseResult.lookaheadRanges.lookaheadRanges[node.raw.id] + else { return false } @@ -325,7 +327,9 @@ public struct ConcurrentEdits: Sendable { do { try self.init(concurrent: Self.translateSequentialEditsToConcurrentEdits(sequentialEdits)) } catch { - fatalError("ConcurrentEdits created by translateSequentialEditsToConcurrentEdits do not satisfy ConcurrentEdits requirements") + fatalError( + "ConcurrentEdits created by translateSequentialEditsToConcurrentEdits do not satisfy ConcurrentEdits requirements" + ) } } diff --git a/Sources/SwiftParser/Lexer/Cursor.swift b/Sources/SwiftParser/Lexer/Cursor.swift index 079ec87042e..302447b00d7 100644 --- a/Sources/SwiftParser/Lexer/Cursor.swift +++ b/Sources/SwiftParser/Lexer/Cursor.swift @@ -187,7 +187,12 @@ extension Lexer.Cursor { } topState = newState case .pushRegexLexemes(let index, let lexemes): - perform(stateTransition: .push(newState: .inRegexLiteral(index: index, lexemes: lexemes.allocate(in: stateAllocator))), stateAllocator: stateAllocator) + perform( + stateTransition: .push( + newState: .inRegexLiteral(index: index, lexemes: lexemes.allocate(in: stateAllocator)) + ), + stateAllocator: stateAllocator + ) case .replace(newState: let newState): topState = newState case .pop: @@ -451,7 +456,11 @@ extension Lexer.Cursor { case .inStringInterpolationStart(stringLiteralKind: let stringLiteralKind): result = lexInStringInterpolationStart(stringLiteralKind: stringLiteralKind) case .inStringInterpolation(stringLiteralKind: let stringLiteralKind, parenCount: let parenCount): - result = lexInStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount, sourceBufferStart: sourceBufferStart) + result = lexInStringInterpolation( + stringLiteralKind: stringLiteralKind, + parenCount: parenCount, + sourceBufferStart: sourceBufferStart + ) case .inRegexLiteral(let index, let lexemes): result = lexInRegexLiteral(lexemes.pointee[index...], existingPtr: lexemes) } @@ -569,7 +578,12 @@ extension Lexer.Cursor { /// Returns `true` if we are not at the end of the file and the character at /// offset `offset` is `character1`, `character2`, or `character3`. - func `is`(offset: Int = 0, at character1: CharacterByte, _ character2: CharacterByte, _ character3: CharacterByte) -> Bool { + func `is`( + offset: Int = 0, + at character1: CharacterByte, + _ character2: CharacterByte, + _ character3: CharacterByte + ) -> Bool { guard let peeked = self.peek(at: offset) else { return false } @@ -598,7 +612,12 @@ extension Lexer.Cursor { /// Returns `true` if we are not at the end of the file and the character at /// offset `offset` is neither `character1` nor `character2` nor `character3`. - func `is`(offset: Int = 0, notAt character1: CharacterByte, _ character2: CharacterByte, _ character3: CharacterByte) -> Bool { + func `is`( + offset: Int = 0, + notAt character1: CharacterByte, + _ character2: CharacterByte, + _ character3: CharacterByte + ) -> Bool { guard let peeked = self.peek(at: offset) else { return false } @@ -928,7 +947,10 @@ extension Lexer.Cursor { } // Try lex a raw string literal. if let delimiterLength = self.advanceIfOpeningRawStringDelimiter() { - return Lexer.Result(.rawStringPoundDelimiter, stateTransition: .push(newState: .afterRawStringDelimiter(delimiterLength: delimiterLength))) + return Lexer.Result( + .rawStringPoundDelimiter, + stateTransition: .push(newState: .afterRawStringDelimiter(delimiterLength: delimiterLength)) + ) } // Try lex a regex literal. @@ -1048,7 +1070,10 @@ extension Lexer.Cursor { return Lexer.Result(.rawStringPoundDelimiter) case "(": _ = self.advance() - return Lexer.Result(.leftParen, stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: 0))) + return Lexer.Result( + .leftParen, + stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: 0)) + ) case nil: return Lexer.Result(.endOfFile) default: @@ -1056,14 +1081,20 @@ extension Lexer.Cursor { } } - private mutating func lexInStringInterpolation(stringLiteralKind: StringLiteralKind, parenCount: Int, sourceBufferStart: Lexer.Cursor) -> Lexer.Result { + private mutating func lexInStringInterpolation( + stringLiteralKind: StringLiteralKind, + parenCount: Int, + sourceBufferStart: Lexer.Cursor + ) -> Lexer.Result { // Keep track of open parentheses switch self.peek() { case "(": _ = self.advance() return Lexer.Result( .leftParen, - stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount + 1)) + stateTransition: .replace( + newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount + 1) + ) ) case ")": _ = self.advance() @@ -1072,7 +1103,9 @@ extension Lexer.Cursor { } else { return Lexer.Result( .rightParen, - stateTransition: .replace(newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount - 1)) + stateTransition: .replace( + newState: .inStringInterpolation(stringLiteralKind: stringLiteralKind, parenCount: parenCount - 1) + ) ) } case "\r", "\n": @@ -1407,7 +1440,10 @@ extension Lexer.Cursor { if Unicode.Scalar(peeked).isValidIdentifierContinuationCodePoint { let errorPos = self self.advance(while: { $0.isValidIdentifierContinuationCodePoint }) - return Lexer.Result(.integerLiteral, error: LexingDiagnostic(.invalidHexDigitInIntegerLiteral, position: errorPos)) + return Lexer.Result( + .integerLiteral, + error: LexingDiagnostic(.invalidHexDigitInIntegerLiteral, position: errorPos) + ) } else { return Lexer.Result(.integerLiteral, error: LexingDiagnostic(.expectedHexDigitInHexLiteral, position: self)) } @@ -1469,7 +1505,9 @@ extension Lexer.Cursor { } if let peeked = self.peek(), !Unicode.Scalar(peeked).isDigit { - if let cursorToDot = cursorToDot, let peeked = cursorToDot.peek(at: 1), !Unicode.Scalar(peeked).isDigit && !signedExponent { + if let cursorToDot = cursorToDot, let peeked = cursorToDot.peek(at: 1), + !Unicode.Scalar(peeked).isDigit && !signedExponent + { // e.g: 0xff.fpValue, 0xff.fp self = cursorToDot return Lexer.Result(.integerLiteral) @@ -1569,7 +1607,10 @@ extension Lexer.Cursor { /// Lexes a single character in a string literal, handling escape sequences /// like `\n` or `\u{1234}` as a single character. - mutating func lexCharacterInStringLiteral(stringLiteralKind: StringLiteralKind, delimiterLength: Int) -> CharacterLex { + mutating func lexCharacterInStringLiteral( + stringLiteralKind: StringLiteralKind, + delimiterLength: Int + ) -> CharacterLex { switch self.peek() { case #"""#: let quote = Unicode.Scalar(self.advance()!) @@ -1791,7 +1832,10 @@ extension Lexer.Cursor { while isSingleLineString.is(notAt: "\r", "\n") { if isSingleLineString.advance(if: { $0 == #"""# }) { if isSingleLineString.advanceIfStringDelimiter(delimiterLength: leadingDelimiterLength) { - return Lexer.Result(.stringQuote, stateTransition: stateTransitionAfterLexingStringQuote(kind: .singleLine)) + return Lexer.Result( + .stringQuote, + stateTransition: stateTransitionAfterLexingStringQuote(kind: .singleLine) + ) } continue } @@ -1895,7 +1939,10 @@ extension Lexer.Cursor { // Eat another character in the segment var clone = self - let charValue = clone.lexCharacterInStringLiteral(stringLiteralKind: stringLiteralKind, delimiterLength: delimiterLength) + let charValue = clone.lexCharacterInStringLiteral( + stringLiteralKind: stringLiteralKind, + delimiterLength: delimiterLength + ) switch charValue { case .success: self = clone @@ -2272,7 +2319,10 @@ extension Lexer.Cursor { /// valid operator start, advance the cursor by what can be considered a /// lexeme. mutating func lexUnknown() -> UnknownCharactersClassification { - precondition(!(self.peekScalar()?.isValidIdentifierStartCodePoint ?? false) && !(self.peekScalar()?.isOperatorStartCodePoint ?? false)) + precondition( + !(self.peekScalar()?.isValidIdentifierStartCodePoint ?? false) + && !(self.peekScalar()?.isOperatorStartCodePoint ?? false) + ) let start = self var tmp = self if tmp.advance(if: { $0.isValidIdentifierContinuationCodePoint }) { @@ -2280,7 +2330,9 @@ extension Lexer.Cursor { // start, attempt to recover by eating more continuation characters. tmp.advance(while: { $0.isValidIdentifierContinuationCodePoint }) self = tmp - return .lexemeContents(Lexer.Result(.identifier, error: LexingDiagnostic(.invalidIdentifierStartCharacter, position: start))) + return .lexemeContents( + Lexer.Result(.identifier, error: LexingDiagnostic(.invalidIdentifierStartCharacter, position: start)) + ) } // This character isn't allowed in Swift source. diff --git a/Sources/SwiftParser/Lexer/LexemeSequence.swift b/Sources/SwiftParser/Lexer/LexemeSequence.swift index 3df628e5848..1d5b9eb2a2c 100644 --- a/Sources/SwiftParser/Lexer/LexemeSequence.swift +++ b/Sources/SwiftParser/Lexer/LexemeSequence.swift @@ -44,10 +44,17 @@ extension Lexer { /// - ``LookaheadTracker`` is not a class to avoid reference counting it. The ``Parser`` that creates the ``LexemeSequence`` will always outlive any ``Lookahead`` created for it. let lookaheadTracker: UnsafeMutablePointer - fileprivate init(sourceBufferStart: Lexer.Cursor, cursor: Lexer.Cursor, lookaheadTracker: UnsafeMutablePointer) { + fileprivate init( + sourceBufferStart: Lexer.Cursor, + cursor: Lexer.Cursor, + lookaheadTracker: UnsafeMutablePointer + ) { self.sourceBufferStart = sourceBufferStart self.cursor = cursor - self.nextToken = self.cursor.nextToken(sourceBufferStart: self.sourceBufferStart, stateAllocator: lexerStateAllocator) + self.nextToken = self.cursor.nextToken( + sourceBufferStart: self.sourceBufferStart, + stateAllocator: lexerStateAllocator + ) self.lookaheadTracker = lookaheadTracker } @@ -63,7 +70,10 @@ extension Lexer { mutating func advance() -> Lexer.Lexeme { defer { - self.nextToken = self.cursor.nextToken(sourceBufferStart: self.sourceBufferStart, stateAllocator: lexerStateAllocator) + self.nextToken = self.cursor.nextToken( + sourceBufferStart: self.sourceBufferStart, + stateAllocator: lexerStateAllocator + ) } self.recordNextTokenInLookaheadTracker() return self.nextToken @@ -81,7 +91,10 @@ extension Lexer { self.cursor = currentToken.cursor self.cursor.position = self.cursor.position.advanced(by: offset) - self.nextToken = self.cursor.nextToken(sourceBufferStart: self.sourceBufferStart, stateAllocator: lexerStateAllocator) + self.nextToken = self.cursor.nextToken( + sourceBufferStart: self.sourceBufferStart, + stateAllocator: lexerStateAllocator + ) currentToken = self.advance() } @@ -94,7 +107,10 @@ extension Lexer { for _ in 0.. 100 { return remainingText.prefix(100) + "..." } else { diff --git a/Sources/SwiftParser/Lexer/RegexLiteralLexer.swift b/Sources/SwiftParser/Lexer/RegexLiteralLexer.swift index 2a632193c87..b97bc09b5f7 100644 --- a/Sources/SwiftParser/Lexer/RegexLiteralLexer.swift +++ b/Sources/SwiftParser/Lexer/RegexLiteralLexer.swift @@ -656,7 +656,8 @@ extension Lexer.Cursor { return true // Bits of string/regex grammar, we can't start lexing a regex literal here. - case .regexPoundDelimiter, .regexSlash, .regexLiteralPattern, .rawStringPoundDelimiter, .stringQuote, .stringSegment, .multilineStringQuote, .singleQuote: + case .regexPoundDelimiter, .regexSlash, .regexLiteralPattern, .rawStringPoundDelimiter, .stringQuote, + .stringSegment, .multilineStringQuote, .singleQuote: return false // Allow unknown for better recovery. diff --git a/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift b/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift index 7fdae7ad9b2..53d3424e425 100644 --- a/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift +++ b/Sources/SwiftParser/Lexer/UnicodeScalarExtensions.swift @@ -84,7 +84,9 @@ extension Unicode.Scalar { // N1518: Recommendations for extended identifier characters for C and C++ // Proposed Annex X.2: Ranges of characters disallowed initially let c = self.value - if ((c >= 0x0300 && c <= 0x036F) || (c >= 0x1DC0 && c <= 0x1DFF) || (c >= 0x20D0 && c <= 0x20FF) || (c >= 0xFE20 && c <= 0xFE2F)) { + if ((c >= 0x0300 && c <= 0x036F) || (c >= 0x1DC0 && c <= 0x1DFF) || (c >= 0x20D0 && c <= 0x20FF) + || (c >= 0xFE20 && c <= 0xFE2F)) + { return false } diff --git a/Sources/SwiftParser/Modifiers.swift b/Sources/SwiftParser/Modifiers.swift index 83585156452..da6a423e9b3 100644 --- a/Sources/SwiftParser/Modifiers.swift +++ b/Sources/SwiftParser/Modifiers.swift @@ -86,7 +86,8 @@ extension Parser { (.declarationModifier(._local), let handle)?, (.declarationModifier(.__setter_access), let handle)?, (.declarationModifier(.reasync), let handle)?, - (.declarationModifier(._resultDependsOnSelf), let handle)? where experimentalFeatures.contains(.nonescapableTypes): + (.declarationModifier(._resultDependsOnSelf), let handle)? + where experimentalFeatures.contains(.nonescapableTypes): let (unexpectedBeforeKeyword, keyword) = self.eat(handle) elements.append(RawDeclModifierSyntax(unexpectedBeforeKeyword, name: keyword, detail: nil, arena: self.arena)) case (.declarationModifier(.rethrows), _)?: @@ -95,14 +96,20 @@ extension Parser { break MODIFIER_LOOP } } - return elements.isEmpty ? self.emptyCollection(RawDeclModifierListSyntax.self) : RawDeclModifierListSyntax(elements: elements, arena: arena) + return elements.isEmpty + ? self.emptyCollection(RawDeclModifierListSyntax.self) + : RawDeclModifierListSyntax(elements: elements, arena: arena) } } extension Parser { mutating func parseModifierDetail() -> RawDeclModifierDetailSyntax { let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen) - let (unexpectedBeforeDetailToken, detailToken) = self.expect(.identifier, TokenSpec(.set, remapping: .identifier), default: .identifier) + let (unexpectedBeforeDetailToken, detailToken) = self.expect( + .identifier, + TokenSpec(.set, remapping: .identifier), + default: .identifier + ) let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) return RawDeclModifierDetailSyntax( unexpectedBeforeLeftParen, diff --git a/Sources/SwiftParser/Names.swift b/Sources/SwiftParser/Names.swift index 19f7050db5d..ddd6a175e75 100644 --- a/Sources/SwiftParser/Names.swift +++ b/Sources/SwiftParser/Names.swift @@ -66,7 +66,9 @@ extension Parser { mutating func parseDeclReferenceExpr(_ flags: DeclNameOptions = []) -> RawDeclReferenceExprSyntax { // Consume the base name. let base: RawTokenSyntax - if let identOrSelf = self.consume(if: .identifier, .keyword(.self), .keyword(.Self)) ?? self.consume(if: .keyword(.`init`)) { + if let identOrSelf = self.consume(if: .identifier, .keyword(.self), .keyword(.Self)) + ?? self.consume(if: .keyword(.`init`)) + { base = identOrSelf } else if flags.contains(.operators), let (_, _) = self.at(anyIn: Operator.self) { base = self.consumeAnyToken(remapping: .binaryOperator) @@ -216,7 +218,12 @@ extension Parser { var keepGoing = self.consume(if: .period) var loopProgress = LoopProgressCondition() while keepGoing != nil && self.hasProgressed(&loopProgress) { - let (unexpectedBeforeName, name) = self.expect(.identifier, .keyword(.self), TokenSpec(.Self, remapping: .identifier), default: .identifier) + let (unexpectedBeforeName, name) = self.expect( + .identifier, + .keyword(.self), + TokenSpec(.Self, remapping: .identifier), + default: .identifier + ) let generics: RawGenericArgumentClauseSyntax? if self.atContextualPunctuator("<") { generics = self.parseGenericArguments() diff --git a/Sources/SwiftParser/Nominals.swift b/Sources/SwiftParser/Nominals.swift index 142be14ba21..b48dffc946a 100644 --- a/Sources/SwiftParser/Nominals.swift +++ b/Sources/SwiftParser/Nominals.swift @@ -318,7 +318,10 @@ extension Parser { // If it is a Python style inheritance clause, then consume a right paren if there is one. if isPythonStyleInheritanceClause, let rightParen = self.consume(if: .rightParen) { - unexpectedAfterInheritedTypeCollection = RawUnexpectedNodesSyntax(elements: [RawSyntax(rightParen)], arena: self.arena) + unexpectedAfterInheritedTypeCollection = RawUnexpectedNodesSyntax( + elements: [RawSyntax(rightParen)], + arena: self.arena + ) } else { unexpectedAfterInheritedTypeCollection = nil } diff --git a/Sources/SwiftParser/Parameters.swift b/Sources/SwiftParser/Parameters.swift index e46147cf618..9d5b8cd1b81 100644 --- a/Sources/SwiftParser/Parameters.swift +++ b/Sources/SwiftParser/Parameters.swift @@ -204,7 +204,12 @@ extension Parser { type = self.parseType(misplacedSpecifiers: misplacedSpecifiers) } } else { - names = ParameterNames(unexpectedBeforeFirstName: nil, firstName: nil, unexpectedBeforeSecondName: nil, secondName: nil) + names = ParameterNames( + unexpectedBeforeFirstName: nil, + firstName: nil, + unexpectedBeforeSecondName: nil, + secondName: nil + ) unexpectedBeforeColon = nil colon = nil type = self.parseType(misplacedSpecifiers: misplacedSpecifiers) @@ -245,7 +250,9 @@ extension Parser { switch self.at(anyIn: ParameterModifier.self) { case (._const, let handle)?: elements.append(RawDeclModifierSyntax(name: self.eat(handle), detail: nil, arena: self.arena)) - case (.isolated, let handle)? where self.withLookahead({ !$0.startsParameterName(isClosure: isClosure, allowMisplacedSpecifierRecovery: false) }): + case (.isolated, let handle)? + where self.withLookahead({ !$0.startsParameterName(isClosure: isClosure, allowMisplacedSpecifierRecovery: false) } + ): elements.append(RawDeclModifierSyntax(name: self.eat(handle), detail: nil, arena: self.arena)) default: break MODIFIER_LOOP @@ -261,7 +268,9 @@ extension Parser { mutating func parseMisplacedSpecifiers() -> [RawTokenSyntax] { var misplacedSpecifiers: [RawTokenSyntax] = [] if self.withLookahead({ !$0.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: false) }) { - while canHaveParameterSpecifier, let specifier = self.consume(ifAnyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) { + while canHaveParameterSpecifier, + let specifier = self.consume(ifAnyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) + { misplacedSpecifiers.append(specifier) } } diff --git a/Sources/SwiftParser/ParseSourceFile.swift b/Sources/SwiftParser/ParseSourceFile.swift index c7074391587..7859d5c9f07 100644 --- a/Sources/SwiftParser/ParseSourceFile.swift +++ b/Sources/SwiftParser/ParseSourceFile.swift @@ -89,7 +89,11 @@ extension Parser { maximumNestingLevel: Int? = nil, parseTransition: IncrementalParseTransition? ) -> (tree: SourceFileSyntax, lookaheadRanges: LookaheadRanges) { - let parseResult = parseIncrementally(source: source, maximumNestingLevel: maximumNestingLevel, parseTransition: parseTransition) + let parseResult = parseIncrementally( + source: source, + maximumNestingLevel: maximumNestingLevel, + parseTransition: parseTransition + ) return (parseResult.tree, parseResult.lookaheadRanges) } diff --git a/Sources/SwiftParser/Parser.swift b/Sources/SwiftParser/Parser.swift index 6b060c0abbe..379e3d591f7 100644 --- a/Sources/SwiftParser/Parser.swift +++ b/Sources/SwiftParser/Parser.swift @@ -145,9 +145,14 @@ public struct Parser { /// /// These empty collections are only created once and the same node is returned /// on subsequent calls, reducing memory usage. - mutating func emptyCollection(_: RawMultipleTrailingClosureElementListSyntax.Type) -> RawMultipleTrailingClosureElementListSyntax { + mutating func emptyCollection( + _: RawMultipleTrailingClosureElementListSyntax.Type + ) -> RawMultipleTrailingClosureElementListSyntax { if _emptyRawMultipleTrailingClosureElementListSyntax == nil { - _emptyRawMultipleTrailingClosureElementListSyntax = RawMultipleTrailingClosureElementListSyntax(elements: [], arena: self.arena) + _emptyRawMultipleTrailingClosureElementListSyntax = RawMultipleTrailingClosureElementListSyntax( + elements: [], + arena: self.arena + ) } return _emptyRawMultipleTrailingClosureElementListSyntax! } @@ -680,7 +685,10 @@ extension Parser { return (nil, self.consumeAnyToken(remapping: .identifier)) } if allowSelfOrCapitalSelfAsIdentifier, - let selfOrCapitalSelf = self.consume(if: TokenSpec(.self, remapping: .identifier), TokenSpec(.Self, remapping: .identifier)) + let selfOrCapitalSelf = self.consume( + if: TokenSpec(.self, remapping: .identifier), + TokenSpec(.Self, remapping: .identifier) + ) { return (nil, selfOrCapitalSelf) } @@ -716,7 +724,10 @@ extension Parser { /// That way, if the developer forgot to to type `{`, we won't eat `}` that were most likely intended to close an outer scope. /// /// If `leftBrace` is present or `introducer` is `nil`, this is equivalent to `self.expect(.rightBrace)`. - mutating func expectRightBrace(leftBrace: RawTokenSyntax, introducer: RawTokenSyntax?) -> (unexpected: RawUnexpectedNodesSyntax?, token: RawTokenSyntax) { + mutating func expectRightBrace( + leftBrace: RawTokenSyntax, + introducer: RawTokenSyntax? + ) -> (unexpected: RawUnexpectedNodesSyntax?, token: RawTokenSyntax) { func indentation(_ pieces: [RawTriviaPiece]) -> RawTriviaPiece? { if pieces.last?.isNewline == true { return .spaces(0) @@ -835,8 +846,10 @@ extension Parser { ) -> (unexpected: RawUnexpectedNodesSyntax?, period: RawTokenSyntax, skipMemberName: Bool) { precondition(self.at(.period)) - let beforePeriodWhitespace = previousNode?.raw.trailingTriviaByteLength ?? 0 > 0 || self.currentToken.leadingTriviaByteLength > 0 - let afterPeriodWhitespace = self.currentToken.trailingTriviaByteLength > 0 || self.peek().leadingTriviaByteLength > 0 + let beforePeriodWhitespace = + previousNode?.raw.trailingTriviaByteLength ?? 0 > 0 || self.currentToken.leadingTriviaByteLength > 0 + let afterPeriodWhitespace = + self.currentToken.trailingTriviaByteLength > 0 || self.peek().leadingTriviaByteLength > 0 let afterContainsAnyNewline = self.peek().isAtStartOfLine let period = self.consumeAnyToken() diff --git a/Sources/SwiftParser/Patterns.swift b/Sources/SwiftParser/Patterns.swift index f1c3fb1bd8b..3d5850bec2b 100644 --- a/Sources/SwiftParser/Patterns.swift +++ b/Sources/SwiftParser/Patterns.swift @@ -67,7 +67,8 @@ extension Parser { arena: self.arena ) ) - case (.rhs(let introducer), let handle)? where self.withLookahead { $0.shouldParsePatternBinding(introducer: introducer) }: + case (.rhs(let introducer), let handle)? + where self.withLookahead { $0.shouldParsePatternBinding(introducer: introducer) }: let bindingSpecifier = self.eat(handle) let value = self.parsePattern() return RawPatternSyntax( @@ -116,7 +117,9 @@ extension Parser { } /// Parse a typed pattern. - mutating func parseTypedPattern(allowRecoveryFromMissingColon: Bool = true) -> (RawPatternSyntax, RawTypeAnnotationSyntax?) { + mutating func parseTypedPattern( + allowRecoveryFromMissingColon: Bool = true + ) -> (RawPatternSyntax, RawTypeAnnotationSyntax?) { let pattern = self.parsePattern() // Now parse an optional type annotation. @@ -176,7 +179,9 @@ extension Parser { /// If we have something like `x SomeType`, use the indication that `SomeType` starts with a capital letter (and is thus probably a type name) /// as an indication that the user forgot to write the colon instead of forgetting to write the comma to separate two elements. - if label == nil, colon == nil, self.at(.identifier), peek(isAt: .identifier), peek().tokenText.isStartingWithUppercase { + if label == nil, colon == nil, self.at(.identifier), peek(isAt: .identifier), + peek().tokenText.isStartingWithUppercase + { label = consume(if: .identifier) colon = self.missingToken(.colon) } @@ -220,7 +225,8 @@ extension Parser { arena: self.arena ) ) - case (.rhs(let introducer), let handle)? where self.withLookahead { $0.shouldParsePatternBinding(introducer: introducer) }: + case (.rhs(let introducer), let handle)? + where self.withLookahead { $0.shouldParsePatternBinding(introducer: introducer) }: let bindingSpecifier = self.eat(handle) let value = self.parseMatchingPattern(context: .bindingIntroducer) return RawPatternSyntax( diff --git a/Sources/SwiftParser/Recovery.swift b/Sources/SwiftParser/Recovery.swift index aeab4f7bde3..18071c4727f 100644 --- a/Sources/SwiftParser/Recovery.swift +++ b/Sources/SwiftParser/Recovery.swift @@ -90,7 +90,9 @@ extension Parser.Lookahead { let initialTokensConsumed = self.tokensConsumed let recoveryPrecedence = min(spec1.recoveryPrecedence, spec2.recoveryPrecedence, spec3.recoveryPrecedence) - let shouldSkipOverNewlines = recoveryPrecedence.shouldSkipOverNewlines && spec1.allowAtStartOfLine && spec2.allowAtStartOfLine && spec3.allowAtStartOfLine + let shouldSkipOverNewlines = + recoveryPrecedence.shouldSkipOverNewlines && spec1.allowAtStartOfLine && spec2.allowAtStartOfLine + && spec3.allowAtStartOfLine while !self.at(.endOfFile) { if !shouldSkipOverNewlines, self.atStartOfLine { diff --git a/Sources/SwiftParser/Specifiers.swift b/Sources/SwiftParser/Specifiers.swift index 87a24e91ce1..c240935a884 100644 --- a/Sources/SwiftParser/Specifiers.swift +++ b/Sources/SwiftParser/Specifiers.swift @@ -171,7 +171,11 @@ protocol RawMisplacedEffectSpecifiersTrait { arena: __shared SyntaxArena ) - func withMisplaced(async misplacedAsyncKeyword: RawTokenSyntax?, throws misplacedThrowsClause: RawThrowsClauseSyntax?, arena: __shared SyntaxArena) -> Self + func withMisplaced( + async misplacedAsyncKeyword: RawTokenSyntax?, + throws misplacedThrowsClause: RawThrowsClauseSyntax?, + arena: __shared SyntaxArena + ) -> Self } protocol RawEffectSpecifiersTrait: RawMisplacedEffectSpecifiersTrait { @@ -204,7 +208,11 @@ extension RawEffectSpecifiersTrait { ) } - func withMisplaced(async misplacedAsyncKeyword: RawTokenSyntax?, throws misplacedThrowsClause: RawThrowsClauseSyntax?, arena: __shared SyntaxArena) -> Self { + func withMisplaced( + async misplacedAsyncKeyword: RawTokenSyntax?, + throws misplacedThrowsClause: RawThrowsClauseSyntax?, + arena: __shared SyntaxArena + ) -> Self { return Self.init( self.unexpectedBeforeAsyncSpecifier, asyncSpecifier: self.asyncSpecifier ?? misplacedAsyncKeyword, @@ -550,9 +558,11 @@ extension RawDeinitializerEffectSpecifiersSyntax: RawMisplacedEffectSpecifiersTr ) } - func withMisplaced(async misplacedAsyncKeyword: RawTokenSyntax?, throws misplacedThrowsClause: RawThrowsClauseSyntax?, arena: SyntaxArena) - -> RawDeinitializerEffectSpecifiersSyntax - { + func withMisplaced( + async misplacedAsyncKeyword: RawTokenSyntax?, + throws misplacedThrowsClause: RawThrowsClauseSyntax?, + arena: SyntaxArena + ) -> RawDeinitializerEffectSpecifiersSyntax { // `throwsClause` should never be present because `parseMisplacedEffectSpecifiers()` only creates missing tokens // and `CorrectThrowsTokenKinds` is an empty `TokenSpecSet`. // @@ -640,7 +650,13 @@ extension Parser { if throwsClause == nil { // Let's synthesize a missing 'throws'. If we find a real throws specifier // later, we will replace the missing token by the present token. - throwsClause = RawThrowsClauseSyntax(throwsSpecifier: missingToken(.keyword(.throws)), leftParen: nil, type: nil, rightParen: nil, arena: self.arena) + throwsClause = RawThrowsClauseSyntax( + throwsSpecifier: missingToken(.keyword(.throws)), + leftParen: nil, + type: nil, + rightParen: nil, + arena: self.arena + ) } } else { break @@ -663,7 +679,10 @@ extension Parser { // Handle `async` after `throws` asyncKeyword = missingToken(.keyword(.async)) } - } else if let (_, handle, _) = self.at(anyIn: S.MisspelledThrowsTokenKinds.self, or: S.CorrectThrowsTokenKinds.self) { + } else if let (_, handle, _) = self.at( + anyIn: S.MisspelledThrowsTokenKinds.self, + or: S.CorrectThrowsTokenKinds.self + ) { let misspelledThrows = self.eat(handle) unexpectedAfterThrowsClause.append(RawSyntax(misspelledThrows)) } else { @@ -749,13 +768,18 @@ extension Parser { /// When a misplaced effect specifier is consumed and `effectSpecifiers` /// doesn't have an effect specifier of that kind, modify `effectSpecifiers` /// to have a missing specifier of that kind. - mutating func parseMisplacedEffectSpecifiers(_ effectSpecifiers: inout S?) -> RawUnexpectedNodesSyntax? { + mutating func parseMisplacedEffectSpecifiers( + _ effectSpecifiers: inout S? + ) -> RawUnexpectedNodesSyntax? { var synthesizedAsync: RawTokenSyntax? = nil var synthesizedThrows: RawTokenSyntax? = nil var unexpected: [RawTokenSyntax] = [] var loopProgress = LoopProgressCondition() while self.hasProgressed(&loopProgress) { - if let (spec, handle, matchedSubset) = self.at(anyIn: S.MisspelledAsyncTokenKinds.self, or: S.CorrectAsyncTokenKinds.self) { + if let (spec, handle, matchedSubset) = self.at( + anyIn: S.MisspelledAsyncTokenKinds.self, + or: S.CorrectAsyncTokenKinds.self + ) { let misspelledAsync = self.eat(handle) unexpected.append(misspelledAsync) if effectSpecifiers?.asyncSpecifier == nil { @@ -765,7 +789,10 @@ extension Parser { synthesizedAsync = missingToken(.async) } } - } else if let (spec, handle, matchedSubset) = self.at(anyIn: S.MisspelledThrowsTokenKinds.self, or: S.CorrectThrowsTokenKinds.self) { + } else if let (spec, handle, matchedSubset) = self.at( + anyIn: S.MisspelledThrowsTokenKinds.self, + or: S.CorrectThrowsTokenKinds.self + ) { let misspelledThrows = self.eat(handle) unexpected.append(misspelledThrows) if effectSpecifiers?.throwsClause == nil { @@ -785,7 +812,11 @@ extension Parser { } if let specifiers = effectSpecifiers { - effectSpecifiers = specifiers.withMisplaced(async: synthesizedAsync, throws: synthesizedThrowsClause, arena: self.arena) + effectSpecifiers = specifiers.withMisplaced( + async: synthesizedAsync, + throws: synthesizedThrowsClause, + arena: self.arena + ) } else { effectSpecifiers = S( asyncSpecifier: synthesizedAsync, diff --git a/Sources/SwiftParser/Statements.swift b/Sources/SwiftParser/Statements.swift index 3b10cf63c14..aa1e22d0e3f 100644 --- a/Sources/SwiftParser/Statements.swift +++ b/Sources/SwiftParser/Statements.swift @@ -162,11 +162,17 @@ extension Parser { var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { - let condition = self.parseConditionElement(lastBindingKind: elements.last?.condition.as(RawOptionalBindingConditionSyntax.self)?.bindingSpecifier) + let condition = self.parseConditionElement( + lastBindingKind: elements.last?.condition.as(RawOptionalBindingConditionSyntax.self)?.bindingSpecifier + ) var unexpectedBeforeKeepGoing: RawUnexpectedNodesSyntax? = nil keepGoing = self.consume(if: .comma) if keepGoing == nil, let token = self.consumeIfContextualPunctuator("&&") ?? self.consume(if: .keyword(.where)) { - unexpectedBeforeKeepGoing = RawUnexpectedNodesSyntax(combining: unexpectedBeforeKeepGoing, token, arena: self.arena) + unexpectedBeforeKeepGoing = RawUnexpectedNodesSyntax( + combining: unexpectedBeforeKeepGoing, + token, + arena: self.arena + ) keepGoing = missingToken(.comma) } elements.append( @@ -227,7 +233,11 @@ extension Parser { let letOrVar: RawTokenSyntax if self.at(.identifier), let lastBindingKind = lastBindingKind { - (unexpectedBeforeBindingKeyword, letOrVar) = self.expect(.keyword(.let), .keyword(.var), default: .keyword(Keyword(lastBindingKind.tokenText) ?? .let)) + (unexpectedBeforeBindingKeyword, letOrVar) = self.expect( + .keyword(.let), + .keyword(.var), + default: .keyword(Keyword(lastBindingKind.tokenText) ?? .let) + ) } else { letOrVar = self.consume(if: TokenSpec.keyword(.let), .keyword(.var)) ?? self.missingToken(.let) unexpectedBeforeBindingKeyword = nil @@ -303,7 +313,10 @@ extension Parser { let arguments = self.parseAvailabilitySpecList() let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) let unexpectedAfterRParen: RawUnexpectedNodesSyntax? - if let (equalOperator, falseKeyword) = self.consume(if: { $0.isContextualPunctuator("==") }, followedBy: { TokenSpec.keyword(.false) ~= $0 }) { + if let (equalOperator, falseKeyword) = self.consume( + if: { $0.isContextualPunctuator("==") }, + followedBy: { TokenSpec.keyword(.false) ~= $0 } + ) { unexpectedAfterRParen = RawUnexpectedNodesSyntax([equalOperator, falseKeyword], arena: self.arena) } else { unexpectedAfterRParen = nil @@ -873,7 +886,9 @@ extension Parser.Lookahead { /// - Note: This function must be kept in sync with `parseStatement()`. /// - Seealso: ``Parser/parseStatement()`` mutating func atStartOfStatement(allowRecovery: Bool = false, preferExpr: Bool) -> Bool { - if (self.at(anyIn: SwitchCaseStart.self) != nil || self.at(.atSign)) && withLookahead({ $0.atStartOfSwitchCaseItem() }) { + if (self.at(anyIn: SwitchCaseStart.self) != nil || self.at(.atSign)) + && withLookahead({ $0.atStartOfSwitchCaseItem() }) + { // We consider SwitchCaseItems statements so we don't parse the start of a new case item as trailing parts of an expression. return true } diff --git a/Sources/SwiftParser/StringLiterals.swift b/Sources/SwiftParser/StringLiterals.swift index 8b33cd59cb8..7533f5a87f3 100644 --- a/Sources/SwiftParser/StringLiterals.swift +++ b/Sources/SwiftParser/StringLiterals.swift @@ -149,7 +149,8 @@ extension Parser { kind: token.tokenKind, text: SyntaxText(rebasing: token.tokenText.dropFirst(reclassifyLeading.count).dropLast(reclassifyTrailing.count)), leadingTriviaPieces: token.leadingTriviaPieces + TriviaParser.parseTrivia(reclassifyLeading, position: .leading), - trailingTriviaPieces: TriviaParser.parseTrivia(reclassifyTrailing, position: .trailing) + token.trailingTriviaPieces, + trailingTriviaPieces: TriviaParser.parseTrivia(reclassifyTrailing, position: .trailing) + + token.trailingTriviaPieces, presence: token.presence, tokenDiagnostic: token.tokenView.tokenDiagnostic ?? tokenDiagnostic, arena: self.arena @@ -195,7 +196,11 @@ extension Parser { ) middleSegments[middleSegments.count - 1] = .stringSegment( RawStringSegmentSyntax( - RawUnexpectedNodesSyntax(combining: lastMiddleSegment.unexpectedBeforeContent, unexpectedBeforeContent, arena: self.arena), + RawUnexpectedNodesSyntax( + combining: lastMiddleSegment.unexpectedBeforeContent, + unexpectedBeforeContent, + arena: self.arena + ), content: content, lastMiddleSegment.unexpectedAfterContent, arena: self.arena @@ -239,7 +244,10 @@ extension Parser { isFirstSegmentOnNewLine: Bool, indentation: SyntaxText ) { - let expressionIndentationChecker = StringLiteralExpressionIndentationChecker(expectedIndentation: indentation, arena: self.arena) + let expressionIndentationChecker = StringLiteralExpressionIndentationChecker( + expectedIndentation: indentation, + arena: self.arena + ) var isSegmentOnNewLine = isFirstSegmentOnNewLine for (index, segment) in middleSegments.enumerated() { @@ -264,9 +272,15 @@ extension Parser { { // 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") })) + let actualIndentation = SyntaxText( + rebasing: segment.content.tokenText.prefix(while: { $0 == UInt8(ascii: " ") || $0 == UInt8(ascii: "\t") }) + ) let tokenDiagnostic = TokenDiagnostic(.insufficientIndentationInMultilineStringLiteral, byteOffset: 0) - let content = self.reclassifyTrivia(in: segment.content, leading: actualIndentation, tokenDiagnostic: tokenDiagnostic) + let content = self.reclassifyTrivia( + in: segment.content, + leading: actualIndentation, + tokenDiagnostic: tokenDiagnostic + ) segment = RawStringSegmentSyntax( segment.unexpectedBeforeContent, content: content, @@ -392,7 +406,9 @@ extension Parser { ) } else { if let lastSegment = lastSegment { - indentationTrivia = TriviaParser.parseTrivia(lastSegment.content.tokenText, position: .leading).prefix(while: { $0.isIndentationWhitespace }) + indentationTrivia = TriviaParser.parseTrivia(lastSegment.content.tokenText, position: .leading).prefix(while: { + $0.isIndentationWhitespace + }) let indentationByteLength = indentationTrivia.reduce(0, { $0 + $1.byteLength }) indentation = SyntaxText(rebasing: lastSegment.content.tokenText[0.. RawSimpleStringLiteralExprSyntax { let openDelimiter = self.consume(if: .rawStringPoundDelimiter) - let (unexpectedBeforeOpenQuote, openQuote) = self.expect(anyIn: SimpleStringLiteralExprSyntax.OpeningQuoteOptions.self, default: .stringQuote) + let (unexpectedBeforeOpenQuote, openQuote) = self.expect( + anyIn: SimpleStringLiteralExprSyntax.OpeningQuoteOptions.self, + default: .stringQuote + ) /// Parse segments. var segments: [RawStringSegmentSyntax] = [] diff --git a/Sources/SwiftParser/SyntaxUtils.swift b/Sources/SwiftParser/SyntaxUtils.swift index 5891956f1fe..5566dcd6d8b 100644 --- a/Sources/SwiftParser/SyntaxUtils.swift +++ b/Sources/SwiftParser/SyntaxUtils.swift @@ -73,7 +73,11 @@ extension RawTokenSyntax: UnexpectedNodesCombinable { extension RawUnexpectedNodesSyntax: UnexpectedNodesCombinable {} extension RawUnexpectedNodesSyntax { - init?(combining syntax1: some UnexpectedNodesCombinable, _ syntax2: some UnexpectedNodesCombinable, arena: __shared SyntaxArena) { + init?( + combining syntax1: some UnexpectedNodesCombinable, + _ syntax2: some UnexpectedNodesCombinable, + arena: __shared SyntaxArena + ) { self.init(syntax1.elements + syntax2.elements, arena: arena) } diff --git a/Sources/SwiftParser/TokenConsumer.swift b/Sources/SwiftParser/TokenConsumer.swift index 0f36e26c4a3..8954338478e 100644 --- a/Sources/SwiftParser/TokenConsumer.swift +++ b/Sources/SwiftParser/TokenConsumer.swift @@ -134,7 +134,9 @@ extension TokenConsumer { /// If this is the case, return the `Subset` case that the parser is positioned in /// as well as a handle to consume that token. @inline(__always) - mutating func at(anyIn specSet: SpecSet.Type) -> (spec: SpecSet, handle: TokenConsumptionHandle)? { + mutating func at( + anyIn specSet: SpecSet.Type + ) -> (spec: SpecSet, handle: TokenConsumptionHandle)? { #if SWIFTPARSER_ENABLE_ALTERNATE_TOKEN_INTROSPECTION if shouldRecordAlternativeTokenChoices { recordAlternativeTokenChoice(for: self.currentToken, choices: specSet.allCases.map(\.spec)) diff --git a/Sources/SwiftParser/TokenPrecedence.swift b/Sources/SwiftParser/TokenPrecedence.swift index 3e620a67b9f..a7e66423ba2 100644 --- a/Sources/SwiftParser/TokenPrecedence.swift +++ b/Sources/SwiftParser/TokenPrecedence.swift @@ -228,9 +228,11 @@ enum TokenPrecedence: Comparable { // Operator stuff .operator, .precedencegroup, // Declaration Modifiers - .__consuming, .final, .required, .optional, .lazy, .dynamic, .infix, .postfix, .prefix, .mutating, .nonmutating, .convenience, .override, .package, .open, + .__consuming, .final, .required, .optional, .lazy, .dynamic, .infix, .postfix, .prefix, .mutating, .nonmutating, + .convenience, .override, .package, .open, .__setter_access, .indirect, .isolated, .nonisolated, .distributed, ._local, - .inout, ._mutating, ._borrow, ._borrowing, .borrowing, ._consuming, .consuming, .consume, ._resultDependsOnSelf, ._resultDependsOn, + .inout, ._mutating, ._borrow, ._borrowing, .borrowing, ._consuming, .consuming, .consume, ._resultDependsOnSelf, + ._resultDependsOn, .transferring, ._consume, ._copy, ._mutate, // Accessors .get, .set, .didSet, .willSet, .unsafeAddress, .addressWithOwner, .addressWithNativeOwner, .unsafeMutableAddress, diff --git a/Sources/SwiftParser/TokenSpec.swift b/Sources/SwiftParser/TokenSpec.swift index ff5278f7b5b..04765fe8dee 100644 --- a/Sources/SwiftParser/TokenSpec.swift +++ b/Sources/SwiftParser/TokenSpec.swift @@ -86,7 +86,10 @@ public struct TokenSpec { recoveryPrecedence: TokenPrecedence? = nil, allowAtStartOfLine: Bool = true ) { - precondition(rawTokenKind != .keyword, "To create a TokenSpec for a keyword use the initializer that takes a keyword") + precondition( + rawTokenKind != .keyword, + "To create a TokenSpec for a keyword use the initializer that takes a keyword" + ) self.rawTokenKind = rawTokenKind self.keyword = nil self.remapping = remapping @@ -195,7 +198,10 @@ 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) + return 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 408b05bc82b..ca7aa553a73 100644 --- a/Sources/SwiftParser/TokenSpecSet.swift +++ b/Sources/SwiftParser/TokenSpecSet.swift @@ -423,7 +423,8 @@ enum DeclarationModifier: TokenSpecSet { case TokenSpec(.unowned): self = .unowned case TokenSpec(.weak): self = .weak case TokenSpec(._resultDependsOn) where experimentalFeatures.contains(.nonescapableTypes): self = ._resultDependsOn - case TokenSpec(._resultDependsOnSelf) where experimentalFeatures.contains(.nonescapableTypes): self = ._resultDependsOnSelf + case TokenSpec(._resultDependsOnSelf) where experimentalFeatures.contains(.nonescapableTypes): + self = ._resultDependsOnSelf default: return nil } } @@ -490,7 +491,8 @@ enum DeclarationStart: TokenSpecSet { } static var allCases: [DeclarationStart] { - return DeclarationModifier.allCases.map(Self.declarationModifier) + DeclarationKeyword.allCases.map(Self.declarationKeyword) + return DeclarationModifier.allCases.map(Self.declarationModifier) + + DeclarationKeyword.allCases.map(Self.declarationKeyword) } var spec: TokenSpec { @@ -600,7 +602,8 @@ enum OperatorLike: TokenSpecSet { } static var allCases: [OperatorLike] { - [.prefixOperator] + BinaryOperatorLike.allCases.map(Self.binaryOperatorLike) + PostfixOperatorLike.allCases.map(Self.postfixOperatorLike) + [.prefixOperator] + BinaryOperatorLike.allCases.map(Self.binaryOperatorLike) + + PostfixOperatorLike.allCases.map(Self.postfixOperatorLike) } var spec: TokenSpec { diff --git a/Sources/SwiftParser/TopLevel.swift b/Sources/SwiftParser/TopLevel.swift index 2a34669a11b..92b12a8181e 100644 --- a/Sources/SwiftParser/TopLevel.swift +++ b/Sources/SwiftParser/TopLevel.swift @@ -208,7 +208,10 @@ extension Parser { /// closing braces while trying to recover to the next item. /// If we are not at the top level, such a closing brace should close the /// wrapping declaration instead of being consumed by lookahead. - private mutating func parseItem(isAtTopLevel: Bool = false, allowInitDecl: Bool = true) -> RawCodeBlockItemSyntax.Item { + private mutating func parseItem( + isAtTopLevel: Bool = false, + allowInitDecl: Bool = true + ) -> RawCodeBlockItemSyntax.Item { if self.at(.poundIf) && !self.withLookahead({ $0.consumeIfConfigOfAttributes() }) { // If config of attributes is parsed as part of declaration parsing as it // doesn't constitute its own code block item. diff --git a/Sources/SwiftParser/Types.swift b/Sources/SwiftParser/Types.swift index a0e64823ae8..1ba26ee569d 100644 --- a/Sources/SwiftParser/Types.swift +++ b/Sources/SwiftParser/Types.swift @@ -35,7 +35,10 @@ extension Parser { var base = RawTypeSyntax(self.parseSimpleOrCompositionType()) if self.withLookahead({ $0.atFunctionTypeArrow() }) { var effectSpecifiers = self.parseTypeEffectSpecifiers() - let returnClause = self.parseFunctionReturnClause(effectSpecifiers: &effectSpecifiers, allowNamedOpaqueResultType: false) + let returnClause = self.parseFunctionReturnClause( + effectSpecifiers: &effectSpecifiers, + allowNamedOpaqueResultType: false + ) let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax? let leftParen: RawTokenSyntax @@ -342,7 +345,9 @@ extension Parser { } /// Parse an optional type. - mutating func parseImplicitlyUnwrappedOptionalType(_ base: RawTypeSyntax) -> RawImplicitlyUnwrappedOptionalTypeSyntax { + mutating func parseImplicitlyUnwrappedOptionalType( + _ base: RawTypeSyntax + ) -> RawImplicitlyUnwrappedOptionalTypeSyntax { let (unexpectedBeforeMark, mark) = self.expect(.exclamationMark) return RawImplicitlyUnwrappedOptionalTypeSyntax( wrappedType: base, @@ -623,7 +628,8 @@ extension Parser.Lookahead { var specifierProgress = LoopProgressCondition() // TODO: Can we model isolated/_const so that they're specified in both canParse* and parse*? while canHaveParameterSpecifier, - self.at(anyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) != nil || self.at(.keyword(.isolated)) || self.at(.keyword(._const)), + self.at(anyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) != nil || self.at(.keyword(.isolated)) + || self.at(.keyword(._const)), self.hasProgressed(&specifierProgress) { self.consumeAnyToken() @@ -734,7 +740,9 @@ extension Parser.Lookahead { return false } - if self.at(TokenSpec(.postfixQuestionMark, allowAtStartOfLine: false)) || self.at(TokenSpec(.exclamationMark, allowAtStartOfLine: false)) { + if self.at(TokenSpec(.postfixQuestionMark, allowAtStartOfLine: false)) + || self.at(TokenSpec(.exclamationMark, allowAtStartOfLine: false)) + { self.consumeAnyToken() continue } @@ -840,7 +848,9 @@ extension Parser.Lookahead { } // Parse an identifier. - guard self.at(.identifier) || self.at(.keyword(.Self)) || (allowKeyword && self.currentToken.isLexerClassifiedKeyword) else { + guard + self.at(.identifier) || self.at(.keyword(.Self)) || (allowKeyword && self.currentToken.isLexerClassifiedKeyword) + else { return false } self.consumeAnyToken() @@ -909,7 +919,11 @@ extension Parser { rightParen: missingToken(.rightParen), arena: self.arena ) - let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax(specifier: specifier, arguments: arguments, arena: self.arena) + let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax( + specifier: specifier, + arguments: arguments, + arena: self.arena + ) return .lifetimeTypeSpecifier(lifetimeSpecifier) } @@ -940,7 +954,11 @@ extension Parser { rightParen: rightParen, arena: self.arena ) - let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax(specifier: specifier, arguments: argumentsSyntax, arena: self.arena) + let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax( + specifier: specifier, + arguments: argumentsSyntax, + arena: self.arena + ) return .lifetimeTypeSpecifier(lifetimeSpecifier) } @@ -958,9 +976,12 @@ extension Parser { specifiers: RawTypeSpecifierListSyntax, attributes: RawAttributeListSyntax )? { - typealias SimpleOrLifetimeSpecifier = EitherTokenSpecSet + typealias SimpleOrLifetimeSpecifier = + EitherTokenSpecSet var specifiers: [RawTypeSpecifierListSyntax.Element] = [] - SPECIFIER_PARSING: while canHaveParameterSpecifier, let (specifierSpec, specifierHandle) = self.at(anyIn: SimpleOrLifetimeSpecifier.self) { + SPECIFIER_PARSING: while canHaveParameterSpecifier, + let (specifierSpec, specifierHandle) = self.at(anyIn: SimpleOrLifetimeSpecifier.self) + { switch specifierSpec { case .lhs: specifiers.append(parseSimpleTypeSpecifier(specifierHandle: specifierHandle)) case .rhs: diff --git a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift index 570cff6c023..d5508703abd 100644 --- a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift @@ -193,16 +193,19 @@ public extension SwiftSyntax.TokenDiagnostic { switch self.kind { case .editorPlaceholder: return StaticTokenError.editorPlaceholder - case .equalMustHaveConsistentWhitespaceOnBothSides: return StaticTokenError.equalMustHaveConsistentWhitespaceOnBothSides + case .equalMustHaveConsistentWhitespaceOnBothSides: + return StaticTokenError.equalMustHaveConsistentWhitespaceOnBothSides case .expectedBinaryExponentInHexFloatLiteral: return StaticTokenError.expectedBinaryExponentInHexFloatLiteral case .expectedClosingBraceInUnicodeEscape: return StaticTokenError.expectedClosingBraceInUnicodeEscape case .expectedDigitInFloatLiteral: return StaticTokenError.expectedDigitInFloatLiteral case .expectedHexCodeInUnicodeEscape: return StaticTokenError.expectedHexCodeInUnicodeEscape case .expectedHexDigitInHexLiteral: return StaticTokenError.expectedHexDigitInHexLiteral case .extraneousLeadingWhitespaceError: return ExtraneousLeadingWhitespaceError(tokenText: token.rawText) - case .extraneousLeadingWhitespaceWarning: return ErrorToWarningDowngrade(error: ExtraneousLeadingWhitespaceError(tokenText: token.rawText)) + case .extraneousLeadingWhitespaceWarning: + return ErrorToWarningDowngrade(error: ExtraneousLeadingWhitespaceError(tokenText: token.rawText)) case .extraneousTrailingWhitespaceError: return ExtraneousTrailingWhitespaceError(tokenText: token.rawText) - case .extraneousTrailingWhitespaceWarning: return ErrorToWarningDowngrade(error: ExtraneousTrailingWhitespaceError(tokenText: token.rawText)) + case .extraneousTrailingWhitespaceWarning: + return ErrorToWarningDowngrade(error: ExtraneousTrailingWhitespaceError(tokenText: token.rawText)) case .insufficientIndentationInMultilineStringLiteral: // This should be diagnosed when visiting the `StringLiteralExprSyntax` // inside `ParseDiagnosticsGenerator` but fall back to an error message @@ -212,7 +215,8 @@ public extension SwiftSyntax.TokenDiagnostic { case .invalidCharacter: return StaticTokenError.invalidCharacter case .invalidDecimalDigitInIntegerLiteral: return InvalidDigitInIntegerLiteral(kind: .decimal(scalarAtErrorOffset)) case .invalidEscapeSequenceInStringLiteral: return StaticTokenError.invalidEscapeSequenceInStringLiteral - case .invalidFloatingPointExponentCharacter: return InvalidFloatingPointExponentDigit(kind: .character(scalarAtErrorOffset)) + case .invalidFloatingPointExponentCharacter: + return InvalidFloatingPointExponentDigit(kind: .character(scalarAtErrorOffset)) case .invalidFloatingPointExponentDigit: return InvalidFloatingPointExponentDigit(kind: .digit(scalarAtErrorOffset)) case .invalidHexDigitInIntegerLiteral: return InvalidDigitInIntegerLiteral(kind: .hex(scalarAtErrorOffset)) case .invalidIdentifierStartCharacter: return StaticTokenError.invalidIdentifierStartCharacter @@ -264,7 +268,10 @@ public extension SwiftSyntax.TokenDiagnostic { .with(\.leadingTrivia, Trivia(pieces: token.leadingTrivia.map(replaceNonBreakingSpace))) .with(\.trailingTrivia, Trivia(pieces: token.trailingTrivia.map(replaceNonBreakingSpace))) return [ - FixIt(message: .replaceNonBreakingSpaceBySpace, changes: [.replace(oldNode: Syntax(token), newNode: Syntax(fixedToken))]) + FixIt( + message: .replaceNonBreakingSpaceBySpace, + changes: [.replace(oldNode: Syntax(token), newNode: Syntax(fixedToken))] + ) ] case .unicodeCurlyQuote: let (rawKind, text) = token.tokenKind.decomposeToRaw() @@ -278,10 +285,14 @@ public extension SwiftSyntax.TokenDiagnostic { let fixedToken = token.with(\.tokenKind, TokenKind.fromRaw(kind: rawKind, text: replacedText)) return [ - FixIt(message: .replaceCurlyQuoteByNormalQuote, changes: [.replace(oldNode: Syntax(token), newNode: Syntax(fixedToken))]) + FixIt( + message: .replaceCurlyQuoteByNormalQuote, + changes: [.replace(oldNode: Syntax(token), newNode: Syntax(fixedToken))] + ) ] case .equalMustHaveConsistentWhitespaceOnBothSides: - let hasLeadingSpace = token.previousToken(viewMode: .all)?.trailingTrivia.contains(where: { $0.isSpaceOrTab }) ?? false + let hasLeadingSpace = + token.previousToken(viewMode: .all)?.trailingTrivia.contains(where: { $0.isSpaceOrTab }) ?? false let hasTrailingSpace = token.trailingTrivia.contains { $0.isSpaceOrTab } var changes: [FixIt.Change] = [] diff --git a/Sources/SwiftParserDiagnostics/MissingNodesError.swift b/Sources/SwiftParserDiagnostics/MissingNodesError.swift index 62206c34f0b..53c4a474dae 100644 --- a/Sources/SwiftParserDiagnostics/MissingNodesError.swift +++ b/Sources/SwiftParserDiagnostics/MissingNodesError.swift @@ -107,7 +107,8 @@ fileprivate enum NodesDescriptionPart { // Merge `tokensWithDefaultText` if they occur consecutively in the tree if let lastPrevious = previousTokens.last, let firstNew = newTokens.first, - originalTokens[lastPrevious, default: lastPrevious].nextToken(viewMode: .all) == originalTokens[firstNew, default: firstNew] + originalTokens[lastPrevious, default: lastPrevious].nextToken(viewMode: .all) + == originalTokens[firstNew, default: firstNew] { parts[parts.count - 1] = .tokensWithDefaultText(previousTokens + newTokens) } else { @@ -138,7 +139,10 @@ func nodesDescription(_ nodes: [some SyntaxProtocol], format: Bool) -> String { } /// Same as `nodesDescription` but if a common ancestor was used to describe `missingNodes`, also return that `commonAncestor` -func nodesDescriptionAndCommonParent(_ nodes: [some SyntaxProtocol], format: Bool) -> (commonAncestor: Syntax?, description: String) { +func nodesDescriptionAndCommonParent( + _ nodes: [some SyntaxProtocol], + format: Bool +) -> (commonAncestor: Syntax?, description: String) { let missingSyntaxNodes = nodes.map(Syntax.init) let isOnlyTokenWithNonMissingText: Bool @@ -166,7 +170,9 @@ func nodesDescriptionAndCommonParent(_ nodes: [some SyntaxProtocol], format: Boo } } - let partDescriptions = NodesDescriptionPart.descriptionParts(for: missingSyntaxNodes).map({ $0.description(format: format) ?? "syntax" }) + let partDescriptions = NodesDescriptionPart.descriptionParts(for: missingSyntaxNodes).map({ + $0.description(format: format) ?? "syntax" + }) return (nil, formatDescriptions(partDescriptions)) } @@ -334,7 +340,8 @@ public struct MissingNodesError: ParserError { var message = "expected \(description)" if let afterClause { message += " \(afterClause)" - } else if let parentContextClause = parentContextClause(anchor: anchor?.parent ?? findCommonAncestor(missingNodes)) { + } else if let parentContextClause = parentContextClause(anchor: anchor?.parent ?? findCommonAncestor(missingNodes)) + { message += " \(parentContextClause)" } return message @@ -451,7 +458,9 @@ extension ParseDiagnosticsGenerator { position = overridePosition } else if node.shouldBeInsertedAfterNextTokenTrivia, let nextToken = node.nextToken(viewMode: .sourceAccurate) { position = nextToken.positionAfterSkippingLeadingTrivia - } else if node.shouldBeInsertedBeforePreviousTokenTrivia, let previousToken = node.previousToken(viewMode: .sourceAccurate) { + } else if node.shouldBeInsertedBeforePreviousTokenTrivia, + let previousToken = node.previousToken(viewMode: .sourceAccurate) + { position = previousToken.endPositionBeforeTrailingTrivia } else { position = node.endPosition diff --git a/Sources/SwiftParserDiagnostics/MissingTokenError.swift b/Sources/SwiftParserDiagnostics/MissingTokenError.swift index 443722f9836..40161fefd63 100644 --- a/Sources/SwiftParserDiagnostics/MissingTokenError.swift +++ b/Sources/SwiftParserDiagnostics/MissingTokenError.swift @@ -31,13 +31,29 @@ extension ParseDiagnosticsGenerator { let handled: Bool switch (missingToken.tokenView.rawKind, invalidToken.tokenView.rawKind) { case (.identifier, _): - handled = handleInvalidIdentifier(invalidToken: invalidToken, missingToken: missingToken, invalidTokenContainer: invalidTokenContainer) + handled = handleInvalidIdentifier( + invalidToken: invalidToken, + missingToken: missingToken, + invalidTokenContainer: invalidTokenContainer + ) case (.multilineStringQuote, .multilineStringQuote): - handled = handleInvalidMultilineStringQuote(invalidToken: invalidToken, missingToken: missingToken, invalidTokenContainer: invalidTokenContainer) + handled = handleInvalidMultilineStringQuote( + invalidToken: invalidToken, + missingToken: missingToken, + invalidTokenContainer: invalidTokenContainer + ) case (.period, .period): - handled = handleInvalidPeriod(invalidToken: invalidToken, missingToken: missingToken, invalidTokenContainer: invalidTokenContainer) + handled = handleInvalidPeriod( + invalidToken: invalidToken, + missingToken: missingToken, + invalidTokenContainer: invalidTokenContainer + ) case (.rawStringPoundDelimiter, .rawStringPoundDelimiter), (.regexPoundDelimiter, .regexPoundDelimiter): - handled = handleInvalidPoundDelimiter(invalidToken: invalidToken, missingToken: missingToken, invalidTokenContainer: invalidTokenContainer) + handled = handleInvalidPoundDelimiter( + invalidToken: invalidToken, + missingToken: missingToken, + invalidTokenContainer: invalidTokenContainer + ) default: handled = false } @@ -46,7 +62,11 @@ extension ParseDiagnosticsGenerator { } } - private func handleInvalidIdentifier(invalidToken: TokenSyntax, missingToken: TokenSyntax, invalidTokenContainer: UnexpectedNodesSyntax) -> Bool { + private func handleInvalidIdentifier( + invalidToken: TokenSyntax, + missingToken: TokenSyntax, + invalidTokenContainer: UnexpectedNodesSyntax + ) -> Bool { let fixIts: [FixIt] if invalidToken.tokenKind.isLexerClassifiedKeyword || invalidToken.tokenKind.isDollarIdentifier { fixIts = [ @@ -56,7 +76,11 @@ extension ParseDiagnosticsGenerator { .replace( oldNode: Syntax(invalidToken), newNode: Syntax( - TokenSyntax.identifier("`\(invalidToken.text)`", leadingTrivia: invalidToken.leadingTrivia, trailingTrivia: invalidToken.trailingTrivia) + TokenSyntax.identifier( + "`\(invalidToken.text)`", + leadingTrivia: invalidToken.leadingTrivia, + trailingTrivia: invalidToken.trailingTrivia + ) ) ) ] @@ -74,13 +98,22 @@ extension ParseDiagnosticsGenerator { return true } - private func handleInvalidMultilineStringQuote(invalidToken: TokenSyntax, missingToken: TokenSyntax, invalidTokenContainer: UnexpectedNodesSyntax) -> Bool { + private func handleInvalidMultilineStringQuote( + invalidToken: TokenSyntax, + missingToken: TokenSyntax, + invalidTokenContainer: UnexpectedNodesSyntax + ) -> Bool { if invalidToken.trailingTrivia.isEmpty && !missingToken.trailingTrivia.isEmpty { addDiagnostic( invalidToken, position: invalidToken.endPositionBeforeTrailingTrivia, .multiLineStringLiteralMustBeginOnNewLine, - fixIts: [FixIt(message: .insertNewline, changes: [.replaceTrailingTrivia(token: invalidToken, newTrivia: missingToken.trailingTrivia)])], + fixIts: [ + FixIt( + message: .insertNewline, + changes: [.replaceTrailingTrivia(token: invalidToken, newTrivia: missingToken.trailingTrivia)] + ) + ], handledNodes: [invalidTokenContainer.id] ) return true @@ -88,7 +121,12 @@ extension ParseDiagnosticsGenerator { addDiagnostic( invalidToken, .multiLineStringLiteralMustHaveClosingDelimiterOnNewLine, - fixIts: [FixIt(message: .insertNewline, changes: [.replaceLeadingTrivia(token: invalidToken, newTrivia: missingToken.leadingTrivia)])], + fixIts: [ + FixIt( + message: .insertNewline, + changes: [.replaceLeadingTrivia(token: invalidToken, newTrivia: missingToken.leadingTrivia)] + ) + ], handledNodes: [invalidTokenContainer.id] ) return true @@ -97,7 +135,11 @@ extension ParseDiagnosticsGenerator { return false } - private func handleInvalidPeriod(invalidToken: TokenSyntax, missingToken: TokenSyntax, invalidTokenContainer: UnexpectedNodesSyntax) -> Bool { + private func handleInvalidPeriod( + invalidToken: TokenSyntax, + missingToken: TokenSyntax, + invalidTokenContainer: UnexpectedNodesSyntax + ) -> Bool { // Trailing trivia is the cause of this diagnostic, don't transfer it. let changes: [FixIt.MultiNodeChange] = [ .makeMissing(invalidToken, transferTrivia: false), @@ -124,7 +166,12 @@ extension ParseDiagnosticsGenerator { ) } else { let fixIt = FixIt(message: .removeExtraneousWhitespace, changes: changes) - addDiagnostic(invalidToken, ExtraneousWhitespace(tokenWithWhitespace: invalidToken), fixIts: [fixIt], handledNodes: [invalidTokenContainer.id]) + addDiagnostic( + invalidToken, + ExtraneousWhitespace(tokenWithWhitespace: invalidToken), + fixIts: [fixIt], + handledNodes: [invalidTokenContainer.id] + ) } return true } diff --git a/Sources/SwiftParserDiagnostics/MultiLineStringLiteralDiagnosticsGenerator.swift b/Sources/SwiftParserDiagnostics/MultiLineStringLiteralDiagnosticsGenerator.swift index 84abb7478f1..7498ae7f671 100644 --- a/Sources/SwiftParserDiagnostics/MultiLineStringLiteralDiagnosticsGenerator.swift +++ b/Sources/SwiftParserDiagnostics/MultiLineStringLiteralDiagnosticsGenerator.swift @@ -29,7 +29,9 @@ final class MultiLineStringLiteralIndentationDiagnosticsGenerator: SyntaxVisitor // MARK: Entry - public static func diagnose(_ node: StringLiteralExprSyntax) -> [(diagnostic: Diagnostic, handledNodes: [SyntaxIdentifier])] { + public static func diagnose( + _ node: StringLiteralExprSyntax + ) -> [(diagnostic: Diagnostic, handledNodes: [SyntaxIdentifier])] { let visitor = MultiLineStringLiteralIndentationDiagnosticsGenerator(closeQuote: node.closingQuote) visitor.walk(node) visitor.finishInProgressDiagnostic() @@ -58,12 +60,16 @@ final class MultiLineStringLiteralIndentationDiagnosticsGenerator: SyntaxVisitor let tokenLeadingTrivia = token.leadingTrivia - let indentationStartIndex = tokenLeadingTrivia.pieces.lastIndex(where: { $0.isNewline })?.advanced(by: 1) ?? tokenLeadingTrivia.startIndex + let indentationStartIndex = + tokenLeadingTrivia.pieces.lastIndex(where: { $0.isNewline })?.advanced(by: 1) ?? tokenLeadingTrivia.startIndex let preIndentationTrivia = Trivia(pieces: tokenLeadingTrivia[0.. SyntaxVisitorContinueKind { @@ -261,7 +288,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { let specifierInfo = [ (node.asyncSpecifier, { AsyncEffectSpecifier(token: $0) != nil }, StaticParserError.misspelledAsync), - (node.throwsClause?.throwsSpecifier, { ThrowsEffectSpecifier(token: $0) != nil }, StaticParserError.misspelledThrows), + ( + node.throwsClause?.throwsSpecifier, { ThrowsEffectSpecifier(token: $0) != nil }, + StaticParserError.misspelledThrows + ), ] let unexpectedNodes = [ @@ -310,7 +340,12 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { duplicateSpecifier, DuplicateEffectSpecifiers(correctSpecifier: specifier, unexpectedSpecifier: duplicateSpecifier), notes: [Note(node: Syntax(specifier), message: EffectSpecifierDeclaredHere(specifier: specifier))], - fixIts: [FixIt(message: RemoveRedundantFixIt(removeTokens: [duplicateSpecifier]), changes: [.makeMissing(duplicateSpecifier)])], + fixIts: [ + FixIt( + message: RemoveRedundantFixIt(removeTokens: [duplicateSpecifier]), + changes: [.makeMissing(duplicateSpecifier)] + ) + ], handledNodes: [unexpected.id] ) } @@ -352,7 +387,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { node, .unexpectedSemicolon, fixIts: [ - FixIt(message: RemoveNodesFixIt(semicolons), changes: semicolons.map { FixIt.MultiNodeChange.makeMissing($0) }) + FixIt( + message: RemoveNodesFixIt(semicolons), + changes: semicolons.map { FixIt.MultiNodeChange.makeMissing($0) } + ) ] ) } else if let firstToken = node.first?.as(TokenSyntax.self), @@ -361,7 +399,8 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { firstToken.presence == .present, let previousToken = node.previousToken(viewMode: .sourceAccurate), previousToken.tokenKind.isIdentifier, - previousToken.parent?.is(DeclSyntax.self) == true || previousToken.parent?.is(IdentifierPatternSyntax.self) == true + previousToken.parent?.is(DeclSyntax.self) == true + || previousToken.parent?.is(IdentifierPatternSyntax.self) == true { // If multiple identifiers are used for a declaration name, offer to join them together. let tokens = @@ -381,7 +420,13 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { FixIt.MultiNodeChange( .replace( oldNode: Syntax(previousToken), - newNode: Syntax(TokenSyntax(.identifier(joined), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)) + newNode: Syntax( + TokenSyntax( + .identifier(joined), + trailingTrivia: tokens.last?.trailingTrivia ?? [], + presence: .present + ) + ) ) ), .makeMissing(tokens), @@ -397,7 +442,13 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { FixIt.MultiNodeChange( .replace( oldNode: Syntax(previousToken), - newNode: Syntax(TokenSyntax(.identifier(joinedUsingCamelCase), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)) + newNode: Syntax( + TokenSyntax( + .identifier(joinedUsingCamelCase), + trailingTrivia: tokens.last?.trailingTrivia ?? [], + presence: .present + ) + ) ) ), .makeMissing(tokens), @@ -405,7 +456,11 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { ) ) } - addDiagnostic(node, SpaceSeparatedIdentifiersError(firstToken: previousToken, additionalTokens: tokens), fixIts: fixIts) + addDiagnostic( + node, + SpaceSeparatedIdentifiersError(firstToken: previousToken, additionalTokens: tokens), + fixIts: fixIts + ) } else { addDiagnostic(node, UnexpectedNodesError(unexpectedNodes: node), highlights: [Syntax(node)]) } @@ -457,7 +512,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { if shouldSkip(node) { return .skipChildren } - handleMisplacedEffectSpecifiersAfterArrow(effectSpecifiers: node.effectSpecifiers, misplacedSpecifiers: node.unexpectedAfterArrow) + handleMisplacedEffectSpecifiersAfterArrow( + effectSpecifiers: node.effectSpecifiers, + misplacedSpecifiers: node.unexpectedAfterArrow + ) return .visitChildren } @@ -496,7 +554,9 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { addDiagnostic( node.rightSquare, .extraRightBracket, - fixIts: [.init(message: InsertFixIt(tokenToBeInserted: node.leftSquare), changes: .makePresent(node.leftSquare))], + fixIts: [ + .init(message: InsertFixIt(tokenToBeInserted: node.leftSquare), changes: .makePresent(node.leftSquare)) + ], handledNodes: [node.leftSquare.id] ) } @@ -557,12 +617,18 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { .with(\.unexpectedAfterRightParen, nil) addDiagnostic( unexpectedAfterRightParen, - AvailabilityConditionAsExpression(availabilityToken: node.availabilityKeyword, negatedAvailabilityToken: negatedAvailabilityKeyword), + 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) + replacements: getTokens( + between: negatedAvailability.availabilityKeyword, + and: negatedAvailability.rightParen + ) ), changes: [ .replace(oldNode: Syntax(node), newNode: Syntax(negatedAvailability)) @@ -650,7 +716,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { FixIt( message: .insertNewline, changes: [ - .replaceTrailingTrivia(token: lastToken, newTrivia: lastToken.trailingTrivia + .newlines(1) + firstToken.indentationOfLine) + .replaceTrailingTrivia( + token: lastToken, + newTrivia: lastToken.trailingTrivia + .newlines(1) + firstToken.indentationOfLine + ) ] ), at: 0 @@ -807,8 +876,15 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { addDiagnostic( duplicateSpecifier, DuplicateEffectSpecifiers(correctSpecifier: asyncSpecifier, unexpectedSpecifier: duplicateSpecifier), - notes: [Note(node: Syntax(asyncSpecifier), message: EffectSpecifierDeclaredHere(specifier: asyncSpecifier))], - fixIts: [FixIt(message: RemoveRedundantFixIt(removeTokens: [duplicateSpecifier]), changes: [.makeMissing(duplicateSpecifier)])], + notes: [ + Note(node: Syntax(asyncSpecifier), message: EffectSpecifierDeclaredHere(specifier: asyncSpecifier)) + ], + fixIts: [ + FixIt( + message: RemoveRedundantFixIt(removeTokens: [duplicateSpecifier]), + changes: [.makeMissing(duplicateSpecifier)] + ) + ], handledNodes: [unexpected.id] ) } @@ -974,7 +1050,11 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } if node.baseName.isMissing, let unexpected = node.unexpectedBeforeBaseName { if unexpected.first?.as(TokenSyntax.self)?.tokenKind == .pound { - addDiagnostic(unexpected, UnknownDirectiveError(unexpected: unexpected), handledNodes: [unexpected.id, node.baseName.id]) + addDiagnostic( + unexpected, + UnknownDirectiveError(unexpected: unexpected), + handledNodes: [unexpected.id, node.baseName.id] + ) } else if let availability = unexpected.first?.as(AvailabilityConditionSyntax.self) { if let prefixOperatorExpr = node.parent?.as(PrefixOperatorExprSyntax.self), prefixOperatorExpr.operator.text == "!", @@ -989,7 +1069,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { ) addDiagnostic( unexpected, - NegatedAvailabilityCondition(availabilityCondition: availability, negatedAvailabilityKeyword: negatedAvailabilityKeyword), + NegatedAvailabilityCondition( + availabilityCondition: availability, + negatedAvailabilityKeyword: negatedAvailabilityKeyword + ), fixIts: [ FixIt( message: ReplaceTokensFixIt( @@ -1004,7 +1087,11 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { handledNodes: [unexpected.id, node.baseName.id] ) } else { - addDiagnostic(unexpected, AvailabilityConditionInExpression(availabilityCondition: availability), handledNodes: [unexpected.id, node.baseName.id]) + addDiagnostic( + unexpected, + AvailabilityConditionInExpression(availabilityCondition: availability), + handledNodes: [unexpected.id, node.baseName.id] + ) } } } @@ -1017,7 +1104,9 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } if let unexpectedBetweenNameAndParameterClause = node.unexpectedBetweenNameAndParameterClause, - let genericParameter = unexpectedBetweenNameAndParameterClause.compactMap({ $0.as(GenericParameterClauseSyntax.self) }).only + let genericParameter = unexpectedBetweenNameAndParameterClause.compactMap({ + $0.as(GenericParameterClauseSyntax.self) + }).only { addDiagnostic( genericParameter, @@ -1209,7 +1298,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { FixIt( message: .insertNewline, changes: [ - .replaceTrailingTrivia(token: lastToken, newTrivia: lastToken.trailingTrivia + .newlines(1) + firstToken.indentationOfLine) + .replaceTrailingTrivia( + token: lastToken, + newTrivia: lastToken.trailingTrivia + .newlines(1) + firstToken.indentationOfLine + ) ] ), at: 0 @@ -1293,17 +1385,30 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { node.fixitySpecifier, .missingFixityInOperatorDeclaration, fixIts: [ - FixIt(message: InsertFixIt(tokenToBeInserted: .keyword(.prefix)), changes: .makePresent(node.fixitySpecifier)), + FixIt( + message: InsertFixIt(tokenToBeInserted: .keyword(.prefix)), + changes: .makePresent(node.fixitySpecifier) + ), FixIt( message: InsertFixIt(tokenToBeInserted: .keyword(.infix)), changes: [ - FixIt.MultiNodeChange(.replace(oldNode: Syntax(node.fixitySpecifier), newNode: Syntax(TokenSyntax(.keyword(.infix), presence: .present)))) + FixIt.MultiNodeChange( + .replace( + oldNode: Syntax(node.fixitySpecifier), + newNode: Syntax(TokenSyntax(.keyword(.infix), presence: .present)) + ) + ) ] ), FixIt( message: InsertFixIt(tokenToBeInserted: .keyword(.postfix)), changes: [ - FixIt.MultiNodeChange(.replace(oldNode: Syntax(node.fixitySpecifier), newNode: Syntax(TokenSyntax(.keyword(.postfix), presence: .present)))) + FixIt.MultiNodeChange( + .replace( + oldNode: Syntax(node.fixitySpecifier), + newNode: Syntax(TokenSyntax(.keyword(.postfix), presence: .present)) + ) + ) ] ), ], @@ -1343,12 +1448,21 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { } else { fixIts = [] } - addDiagnostic(unexpected, message, highlights: [Syntax(unexpected)], fixIts: fixIts, handledNodes: [unexpected.id, node.name.id]) + addDiagnostic( + unexpected, + message, + highlights: [Syntax(unexpected)], + fixIts: fixIts, + handledNodes: [unexpected.id, node.name.id] + ) } } diagnoseIdentifierInOperatorName(unexpected: node.unexpectedBetweenOperatorKeywordAndName, name: node.name) - diagnoseIdentifierInOperatorName(unexpected: node.unexpectedBetweenNameAndOperatorPrecedenceAndTypes, name: node.name) + diagnoseIdentifierInOperatorName( + unexpected: node.unexpectedBetweenNameAndOperatorPrecedenceAndTypes, + name: node.name + ) return .visitChildren } @@ -1374,7 +1488,11 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return .skipChildren } if let unexpected = node.unexpectedBetweenColonAndValue ?? node.unexpectedAfterValue, node.value.isMissing { - addDiagnostic(unexpected, .invalidFlagAfterPrecedenceGroupAssignment, handledNodes: [unexpected.id, node.value.id]) + addDiagnostic( + unexpected, + .invalidFlagAfterPrecedenceGroupAssignment, + handledNodes: [unexpected.id, node.value.id] + ) } return .visitChildren } @@ -1445,11 +1563,15 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { var rawDelimiters: [TokenSyntax] = [] - if let unexpectedBeforeOpenQuote = node.unexpectedBeforeOpeningQuote?.onlyPresentToken(where: { $0.tokenKind.isRawStringDelimiter }) { + if let unexpectedBeforeOpenQuote = node.unexpectedBeforeOpeningQuote?.onlyPresentToken(where: { + $0.tokenKind.isRawStringDelimiter + }) { rawDelimiters += [unexpectedBeforeOpenQuote] } - if let unexpectedAfterCloseQuote = node.unexpectedAfterClosingQuote?.onlyPresentToken(where: { $0.tokenKind.isRawStringDelimiter }) { + if let unexpectedAfterCloseQuote = node.unexpectedAfterClosingQuote?.onlyPresentToken(where: { + $0.tokenKind.isRawStringDelimiter + }) { rawDelimiters += [unexpectedAfterCloseQuote] } @@ -1503,7 +1625,9 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return .skipChildren } // recover from Objective-C style literals - if let atSign = node.unexpectedBetweenOpeningPoundsAndOpeningQuote?.onlyPresentToken(where: { $0.tokenKind == .atSign }) { + if let atSign = node.unexpectedBetweenOpeningPoundsAndOpeningQuote?.onlyPresentToken(where: { + $0.tokenKind == .atSign + }) { addDiagnostic( node, .stringLiteralAtSign, @@ -1513,14 +1637,19 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { handledNodes: [atSign.id] ) } - if let singleQuote = node.unexpectedBetweenOpeningPoundsAndOpeningQuote?.onlyPresentToken(where: { $0.tokenKind == .singleQuote }) { + if let singleQuote = node.unexpectedBetweenOpeningPoundsAndOpeningQuote?.onlyPresentToken(where: { + $0.tokenKind == .singleQuote + }) { let fixIt = FixIt( message: ReplaceTokensFixIt(replaceTokens: [singleQuote], replacements: [node.openingQuote]), changes: [ .makeMissing(singleQuote, transferTrivia: false), .makePresent(node.openingQuote, leadingTrivia: singleQuote.leadingTrivia), .makeMissing(node.unexpectedBetweenSegmentsAndClosingQuote, transferTrivia: false), - .makePresent(node.closingQuote, trailingTrivia: node.unexpectedBetweenSegmentsAndClosingQuote?.trailingTrivia ?? []), + .makePresent( + node.closingQuote, + trailingTrivia: node.unexpectedBetweenSegmentsAndClosingQuote?.trailingTrivia ?? [] + ), ] ) addDiagnostic( @@ -1563,7 +1692,9 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { addDiagnostic(diagnostic, handledNodes: handledNodes) } if case .stringSegment(let segment) = node.segments.last { - if let invalidContent = segment.unexpectedBeforeContent?.onlyPresentToken(where: { $0.trailingTrivia.contains(where: { $0.isBackslash }) }) { + if let invalidContent = segment.unexpectedBeforeContent?.onlyPresentToken(where: { + $0.trailingTrivia.contains(where: { $0.isBackslash }) + }) { let fixIt = FixIt( message: .removeBackslash, changes: [ @@ -1647,7 +1778,9 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { if shouldSkip(node) { return .skipChildren } - if let unexpected = node.unexpectedBetweenDefaultKeywordAndColon, unexpected.first?.as(TokenSyntax.self)?.tokenKind == .keyword(.where) { + if let unexpected = node.unexpectedBetweenDefaultKeywordAndColon, + unexpected.first?.as(TokenSyntax.self)?.tokenKind == .keyword(.where) + { addDiagnostic(unexpected, .defaultCannotBeUsedWithWhere, handledNodes: [unexpected.id]) } return .visitChildren @@ -1676,7 +1809,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { node.expression, .expectedExpressionAfterTry, fixIts: [ - FixIt(message: InsertTokenFixIt(missingNodes: [Syntax(node.expression)]), changes: .makePresent(node.expression)) + FixIt( + message: InsertTokenFixIt(missingNodes: [Syntax(node.expression)]), + changes: .makePresent(node.expression) + ) ], handledNodes: [node.expression.id] ) @@ -1781,7 +1917,11 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { ), changes: [ .makeMissing(equalToken, transferTrivia: false), - .makePresent(node.colon, leadingTrivia: equalToken.leadingTrivia, trailingTrivia: equalToken.trailingTrivia), + .makePresent( + node.colon, + leadingTrivia: equalToken.leadingTrivia, + trailingTrivia: equalToken.trailingTrivia + ), ] ) ], @@ -1864,9 +2004,11 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { continue } - let unexpectedTokens: [TokenSyntax] = [detail.unexpectedBetweenLeftParenAndDetail, detail.unexpectedBetweenDetailAndRightParen] - .compactMap { $0?.tokens(viewMode: .sourceAccurate) } - .flatMap { $0 } + let unexpectedTokens: [TokenSyntax] = [ + detail.unexpectedBetweenLeftParenAndDetail, detail.unexpectedBetweenDetailAndRightParen, + ] + .compactMap { $0?.tokens(viewMode: .sourceAccurate) } + .flatMap { $0 } // If there is no unexpected tokens it means we miss a paren or set keyword. // So we just skip the handling here diff --git a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift index 4e7c072a653..4e11b4671d9 100644 --- a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift @@ -272,7 +272,8 @@ public struct AsyncMustPrecedeThrows: ParserError { public let throwsKeyword: TokenSyntax public var message: String { - return "\(nodesDescription(asyncKeywords, format: false)) must precede \(nodesDescription([throwsKeyword], format: false))" + return + "\(nodesDescription(asyncKeywords, format: false)) must precede \(nodesDescription([throwsKeyword], format: false))" } } @@ -289,7 +290,8 @@ 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'" + return + "\(nodesDescription([availabilityCondition], format: false)) cannot be used in an expression, only as a condition of 'if' or 'guard'" } } @@ -339,7 +341,8 @@ public struct DuplicateEffectSpecifiers: ParserError { if correctSpecifier.tokenKind == unexpectedSpecifier.tokenKind { return "\(nodesDescription([unexpectedSpecifier], format: false)) has already been specified" } else { - return "\(nodesDescription([unexpectedSpecifier], format: false)) conflicts with \(nodesDescription([correctSpecifier], format: false))" + return + "\(nodesDescription([unexpectedSpecifier], format: false)) conflicts with \(nodesDescription([correctSpecifier], format: false))" } } } @@ -372,7 +375,8 @@ 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" + return + "\(nodesDescription([identifier], format: false)) is considered an identifier and must not appear within an operator name" } } @@ -380,7 +384,8 @@ 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)'" + return + "'.\(decimalDigits.text)' is not a valid floating point literal; it must be written '0.\(decimalDigits.text)'" } } @@ -540,10 +545,13 @@ public struct UnexpectedNodesError: ParserError { var message = "unexpected \(unexpectedNodes.shortSingleLineContentDescription)" if let parent = unexpectedNodes.parent { if let parentTypeName = parent.nodeTypeNameForDiagnostics(allowBlockNames: false), - parent.children(viewMode: .sourceAccurate).first(where: { $0.totalLength.utf8Length > 0 })?.id == unexpectedNodes.id + parent.children(viewMode: .sourceAccurate).first(where: { $0.totalLength.utf8Length > 0 })?.id + == unexpectedNodes.id { message += " before \(parentTypeName)" - } else if let parentTypeName = parent.ancestorOrSelf(mapping: { $0.nodeTypeNameForDiagnostics(allowBlockNames: false) }) { + } else if let parentTypeName = parent.ancestorOrSelf(mapping: { + $0.nodeTypeNameForDiagnostics(allowBlockNames: false) + }) { message += " in \(parentTypeName)" } } @@ -566,7 +574,9 @@ public struct UnknownParameterError: ParserError { public var message: String { var message = "unknown parameter '\(parameter.text)'" - if let parentTypeName = parameter.parent?.ancestorOrSelf(mapping: { $0.nodeTypeNameForDiagnostics(allowBlockNames: false) }) { + if let parentTypeName = parameter.parent?.ancestorOrSelf(mapping: { + $0.nodeTypeNameForDiagnostics(allowBlockNames: false) + }) { message += " in \(parentTypeName)" } diff --git a/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift b/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift index 6cd050c0a52..8d59d387138 100644 --- a/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift +++ b/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift @@ -100,7 +100,9 @@ extension SyntaxProtocol { } else { return "braces" } - } else if let token = Syntax(self).as(UnexpectedNodesSyntax.self)?.onlyPresentTokens(satisfying: { $0.tokenKind.isLexerClassifiedKeyword })?.only { + } else if let token = Syntax(self).as(UnexpectedNodesSyntax.self)?.onlyPresentTokens(satisfying: { + $0.tokenKind.isLexerClassifiedKeyword + })?.only { return "'\(token.text)' keyword" } else if let token = Syntax(self).as(TokenSyntax.self) { return "'\(token.text)' keyword" diff --git a/Sources/SwiftRefactor/CallToTrailingClosures.swift b/Sources/SwiftRefactor/CallToTrailingClosures.swift index bbc5f3d9c81..f49c6465f3f 100644 --- a/Sources/SwiftRefactor/CallToTrailingClosures.swift +++ b/Sources/SwiftRefactor/CallToTrailingClosures.swift @@ -52,7 +52,10 @@ 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? { + public static func refactor( + syntax call: FunctionCallExprSyntax, + in context: Context = Context() + ) -> FunctionCallExprSyntax? { let converted = call.convertToTrailingClosures(from: context.startAtArgument) return converted?.formatted().as(FunctionCallExprSyntax.self) } diff --git a/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift b/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift index 4630d0e34b4..7ebd8c60634 100644 --- a/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift +++ b/Sources/SwiftRefactor/ExpandEditorPlaceholder.swift @@ -115,7 +115,9 @@ struct ExpandSingleEditorPlaceholder: EditRefactoringProvider { } } - return [SourceEdit.replace(token, with: token.leadingTrivia.description + expanded + token.trailingTrivia.description)] + return [ + SourceEdit.replace(token, with: token.leadingTrivia.description + expanded + token.trailingTrivia.description) + ] } } @@ -207,7 +209,10 @@ public struct ExpandEditorPlaceholdersToTrailingClosures: SyntaxRefactoringProvi } } - public static func refactor(syntax call: FunctionCallExprSyntax, in context: Context = Context()) -> FunctionCallExprSyntax? { + public static func refactor( + syntax call: FunctionCallExprSyntax, + in context: Context = Context() + ) -> FunctionCallExprSyntax? { return Self.expandTrailingClosurePlaceholders(in: call, ifIncluded: nil, indentationWidth: context.indentationWidth) } @@ -221,11 +226,14 @@ public struct ExpandEditorPlaceholdersToTrailingClosures: SyntaxRefactoringProvi ifIncluded arg: LabeledExprSyntax?, indentationWidth: Trivia? ) -> FunctionCallExprSyntax? { - guard let expanded = call.expandTrailingClosurePlaceholders(ifIncluded: arg, indentationWidth: indentationWidth) else { + guard let expanded = call.expandTrailingClosurePlaceholders(ifIncluded: arg, indentationWidth: indentationWidth) + else { return nil } - let callToTrailingContext = CallToTrailingClosures.Context(startAtArgument: call.arguments.count - expanded.numClosures) + let callToTrailingContext = CallToTrailingClosures.Context( + startAtArgument: call.arguments.count - expanded.numClosures + ) guard let trailing = CallToTrailingClosures.refactor(syntax: expanded.expr, in: callToTrailingContext) else { return nil } @@ -339,7 +347,10 @@ extension FunctionCallExprSyntax { for arg in arguments.suffix(argsToExpand) { let edits = ExpandSingleEditorPlaceholder.textRefactor( syntax: arg.expression.cast(DeclReferenceExprSyntax.self).baseName, - in: ExpandSingleEditorPlaceholder.Context(indentationWidth: indentationWidth, initialIndentation: lineIndentation) + in: ExpandSingleEditorPlaceholder.Context( + indentationWidth: indentationWidth, + initialIndentation: lineIndentation + ) ) guard edits.count == 1, let edit = edits.first, !edit.replacement.isEmpty else { return nil diff --git a/Sources/SwiftSyntax/Raw/RawSyntax.swift b/Sources/SwiftSyntax/Raw/RawSyntax.swift index 879832e1c6e..b0f51cd55a2 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntax.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntax.swift @@ -89,7 +89,13 @@ internal struct RawSyntaxData: Sendable { } } - init(tokenKind: RawTokenKind, wholeText: SyntaxText, textRange: Range, presence: SourcePresence, tokenDiagnostic: TokenDiagnostic?) { + init( + tokenKind: RawTokenKind, + wholeText: SyntaxText, + textRange: Range, + presence: SourcePresence, + tokenDiagnostic: TokenDiagnostic? + ) { self.tokenKind = tokenKind self.wholeText = wholeText self.textRange = textRange @@ -560,7 +566,10 @@ extension RawSyntax { presence: presence, tokenDiagnostic: tokenDiagnostic ) - precondition(kind != .keyword || Keyword(payload.tokenText) != nil, "If kind is keyword, the text must be a known token kind") + precondition( + kind != .keyword || Keyword(payload.tokenText) != nil, + "If kind is keyword, the text must be a known token kind" + ) return RawSyntax(arena: arena, payload: .parsedToken(payload)) } @@ -819,13 +828,19 @@ extension RawSyntax { // Find the index of the first non-empty node so we can attach the trivia to it. let idx = layout.firstIndex(where: { $0 != nil && ($0!.isToken || $0!.totalNodes > 1) }) { - layout[idx] = layout[idx]!.withLeadingTrivia(leadingTrivia + (layout[idx]?.formLeadingTrivia() ?? []), arena: arena) + layout[idx] = layout[idx]!.withLeadingTrivia( + leadingTrivia + (layout[idx]?.formLeadingTrivia() ?? []), + arena: arena + ) } if let trailingTrivia = trailingTrivia, // Find the index of the first non-empty node so we can attach the trivia to it. let idx = layout.lastIndex(where: { $0 != nil && ($0!.isToken || $0!.totalNodes > 1) }) { - layout[idx] = layout[idx]!.withTrailingTrivia((layout[idx]?.formTrailingTrivia() ?? []) + trailingTrivia, arena: arena) + layout[idx] = layout[idx]!.withTrailingTrivia( + (layout[idx]?.formTrailingTrivia() ?? []) + trailingTrivia, + arena: arena + ) } return .makeLayout(kind: kind, from: layout, arena: arena) } diff --git a/Sources/SwiftSyntax/SourceLocation.swift b/Sources/SwiftSyntax/SourceLocation.swift index 92cd90bbbf1..243b62177e0 100644 --- a/Sources/SwiftSyntax/SourceLocation.swift +++ b/Sources/SwiftSyntax/SourceLocation.swift @@ -278,7 +278,9 @@ public final class SourceLocationConverter { /// start of file is returned. public func location(for position: AbsolutePosition) -> SourceLocation { let physicalLocation = physicalLocation(for: position) - if let lastSourceLocationDirective = sourceLocationDirectives.last(where: { $0.sourceLine < physicalLocation.line }), + if let lastSourceLocationDirective = + sourceLocationDirectives + .last(where: { $0.sourceLine < physicalLocation.line }), let arguments = lastSourceLocationDirective.arguments { let presumedLine = arguments.line + physicalLocation.line - lastSourceLocationDirective.sourceLine - 1 diff --git a/Sources/SwiftSyntax/Syntax.swift b/Sources/SwiftSyntax/Syntax.swift index 0940ee2dbe6..5763510ab8b 100644 --- a/Sources/SwiftSyntax/Syntax.swift +++ b/Sources/SwiftSyntax/Syntax.swift @@ -187,7 +187,12 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { // If we have a parent already, then ask our current parent to copy itself // recursively up to the root. if let parent { - let newParent = parent.replacingChild(at: indexInParent, with: newRaw, rawNodeArena: rawNodeArena, allocationArena: allocationArena) + let newParent = parent.replacingChild( + at: indexInParent, + with: newRaw, + rawNodeArena: rawNodeArena, + allocationArena: allocationArena + ) return Syntax(absoluteRaw.replacingSelf(newRaw, newRootId: newParent.id.rootId), parent: newParent) } else { // Otherwise, we're already the root, so return the new root data. @@ -207,7 +212,12 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// - Returns: The new root node created by this operation, and the new child /// syntax data. /// - SeeAlso: replacingSelf(_:) - func replacingChild(at index: Int, with newChild: RawSyntax?, rawNodeArena: RetainedSyntaxArena?, allocationArena: SyntaxArena) -> Syntax { + func replacingChild( + at index: Int, + with newChild: RawSyntax?, + rawNodeArena: RetainedSyntaxArena?, + allocationArena: SyntaxArena + ) -> Syntax { precondition(newChild == nil || (rawNodeArena != nil && newChild!.arenaReference == rawNodeArena!)) // After newRaw has been allocated in `allocationArena`, `rawNodeArena` will // be a child arena of `allocationArena` and thus, `allocationArena` will @@ -219,8 +229,18 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { } /// Same as `replacingChild(at:with:rawNodeArena:allocationArena:)` but takes a `__SyntaxArena` instead of a `RetainedSyntaxArena`. - func replacingChild(at index: Int, with newChild: RawSyntax?, rawNodeArena: SyntaxArena?, allocationArena: SyntaxArena) -> Syntax { - return self.replacingChild(at: index, with: newChild, rawNodeArena: rawNodeArena.map(RetainedSyntaxArena.init), allocationArena: allocationArena) + func replacingChild( + at index: Int, + with newChild: RawSyntax?, + rawNodeArena: SyntaxArena?, + allocationArena: SyntaxArena + ) -> Syntax { + return self.replacingChild( + at: index, + with: newChild, + rawNodeArena: rawNodeArena.map(RetainedSyntaxArena.init), + allocationArena: allocationArena + ) } /// Identical to `replacingChild(at: Int, with: RawSyntax?, arena: SyntaxArena)` @@ -228,7 +248,12 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// `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.arenaReference.retained, allocationArena: arena) + return replacingChild( + at: index, + with: newChild?.raw, + rawNodeArena: newChild?.raw.arenaReference.retained, + allocationArena: arena + ) } } diff --git a/Sources/SwiftSyntax/SyntaxArenaAllocatedBuffer.swift b/Sources/SwiftSyntax/SyntaxArenaAllocatedBuffer.swift index d8b46a38e72..a6b505fbb70 100644 --- a/Sources/SwiftSyntax/SyntaxArenaAllocatedBuffer.swift +++ b/Sources/SwiftSyntax/SyntaxArenaAllocatedBuffer.swift @@ -46,7 +46,8 @@ /// reference its contents, we know that the buffer's contents won't get /// deallocated while being accessed and thus we can add an unchecked `Sendable` /// conformance. -@_spi(RawSyntax) public struct SyntaxArenaAllocatedBufferPointer: RandomAccessCollection, @unchecked Sendable { +@_spi(RawSyntax) +public struct SyntaxArenaAllocatedBufferPointer: RandomAccessCollection, @unchecked Sendable { private let buffer: UnsafeBufferPointer /// Create an empty buffer with no elements. @@ -64,7 +65,10 @@ self.buffer = buffer } - @_spi(RawSyntax) public subscript>(range: RangeType) -> SyntaxArenaAllocatedBufferPointer { + @_spi(RawSyntax) + public subscript>( + range: RangeType + ) -> SyntaxArenaAllocatedBufferPointer { return SyntaxArenaAllocatedBufferPointer(UnsafeBufferPointer(rebasing: self.buffer[range])) } diff --git a/Sources/SwiftSyntax/SyntaxChildren.swift b/Sources/SwiftSyntax/SyntaxChildren.swift index c7649e71475..d769e3be780 100644 --- a/Sources/SwiftSyntax/SyntaxChildren.swift +++ b/Sources/SwiftSyntax/SyntaxChildren.swift @@ -367,7 +367,10 @@ struct NonNilRawSyntaxChildren: BidirectionalCollection, Sendable { } // Reversing any further would result in undefined behaviour of // index(before:) - precondition(reversedIndex != children.startIndex, "presentIndex(before:) must not be called if there is no " + "present index before the given one") + precondition( + reversedIndex != children.startIndex, + "presentIndex(before:) must not be called if there is no " + "present index before the given one" + ) reversedIndex = children.index(before: reversedIndex) } } diff --git a/Sources/SwiftSyntax/SyntaxCollection.swift b/Sources/SwiftSyntax/SyntaxCollection.swift index d1c3f5e0f74..e17be71f842 100644 --- a/Sources/SwiftSyntax/SyntaxCollection.swift +++ b/Sources/SwiftSyntax/SyntaxCollection.swift @@ -70,7 +70,9 @@ extension SyntaxCollection { internal func replacingLayout(_ layout: [RawSyntax?]) -> Self { let arena = SyntaxArena() let newRaw = layoutView.replacingLayout(with: layout, arena: arena) - return Syntax(self).replacingSelf(newRaw, rawNodeArena: RetainedSyntaxArena(arena), allocationArena: arena).cast(Self.self) + return Syntax(self) + .replacingSelf(newRaw, rawNodeArena: RetainedSyntaxArena(arena), allocationArena: arena) + .cast(Self.self) } /// Return the index of `node` within this collection. @@ -124,6 +126,7 @@ extension SyntaxCollection { /// /// - Parameter syntax: The element to append. /// - Returns: A new collection with that element appended to the end. + // swift-format-ignore @available(*, deprecated, message: "Create a new array of elements and construct a new collection type from those elements") public func appending(_ syntax: Element) -> Self { var newLayout = layoutView.formLayoutArray() @@ -137,6 +140,7 @@ extension SyntaxCollection { /// - Parameter syntax: The element to prepend. /// - Returns: A new collection with that element prepended to the /// beginning. + // swift-format-ignore @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) @@ -150,6 +154,7 @@ extension SyntaxCollection { /// - index: The index at which to insert the element in the collection. /// /// - Returns: A new collection with that element appended to the end. + // swift-format-ignore @available(*, deprecated, message: "Create a new array of elements and construct a new collection type from those elements") public func inserting(_ syntax: Element, at index: Int) -> Self { var newLayout = layoutView.formLayoutArray() @@ -188,6 +193,7 @@ extension SyntaxCollection { /// - Parameter index: The index of the element to remove from the collection. /// - Returns: A new collection with the element at the provided index /// removed. + // swift-format-ignore @available(*, deprecated, message: "Use filter to remove unwanted elements and construct a new collection type from the filtered elements") public func removing(childAt index: Int) -> Self { var newLayout = layoutView.formLayoutArray() diff --git a/Sources/SwiftSyntax/TokenSequence.swift b/Sources/SwiftSyntax/TokenSequence.swift index 5cb2efecd5a..ef31c2c129c 100644 --- a/Sources/SwiftSyntax/TokenSequence.swift +++ b/Sources/SwiftSyntax/TokenSequence.swift @@ -51,7 +51,11 @@ public struct TokenSequence: Sequence, Sendable { /// 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) + return Iterator( + node.firstToken(viewMode: viewMode), + endToken: node.lastToken(viewMode: viewMode), + viewMode: viewMode + ) } /// Iterate the tokens in reverse order. diff --git a/Sources/SwiftSyntax/TokenSyntax.swift b/Sources/SwiftSyntax/TokenSyntax.swift index d7fd7ae213d..f0cbfca3691 100644 --- a/Sources/SwiftSyntax/TokenSyntax.swift +++ b/Sources/SwiftSyntax/TokenSyntax.swift @@ -111,7 +111,9 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { } let arena = SyntaxArena() let newRaw = tokenView.withKind(newValue, arena: arena) - self = Syntax(self).replacingSelf(newRaw, rawNodeArena: RetainedSyntaxArena(arena), allocationArena: arena).cast(TokenSyntax.self) + self = Syntax(self) + .replacingSelf(newRaw, rawNodeArena: RetainedSyntaxArena(arena), allocationArena: arena) + .cast(TokenSyntax.self) } } diff --git a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift index 181bf97a2a6..90c51e4a926 100644 --- a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift +++ b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift @@ -114,7 +114,9 @@ extension DictionaryExprSyntax { public init( leftSquare: TokenSyntax = .leftSquareToken(), rightSquare: TokenSyntax = .rightSquareToken(), - @DictionaryElementListBuilder contentBuilder: () -> DictionaryElementListSyntax = { DictionaryElementListSyntax([]) } + @DictionaryElementListBuilder contentBuilder: () -> DictionaryElementListSyntax = { + DictionaryElementListSyntax([]) + } ) { let elementList = contentBuilder() self.init( diff --git a/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift b/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift index 42f404303e9..39848d2257f 100644 --- a/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift +++ b/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift @@ -372,7 +372,8 @@ extension Set: ExpressibleByLiteralSyntax where Element: ExpressibleByLiteralSyn } } -extension KeyValuePairs: ExpressibleByLiteralSyntax where Key: ExpressibleByLiteralSyntax, Value: ExpressibleByLiteralSyntax { +extension KeyValuePairs: ExpressibleByLiteralSyntax +where Key: ExpressibleByLiteralSyntax, Value: ExpressibleByLiteralSyntax { public func makeLiteralSyntax() -> DictionaryExprSyntax { DictionaryExprSyntax(leftSquare: .leftSquareToken(), rightSquare: .rightSquareToken()) { for elem in self { @@ -386,7 +387,8 @@ extension KeyValuePairs: ExpressibleByLiteralSyntax where Key: ExpressibleByLite } } -extension Dictionary: ExpressibleByLiteralSyntax where Key: ExpressibleByLiteralSyntax, Value: ExpressibleByLiteralSyntax { +extension Dictionary: ExpressibleByLiteralSyntax +where Key: ExpressibleByLiteralSyntax, Value: ExpressibleByLiteralSyntax { public func makeLiteralSyntax() -> DictionaryExprSyntax { // Dictionaries are unordered. Sort the elements by their keys' source-code representation to emit them in a stable order. let elemSyntaxes = map { diff --git a/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift b/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift index f9d3730e1da..76e19f60dc9 100644 --- a/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift +++ b/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift @@ -81,7 +81,10 @@ public extension HasTrailingCodeBlock where Self: StmtSyntaxProtocol { } extension CatchClauseSyntax: HasTrailingCodeBlock { - public init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax) rethrows { + public init( + _ header: SyntaxNodeString, + @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax + ) rethrows { self = CatchClauseSyntax("\(header) {}") self.body = try CodeBlockSyntax(statements: bodyBuilder()) } @@ -150,11 +153,17 @@ public protocol HasTrailingMemberDeclBlock { /// ``` /// /// Throws an error if `header` defines a different node type than the type the initializer is called on. E.g. if calling `try StructDeclSyntax("class MyClass") {}` - init(_ header: SyntaxNodeString, @MemberBlockItemListBuilder membersBuilder: () throws -> MemberBlockItemListSyntax) throws + init( + _ header: SyntaxNodeString, + @MemberBlockItemListBuilder membersBuilder: () throws -> MemberBlockItemListSyntax + ) throws } public extension HasTrailingMemberDeclBlock where Self: DeclSyntaxProtocol { - init(_ header: SyntaxNodeString, @MemberBlockItemListBuilder membersBuilder: () throws -> MemberBlockItemListSyntax) throws { + init( + _ header: SyntaxNodeString, + @MemberBlockItemListBuilder membersBuilder: () throws -> MemberBlockItemListSyntax + ) throws { let decl = DeclSyntax("\(header) {}") guard let castedDecl = decl.as(Self.self) else { throw SyntaxStringInterpolationInvalidNodeTypeError(expectedType: Self.self, actualNode: decl) @@ -242,7 +251,11 @@ public extension IfExprSyntax { /// ``` /// /// Throws an error if `header` does not start an `if` expression. E.g. if calling `try IfExprSyntax("while true", bodyBuilder: {}, elseIf: {})` - init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax, elseIf: IfExprSyntax) throws { + init( + _ header: SyntaxNodeString, + @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax, + elseIf: IfExprSyntax + ) throws { let expr = ExprSyntax("\(header) {}") guard let ifExpr = expr.as(Self.self) else { throw SyntaxStringInterpolationInvalidNodeTypeError(expectedType: Self.self, actualNode: expr) @@ -275,7 +288,10 @@ extension SwitchCaseSyntax { /// ``` /// /// Throws an error if `header` does not start a switch case item. E.g. if calling `try SwitchCaseSyntax("func foo") {}` - public init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder statementsBuilder: () throws -> CodeBlockItemListSyntax) rethrows { + public init( + _ header: SyntaxNodeString, + @CodeBlockItemListBuilder statementsBuilder: () throws -> CodeBlockItemListSyntax + ) rethrows { self = SwitchCaseSyntax("\(header)") self.statements = try statementsBuilder() } @@ -309,7 +325,10 @@ public extension SwitchExprSyntax { /// ``` /// /// Throws an error if `header` does not start a switch expression. E.g. if calling `try SwitchExprSyntax("if x < 42") {}` - init(_ header: SyntaxNodeString, @SwitchCaseListBuilder casesBuilder: () throws -> SwitchCaseListSyntax = { SwitchCaseListSyntax([]) }) throws { + init( + _ header: SyntaxNodeString, + @SwitchCaseListBuilder casesBuilder: () throws -> SwitchCaseListSyntax = { SwitchCaseListSyntax([]) } + ) throws { let expr = ExprSyntax("\(header) {}") guard let switchExpr = expr.as(Self.self) else { throw SyntaxStringInterpolationInvalidNodeTypeError(expectedType: Self.self, actualNode: expr) diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift b/Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift index cfe89970c82..82500b42703 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift @@ -127,8 +127,10 @@ public func expandFreestandingMacro( if let expansionDecl = node.as(MacroExpansionDeclSyntax.self) { // Strip any indentation from the attributes and modifiers that we are // inheriting. The expanded macro should start at the leftmost column. - let attributes = declMacroDef.propagateFreestandingMacroAttributes ? expansionDecl.attributes.withIndentationRemoved : nil - let modifiers = declMacroDef.propagateFreestandingMacroModifiers ? expansionDecl.modifiers.withIndentationRemoved : nil + let attributes = + declMacroDef.propagateFreestandingMacroAttributes ? expansionDecl.attributes.withIndentationRemoved : nil + let modifiers = + declMacroDef.propagateFreestandingMacroModifiers ? expansionDecl.modifiers.withIndentationRemoved : nil rewritten = rewritten.map { $0.applying(attributes: attributes, modifiers: modifiers) } @@ -145,7 +147,8 @@ public func expandFreestandingMacro( let rewritten = try codeItemMacroDef.expansion(of: node, in: context) expandedSyntax = Syntax(CodeBlockItemListSyntax(rewritten)) - case (.accessor, _), (.memberAttribute, _), (.member, _), (.peer, _), (.conformance, _), (.extension, _), (.expression, _), (.declaration, _), + case (.accessor, _), (.memberAttribute, _), (.member, _), (.peer, _), (.conformance, _), (.extension, _), + (.expression, _), (.declaration, _), (.codeItem, _), (.preamble, _), (.body, _): throw MacroExpansionError.unmatchedMacroRole(definition, macroRole) } @@ -310,7 +313,9 @@ public func expandAttachedMacroWithoutCollapsing } case (let attachedMacro as PreambleMacro.Type, .preamble): - guard let declToPass = Syntax(declarationNode).asProtocol(SyntaxProtocol.self) as? (DeclSyntaxProtocol & WithOptionalCodeBlockSyntax) + guard + let declToPass = Syntax(declarationNode).asProtocol(SyntaxProtocol.self) + as? (DeclSyntaxProtocol & WithOptionalCodeBlockSyntax) else { // Compiler error: declaration must have a body. throw MacroExpansionError.declarationHasNoBody @@ -326,7 +331,9 @@ public func expandAttachedMacroWithoutCollapsing } case (let attachedMacro as BodyMacro.Type, .body): - guard let declToPass = Syntax(declarationNode).asProtocol(SyntaxProtocol.self) as? (DeclSyntaxProtocol & WithOptionalCodeBlockSyntax) + guard + let declToPass = Syntax(declarationNode).asProtocol(SyntaxProtocol.self) + as? (DeclSyntaxProtocol & WithOptionalCodeBlockSyntax) else { // Compiler error: declaration must have a body. throw MacroExpansionError.declarationHasNoBody diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift b/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift index 5a03bf218c8..a1ee7070e0d 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift @@ -68,7 +68,11 @@ public enum MacroDefinition { /// defining macro. These subtrees will need to be replaced with the text of /// the corresponding argument to the macro, which can be accomplished with /// `MacroDeclSyntax.expandDefinition`. - case expansion(MacroExpansionExprSyntax, replacements: [Replacement], genericReplacements: [GenericArgumentReplacement]) + case expansion( + MacroExpansionExprSyntax, + replacements: [Replacement], + genericReplacements: [GenericArgumentReplacement] + ) } extension MacroDefinition { diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift index 5d46aee2089..7c5aaf9ea09 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift @@ -155,7 +155,10 @@ private func expandFreestandingExpr( /// Adds the appropriate indentation on expanded code even if it's multi line. /// Makes sure original macro expression's trivia is maintained by adding it to expanded code. -private func adjustIndentationOfFreestandingMacro(expandedCode: String, node: some FreestandingMacroExpansionSyntax) -> String { +private func adjustIndentationOfFreestandingMacro( + expandedCode: String, + node: some FreestandingMacroExpansionSyntax +) -> String { if expandedCode.isEmpty { return expandedCode.wrappingInTrivia(from: node) @@ -470,7 +473,8 @@ private func expandBodyMacro( // prepend a space when it's being introduced on a declaration that has no // body yet. let leadingWhitespace = decl.body == nil ? " " : "" - let indentedSource = leadingWhitespace + expanded.indented(by: decl.indentationOfFirstLine).drop(while: { $0.isWhitespace }) + let indentedSource = + leadingWhitespace + expanded.indented(by: decl.indentationOfFirstLine).drop(while: { $0.isWhitespace }) return "\(raw: indentedSource)" } @@ -574,7 +578,9 @@ public class AttributeRemover: SyntaxRewriter { if !triviaToAttachToNextToken.isEmpty { triviaToAttachToNextToken = triviaToAttachToNextToken.trimmingSuffix(while: \.isSpaceOrTab) } else if let lastAttribute = filteredAttributes.last { - filteredAttributes[filteredAttributes.count - 1].trailingTrivia = lastAttribute.trailingTrivia.trimmingSuffix(while: \.isSpaceOrTab) + filteredAttributes[filteredAttributes.count - 1].trailingTrivia = lastAttribute + .trailingTrivia + .trimmingSuffix(while: \.isSpaceOrTab) } } return AttributeListSyntax(filteredAttributes) @@ -722,7 +728,10 @@ private class MacroApplication: SyntaxRewriter { _ node: Node ) -> Node { // Expand preamble macros into a set of code items. - let preamble = expandMacros(attachedTo: DeclSyntax(node), ofType: PreambleMacro.Type.self) { attributeNode, definition, _ in + let preamble = expandMacros( + attachedTo: DeclSyntax(node), + ofType: PreambleMacro.Type.self + ) { attributeNode, definition, _ in expandPreambleMacro( definition: definition, attributeNode: attributeNode, @@ -733,7 +742,10 @@ private class MacroApplication: SyntaxRewriter { } // Expand body macro. - let expandedBodies = expandMacros(attachedTo: DeclSyntax(node), ofType: BodyMacro.Type.self) { attributeNode, definition, _ in + let expandedBodies = expandMacros( + attachedTo: DeclSyntax(node), + ofType: BodyMacro.Type.self + ) { attributeNode, definition, _ in expandBodyMacro( definition: definition, attributeNode: attributeNode, @@ -912,7 +924,10 @@ private class MacroApplication: SyntaxRewriter { } guard node.bindings.count == 1, let binding = node.bindings.first else { - contextGenerator(Syntax(node)).addDiagnostics(from: MacroApplicationError.accessorMacroOnVariableWithMultipleBindings, node: node) + contextGenerator(Syntax(node)).addDiagnostics( + from: MacroApplicationError.accessorMacroOnVariableWithMultipleBindings, + node: node + ) return DeclSyntax(node) } @@ -983,21 +998,30 @@ extension MacroApplication { } /// Call `expandMacro` for every macro of type `ofType` attached to `decl` and - /// return the list of all expaned nodes. + /// return the list of all expanded nodes. private func expandMacros< ExpandedNode: SyntaxProtocol, - ExpanedNodeCollection: Sequence, + ExpandedNodeCollection: Sequence, MacroType >( attachedTo decl: DeclSyntax, ofType: MacroType.Type, - expandMacro: (_ attributeNode: AttributeSyntax, _ definition: MacroType, _ conformanceList: InheritedTypeListSyntax) throws -> ExpanedNodeCollection? + expandMacro: + ( + _ attributeNode: AttributeSyntax, + _ definition: MacroType, + _ conformanceList: InheritedTypeListSyntax + ) throws -> ExpandedNodeCollection? ) -> [ExpandedNode] { var result: [ExpandedNode] = [] for macroAttribute in macroAttributes(attachedTo: decl, ofType: ofType) { do { - if let expanded = try expandMacro(macroAttribute.attributeNode, macroAttribute.definition, macroAttribute.conformanceList) { + if let expanded = try expandMacro( + macroAttribute.attributeNode, + macroAttribute.definition, + macroAttribute.conformanceList + ) { result += expanded } } catch { @@ -1050,7 +1074,10 @@ extension MacroApplication { /// /// - Returns: The macro-synthesized extensions private func expandExtensions(of decl: DeclSyntax) -> [CodeBlockItemSyntax] { - return expandMacros(attachedTo: decl, ofType: ExtensionMacro.Type.self) { attributeNode, definition, conformanceList in + return expandMacros( + attachedTo: decl, + ofType: ExtensionMacro.Type.self + ) { attributeNode, definition, conformanceList in return try expandExtensionMacro( definition: definition, attributeNode: attributeNode, @@ -1085,7 +1112,10 @@ extension MacroApplication { of decl: DeclSyntax, parentDecl: DeclSyntax ) -> [AttributeListSyntax.Element] { - return expandMacros(attachedTo: parentDecl, ofType: MemberAttributeMacro.Type.self) { attributeNode, definition, conformanceList in + return expandMacros( + attachedTo: parentDecl, + ofType: MemberAttributeMacro.Type.self + ) { attributeNode, definition, conformanceList in return try expandMemberAttributeMacro( definition: definition, attributeNode: attributeNode, diff --git a/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift b/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift index bdf61d913e9..586ae269aaf 100644 --- a/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift +++ b/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift @@ -116,7 +116,10 @@ extension MacroExpansionContext { } else if let message = error as? DiagnosticMessage { diagnostics = [Diagnostic(node: Syntax(node), message: message)] } else if let error = error as? SyntaxStringInterpolationInvalidNodeTypeError { - let diagnostic = Diagnostic(node: Syntax(node), message: ThrownErrorDiagnostic(message: "Internal macro error: \(error.description)")) + let diagnostic = Diagnostic( + node: Syntax(node), + message: ThrownErrorDiagnostic(message: "Internal macro error: \(error.description)") + ) diagnostics = [diagnostic] } else { diagnostics = [Diagnostic(node: Syntax(node), message: ThrownErrorDiagnostic(message: String(describing: error)))] diff --git a/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift b/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift index 6ad8ca9fe22..b7366e21e0f 100644 --- a/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift +++ b/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift @@ -79,10 +79,28 @@ func assertNote( in expansionContext: BasicMacroExpansionContext, expected spec: NoteSpec ) { - assertStringsEqualWithDiff(note.message, spec.message, "message of note does not match", file: spec.originatorFile, line: spec.originatorLine) + assertStringsEqualWithDiff( + note.message, + spec.message, + "message of note does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) let location = expansionContext.location(for: note.position, anchoredAt: note.node, fileName: "") - XCTAssertEqual(location.line, spec.line, "line of note does not match", file: spec.originatorFile, line: spec.originatorLine) - XCTAssertEqual(location.column, spec.column, "column of note does not match", file: spec.originatorFile, line: spec.originatorLine) + XCTAssertEqual( + location.line, + spec.line, + "line of note does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) + XCTAssertEqual( + location.column, + spec.column, + "column of note does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) } // MARK: - Fix-It @@ -120,7 +138,13 @@ func assertFixIt( _ fixIt: FixIt, expected spec: FixItSpec ) { - assertStringsEqualWithDiff(fixIt.message.message, spec.message, "message of Fix-It does not match", file: spec.originatorFile, line: spec.originatorLine) + assertStringsEqualWithDiff( + fixIt.message.message, + spec.message, + "message of Fix-It does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) } // MARK: - Diagnostic @@ -202,8 +226,9 @@ extension DiagnosticSpec { return highlights.joined(separator: " ") } - @_disfavoredOverload + // swift-format-ignore @available(*, deprecated, message: "Use init(id:message:line:column:severity:highlights:notes:fixIts:originatorFile:originatorLine:) instead") + @_disfavoredOverload public init( id: MessageID? = nil, message: String, @@ -235,14 +260,38 @@ func assertDiagnostic( expected spec: DiagnosticSpec ) { if let id = spec.id { - XCTAssertEqual(diag.diagnosticID, id, "diagnostic ID does not match", file: spec.originatorFile, line: spec.originatorLine) + XCTAssertEqual( + diag.diagnosticID, + id, + "diagnostic ID does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) } - assertStringsEqualWithDiff(diag.message, spec.message, "message does not match", file: spec.originatorFile, line: spec.originatorLine) + assertStringsEqualWithDiff( + diag.message, + spec.message, + "message does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) let location = expansionContext.location(for: diag.position, anchoredAt: diag.node, fileName: "") XCTAssertEqual(location.line, spec.line, "line does not match", file: spec.originatorFile, line: spec.originatorLine) - XCTAssertEqual(location.column, spec.column, "column does not match", file: spec.originatorFile, line: spec.originatorLine) + XCTAssertEqual( + location.column, + spec.column, + "column does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) - XCTAssertEqual(spec.severity, diag.diagMessage.severity, "severity does not match", file: spec.originatorFile, line: spec.originatorLine) + XCTAssertEqual( + spec.severity, + diag.diagMessage.severity, + "severity does not match", + file: spec.originatorFile, + line: spec.originatorLine + ) if let highlights = spec.highlights { if diag.highlights.count != highlights.count { @@ -384,7 +433,11 @@ public func assertMacroExpansion( return BasicMacroExpansionContext(sharingWith: context, lexicalContext: syntax.allMacroLexicalContexts()) } - let expandedSourceFile = origSourceFile.expand(macroSpecs: macroSpecs, contextGenerator: contextGenerator, indentationWidth: indentationWidth) + let expandedSourceFile = origSourceFile.expand( + macroSpecs: macroSpecs, + contextGenerator: contextGenerator, + indentationWidth: indentationWidth + ) let diags = ParseDiagnosticsGenerator.diagnostics(for: expandedSourceFile) if !diags.isEmpty { XCTFail( diff --git a/Sources/_SwiftSyntaxTestSupport/IncrementalParseTestUtils.swift b/Sources/_SwiftSyntaxTestSupport/IncrementalParseTestUtils.swift index ac67ffc4f1e..8a2a65905ee 100644 --- a/Sources/_SwiftSyntaxTestSupport/IncrementalParseTestUtils.swift +++ b/Sources/_SwiftSyntaxTestSupport/IncrementalParseTestUtils.swift @@ -99,7 +99,8 @@ public func assertIncrementalParse( var lastRangeUpperBound = originalString.startIndex for expectedReusedNode in expectedReusedNodes { - guard let range = byteSourceRange(for: expectedReusedNode.source, in: originalString, after: lastRangeUpperBound) else { + guard let range = byteSourceRange(for: expectedReusedNode.source, in: originalString, after: lastRangeUpperBound) + else { XCTFail("Fail to find string in original source,", file: expectedReusedNode.file, line: expectedReusedNode.line) continue } @@ -170,7 +171,9 @@ public struct ReusedNodeSpec { /// Contents between `⏩️` and `⏸️` are source text that before modification, contents /// betwwen `⏸️` and `⏪️` are source text that after modification /// i.e. `⏩️foo⏸️bar⏪️`, the original source is `foo` and the edited source is `bar` -public func extractEditsAndSources(from source: String) -> (edits: ConcurrentEdits, orignialSource: Substring, editedSource: Substring) { +public func extractEditsAndSources( + from source: String +) -> (edits: ConcurrentEdits, originalSource: Substring, editedSource: Substring) { var editedSource = Substring() var originalSource = Substring() var concurrentEdits: [IncrementalEdit] = [] @@ -206,7 +209,9 @@ public func extractEditsAndSources(from source: String) -> (edits: ConcurrentEdi let edits = try ConcurrentEdits(concurrent: concurrentEdits) return (edits, originalSource, editedSource) } catch { - fatalError("ConcurrentEdits created by the test case do not satisfy ConcurrentEdits requirements, please check the test setup") + fatalError( + "ConcurrentEdits created by the test case do not satisfy ConcurrentEdits requirements, please check the test setup" + ) } } diff --git a/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift b/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift index e48bf6dc367..fd3dbf98294 100644 --- a/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift +++ b/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift @@ -13,6 +13,9 @@ 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: [" "]) + return + self + .replacingOccurrences(of: "[ ]+\\n", with: "\n", options: .regularExpression) + .trimmingCharacters(in: [" "]) } } diff --git a/Sources/_SwiftSyntaxTestSupport/Syntax+Assertions.swift b/Sources/_SwiftSyntaxTestSupport/Syntax+Assertions.swift index 3dfd5655f02..60aa6e8f9c3 100644 --- a/Sources/_SwiftSyntaxTestSupport/Syntax+Assertions.swift +++ b/Sources/_SwiftSyntaxTestSupport/Syntax+Assertions.swift @@ -101,14 +101,28 @@ public struct SubtreeMatcher { /// Same as `Syntax.findFirstDifference(baseline:includeTrivia:)`, but /// matches against the first subtree from parsing `markedText` that is after /// `afterMarker` with the root matching the root type of `baseline`. - public func findFirstDifference(afterMarker: String? = nil, baseline: some SyntaxProtocol, includeTrivia: Bool = false) throws -> TreeDifference? { + public func findFirstDifference( + afterMarker: String? = nil, + baseline: some SyntaxProtocol, + includeTrivia: Bool = false + ) throws -> TreeDifference? { let afterMarker = afterMarker ?? markers.first!.key guard let subtreeStart = markers[afterMarker] else { throw SubtreeError.invalidMarker(name: afterMarker) } - guard let subtree = SyntaxTypeFinder.findFirstNode(in: actualTree, afterUTF8Offset: subtreeStart, ofType: baseline.syntaxNodeType) else { - throw SubtreeError.invalidSubtree(tree: actualTree, afterUTF8Offset: subtreeStart, type: String(describing: baseline.syntaxNodeType)) + guard + let subtree = SyntaxTypeFinder.findFirstNode( + in: actualTree, + afterUTF8Offset: subtreeStart, + ofType: baseline.syntaxNodeType + ) + else { + throw SubtreeError.invalidSubtree( + tree: actualTree, + afterUTF8Offset: subtreeStart, + type: String(describing: baseline.syntaxNodeType) + ) } return subtree.findFirstDifference(baseline: baseline, includeTrivia: includeTrivia) @@ -150,7 +164,8 @@ public enum SubtreeError: Error, CustomStringConvertible { case let .invalidMarker(name): return "Could not find marker with name '\(name)'" case let .invalidSubtree(tree, afterUTF8Offset, type): - return "Could not find subtree after UTF8 offset \(afterUTF8Offset) with type \(type) in:\n\(tree.debugDescription)" + return + "Could not find subtree after UTF8 offset \(afterUTF8Offset) with type \(type) in:\n\(tree.debugDescription)" } } } @@ -180,7 +195,11 @@ fileprivate class SyntaxTypeFinder: SyntaxAnyVisitor { return .visitChildren } - public static func findFirstNode(in tree: Syntax, afterUTF8Offset offset: Int, ofType type: SyntaxProtocol.Type) -> Syntax? { + public static func findFirstNode( + in tree: Syntax, + afterUTF8Offset offset: Int, + ofType type: SyntaxProtocol.Type + ) -> Syntax? { let finder = SyntaxTypeFinder(offset: offset, type: type) finder.walk(tree) return finder.found diff --git a/Sources/_SwiftSyntaxTestSupport/SyntaxComparison.swift b/Sources/_SwiftSyntaxTestSupport/SyntaxComparison.swift index 66976735200..883ca0ed182 100644 --- a/Sources/_SwiftSyntaxTestSupport/SyntaxComparison.swift +++ b/Sources/_SwiftSyntaxTestSupport/SyntaxComparison.swift @@ -129,7 +129,10 @@ public extension SyntaxProtocol { if token.tokenKind != baselineToken.tokenKind { return .token } - if includeTrivia && (token.leadingTrivia != baselineToken.leadingTrivia || token.trailingTrivia != baselineToken.trailingTrivia) { + if includeTrivia + && (token.leadingTrivia != baselineToken.leadingTrivia + || token.trailingTrivia != baselineToken.trailingTrivia) + { return .trivia } } diff --git a/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift b/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift index ce210069984..1e3955b74ee 100644 --- a/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift +++ b/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift @@ -27,7 +27,10 @@ private class InitializerExprFormat: BasicFormat { super.init(indentationWidth: .spaces(2)) } - private func formatChildrenSeparatedByNewline(children: SyntaxChildren, elementType: SyntaxType.Type) -> [SyntaxType] { + private func formatChildrenSeparatedByNewline( + children: SyntaxChildren, + elementType: SyntaxType.Type + ) -> [SyntaxType] { increaseIndentationLevel() var formattedChildren = children.map { self.rewrite($0.cast(SyntaxType.self)).cast(SyntaxType.self) @@ -41,7 +44,8 @@ private class InitializerExprFormat: BasicFormat { } decreaseIndentationLevel() if !formattedChildren.isEmpty { - formattedChildren[formattedChildren.count - 1] = formattedChildren[formattedChildren.count - 1].with(\.trailingTrivia, .newline + currentIndentationLevel) + formattedChildren[formattedChildren.count - 1] = formattedChildren[formattedChildren.count - 1] + .with(\.trailingTrivia, .newline + currentIndentationLevel) } return formattedChildren } @@ -49,12 +53,16 @@ private class InitializerExprFormat: BasicFormat { override func visit(_ node: LabeledExprListSyntax) -> LabeledExprListSyntax { let children = node.children(viewMode: .all) // If the function only takes a single argument, display it on the same line - if let callee = node.parent?.as(FunctionCallExprSyntax.self)?.calledExpression.as(MemberAccessExprSyntax.self), callee.base == nil { + if let callee = node.parent?.as(FunctionCallExprSyntax.self)?.calledExpression.as(MemberAccessExprSyntax.self), + callee.base == nil + { // This is a constructor for tokens. Write them on a single line return super.visit(node) } if children.count > 1 { - return LabeledExprListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: LabeledExprSyntax.self)) + return LabeledExprListSyntax( + formatChildrenSeparatedByNewline(children: children, elementType: LabeledExprSyntax.self) + ) } else { return super.visit(node) } @@ -64,7 +72,9 @@ private class InitializerExprFormat: BasicFormat { let children = node.children(viewMode: .all) // Short array literals are presented on one line, list each element on a different line. if node.description.count > 30 { - return ArrayElementListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: ArrayElementSyntax.self)) + return ArrayElementListSyntax( + formatChildrenSeparatedByNewline(children: children, elementType: ArrayElementSyntax.self) + ) } else { return super.visit(node) } @@ -147,7 +157,9 @@ extension SyntaxProtocol { LabeledExprSyntax( expression: ArrayExprSyntax { for child in self.children(viewMode: .all) { - ArrayElementSyntax(expression: child.as(collectionElementType)!.debugInitCallExpr(includeTrivia: includeTrivia)) + ArrayElementSyntax( + expression: child.as(collectionElementType)!.debugInitCallExpr(includeTrivia: includeTrivia) + ) } } ) diff --git a/SwiftParserCLI/Sources/swift-parser-cli/BasicFormat.swift b/SwiftParserCLI/Sources/swift-parser-cli/BasicFormat.swift index 0588e1843c1..de4e41047c2 100644 --- a/SwiftParserCLI/Sources/swift-parser-cli/BasicFormat.swift +++ b/SwiftParserCLI/Sources/swift-parser-cli/BasicFormat.swift @@ -91,7 +91,9 @@ struct BasicFormat: ParsableCommand, ParseCommand { ) } - let formattedTree = resultTree.formatted(using: SwiftBasicFormat.BasicFormat(indentationWidth: .spaces(indentationWidth))) + let formattedTree = resultTree.formatted( + using: SwiftBasicFormat.BasicFormat(indentationWidth: .spaces(indentationWidth)) + ) print(formattedTree.description) } diff --git a/SwiftParserCLI/Sources/swift-parser-cli/Commands/Reduce.swift b/SwiftParserCLI/Sources/swift-parser-cli/Commands/Reduce.swift index 43921838359..393df87845d 100644 --- a/SwiftParserCLI/Sources/swift-parser-cli/Commands/Reduce.swift +++ b/SwiftParserCLI/Sources/swift-parser-cli/Commands/Reduce.swift @@ -30,7 +30,8 @@ fileprivate func withTemporaryFile(contents: [UInt8], body: (URL) throws -> T struct Reduce: ParsableCommand { static var configuration = CommandConfiguration( commandName: "reduce", - abstract: "Reduce a test case that crashes the parser or fails to round-trip to a smaller test case that still reproduces the issue" + abstract: + "Reduce a test case that crashes the parser or fails to round-trip to a smaller test case that still reproduces the issue" ) @Argument(help: "The test case that should be reduced; if omitted, use stdin") @@ -154,7 +155,8 @@ struct Reduce: ParsableCommand { // Characters that stil need to be checked whether they can be removed. var remaining = source while !remaining.isEmpty { - let index = remaining.index(remaining.startIndex, offsetBy: chunkSize, limitedBy: remaining.endIndex) ?? remaining.endIndex + let index = + remaining.index(remaining.startIndex, offsetBy: chunkSize, limitedBy: remaining.endIndex) ?? remaining.endIndex let testChunk = [UInt8](remaining[.. [URL] { - guard let enumerator = FileManager.default.enumerator(at: Paths.packageDir.resolvingSymlinksInPath(), includingPropertiesForKeys: [], options: []) else { + guard + let enumerator = FileManager.default.enumerator( + at: Paths.packageDir.resolvingSymlinksInPath(), + includingPropertiesForKeys: [], + options: [] + ) + else { return [] } @@ -265,7 +271,9 @@ struct FormatExecutor { func run() throws { #if compiler(<5.10) - print("💡 You are building running the format script with Swift 5.9 or lower. Running it with SwiftPM 5.10 is about 10s faster.") + print( + "💡 You are building running the format script with Swift 5.9 or lower. Running it with SwiftPM 5.10 is about 10s faster." + ) #endif try run(updateAndBuild: update) diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/LocalPrPrecheck.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/LocalPrPrecheck.swift index f791d177922..3eec83dc46d 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/LocalPrPrecheck.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/LocalPrPrecheck.swift @@ -45,8 +45,12 @@ struct LocalPrPrecheckExecutor { init(toolchain: URL, verbose: Bool = false) { self.formatExecutor = FormatExecutor(update: false, verbose: verbose) self.generateSourceCodeExecutor = GenerateSourceCodeExecutor(toolchain: toolchain, verbose: verbose) - self.buildExecutor = BuildExecutor(swiftPMBuilder: SwiftPMBuilder(toolchain: toolchain, useLocalDeps: false, verbose: verbose)) - self.testExecutor = TestExecutor(swiftPMBuilder: SwiftPMBuilder(toolchain: toolchain, useLocalDeps: false, verbose: verbose)) + self.buildExecutor = BuildExecutor( + swiftPMBuilder: SwiftPMBuilder(toolchain: toolchain, useLocalDeps: false, verbose: verbose) + ) + self.testExecutor = TestExecutor( + swiftPMBuilder: SwiftPMBuilder(toolchain: toolchain, useLocalDeps: false, verbose: verbose) + ) } func run() throws { diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Utils.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Utils.swift index 78ee028897e..830d65e9536 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Utils.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Utils.swift @@ -29,9 +29,10 @@ func withTemporaryDirectory(_ body: (URL) throws -> T) throws -> T { func defaultToolchain() -> URL? { #if os(macOS) do { - let swiftcPath = try ProcessRunner(executableURL: try Paths.xcrunExec, arguments: ["--find", "swiftc"]).run(verbose: false).stdout.trimmingCharacters( - in: .whitespacesAndNewlines - ) + let swiftcPath = try ProcessRunner(executableURL: try Paths.xcrunExec, arguments: ["--find", "swiftc"]) + .run(verbose: false) + .stdout + .trimmingCharacters(in: .whitespacesAndNewlines) if swiftcPath.isEmpty { return nil } diff --git a/Tests/PerformanceTest/InstructionsCountAssertion.swift b/Tests/PerformanceTest/InstructionsCountAssertion.swift index edc41c34c9c..b14d15c14f5 100644 --- a/Tests/PerformanceTest/InstructionsCountAssertion.swift +++ b/Tests/PerformanceTest/InstructionsCountAssertion.swift @@ -23,7 +23,12 @@ fileprivate var baselineURL: URL { } } -func measureInstructions(_ baselineName: StaticString = #function, block: () -> Void, file: StaticString = #filePath, line: UInt = #line) throws { +func measureInstructions( + _ baselineName: StaticString = #function, + block: () -> Void, + file: StaticString = #filePath, + line: UInt = #line +) throws { let startInstructions = getInstructionsExecuted() block() let endInstructions = getInstructionsExecuted() diff --git a/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift b/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift index 76ba6fef82a..6a6864f6bca 100644 --- a/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift +++ b/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift @@ -182,7 +182,11 @@ final class GroupedDiagnosticsFormatterTests: XCTestCase { displayName: "#myAssert", parent: (mainSourceID, inExpansionNotePos), diagnosticDescriptors: [ - DiagnosticDescriptor(locationMarker: "1️⃣", message: "in expansion of macro 'invertedEqualityCheck' here", severity: .note) + DiagnosticDescriptor( + locationMarker: "1️⃣", + message: "in expansion of macro 'invertedEqualityCheck' here", + severity: .note + ) ] ) let inInnerExpansionNotePos = outerExpansionSourceMarkers["1️⃣"]! @@ -195,7 +199,11 @@ final class GroupedDiagnosticsFormatterTests: XCTestCase { displayName: "#invertedEqualityCheck", parent: (outerExpansionSourceID, inInnerExpansionNotePos), diagnosticDescriptors: [ - DiagnosticDescriptor(locationMarker: "1️⃣", message: "no matching operator '==' for types 'Double' and 'Int'", severity: .error) + DiagnosticDescriptor( + locationMarker: "1️⃣", + message: "no matching operator '==' for types 'Double' and 'Int'", + severity: .error + ) ] ) diff --git a/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift b/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift index 4240c5350dd..b21399783b3 100644 --- a/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift +++ b/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift @@ -58,7 +58,12 @@ private func assertNameMatcherResult( let actualArgumentLabels = argumentLabels.map { input[$0.range] } XCTAssertEqual(actualArgumentLabels, expected.arguments, file: file, line: expected.originatorLine) - XCTAssertEqual(DeclNameLocationSpec.ArgumentsType(actual.arguments), expected.type, file: file, line: expected.originatorLine) + XCTAssertEqual( + DeclNameLocationSpec.ArgumentsType(actual.arguments), + expected.type, + file: file, + line: expected.originatorLine + ) XCTAssertEqual(actual.isActive, expected.isActive, file: file, line: expected.originatorLine) XCTAssertEqual(actual.context, expected.context, file: file, line: expected.originatorLine) } diff --git a/Tests/SwiftParserTest/Assertions.swift b/Tests/SwiftParserTest/Assertions.swift index e9230aca36c..8514e75ed56 100644 --- a/Tests/SwiftParserTest/Assertions.swift +++ b/Tests/SwiftParserTest/Assertions.swift @@ -661,11 +661,22 @@ extension ParserTestCase { } if expectedDiagnostics.allSatisfy({ $0.fixIts.isEmpty }) && expectedFixedSource != nil { - XCTFail("Fixed source was provided but the test case produces no diagnostics with Fix-Its", file: file, line: line) + XCTFail( + "Fixed source was provided but the test case produces no diagnostics with Fix-Its", + file: file, + line: line + ) } if expectedDiagnostics.isEmpty && diags.isEmpty { - assertBasicFormat(source: source, parse: parse, swiftVersion: swiftVersion, experimentalFeatures: experimentalFeatures, file: file, line: line) + assertBasicFormat( + source: source, + parse: parse, + swiftVersion: swiftVersion, + experimentalFeatures: experimentalFeatures, + file: file, + line: line + ) } if !longTestsDisabled { @@ -683,12 +694,17 @@ extension ParserTestCase { } #if SWIFTPARSER_ENABLE_ALTERNATE_TOKEN_INTROSPECTION - let mutations: [(offset: Int, replacement: TokenSpec)] = parser.alternativeTokenChoices.flatMap { offset, replacements in + let mutations: [(offset: Int, replacement: TokenSpec)] = parser.alternativeTokenChoices.flatMap { + offset, + replacements in return replacements.map { (offset, $0) } } DispatchQueue.concurrentPerform(iterations: mutations.count) { index in let mutation = mutations[index] - let alternateSource = MutatedTreePrinter.print(tree: Syntax(tree), mutations: [mutation.offset: mutation.replacement]) + let alternateSource = MutatedTreePrinter.print( + tree: Syntax(tree), + mutations: [mutation.offset: mutation.replacement] + ) Self.assertMutationRoundTrip( source: alternateSource, parse, @@ -744,7 +760,11 @@ func assertBasicFormat( let withoutTrivia = TriviaRemover(viewMode: .sourceAccurate).rewrite(sourceTree) let formatted = withoutTrivia.formatted() - var formattedParser = Parser(formatted.description, swiftVersion: swiftVersion, experimentalFeatures: experimentalFeatures) + var formattedParser = Parser( + formatted.description, + swiftVersion: swiftVersion, + experimentalFeatures: experimentalFeatures + ) let formattedReparsed = Syntax(parse(&formattedParser)) do { diff --git a/Tests/SwiftParserTest/AttributeTests.swift b/Tests/SwiftParserTest/AttributeTests.swift index 0fd48e2d29a..c1da7778ff2 100644 --- a/Tests/SwiftParserTest/AttributeTests.swift +++ b/Tests/SwiftParserTest/AttributeTests.swift @@ -54,7 +54,10 @@ final class AttributeTests: ParserTestCase { message: "expected ':' and arguments in '@differentiable' argument", fixIts: ["insert ':' and arguments"] ), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected ':' or '==' to indicate a conformance or same-type requirement"), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected ':' or '==' to indicate a conformance or same-type requirement" + ), DiagnosticSpec( locationMarker: "2️⃣", message: "expected ')' to end attribute", @@ -581,7 +584,10 @@ final class AttributeTests: ParserTestCase { func foo() {} """, diagnostics: [ - DiagnosticSpec(message: "expected 'message' in @_unavailableFromAsync argument", fixIts: ["replace 'nope' with 'message'"]) + DiagnosticSpec( + message: "expected 'message' in @_unavailableFromAsync argument", + fixIts: ["replace 'nope' with 'message'"] + ) ], fixedSource: """ @_unavailableFromAsync(message: "abc") @@ -658,7 +664,9 @@ final class AttributeTests: ParserTestCase { assertParse("@_documentation(visibility: internal) @_exported import A") assertParse("@_documentation(metadata: cool_stuff) public class SomeClass {}") assertParse(#"@_documentation(metadata: "this is a longer string") public class OtherClass {}"#) - assertParse(#"@_documentation(visibility: internal, metadata: "this is a longer string") public class OtherClass {}"#) + assertParse( + #"@_documentation(visibility: internal, metadata: "this is a longer string") public class OtherClass {}"# + ) } func testSendable() { diff --git a/Tests/SwiftParserTest/DeclarationTests.swift b/Tests/SwiftParserTest/DeclarationTests.swift index e4c085a9c32..bd01a9d7f3e 100644 --- a/Tests/SwiftParserTest/DeclarationTests.swift +++ b/Tests/SwiftParserTest/DeclarationTests.swift @@ -60,7 +60,11 @@ final class DeclarationTests: ParserTestCase { 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 ':' and type in parameter", + fixIts: ["insert ':' and type"] + ), DiagnosticSpec(locationMarker: "3️⃣", message: "expected ')' to end parameter clause", fixIts: ["insert ')'"]), ], fixedSource: """ @@ -124,7 +128,11 @@ final class DeclarationTests: ParserTestCase { message: "expected 'func' in function", fixIts: ["insert 'func'"] ), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected parameter clause in function signature", + fixIts: ["insert parameter clause"] + ), ], fixedSource: """ class MyClass { @@ -337,7 +345,10 @@ final class DeclarationTests: ParserTestCase { assertParse( "_ = foo/* */?.description1️⃣", diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]) + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ) ], fixedSource: """ _ = foo/* */?.description : <#expression#> @@ -964,7 +975,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() throws 1️⃣async2️⃣(MyError) {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'async' must precede 'throws'", fixIts: ["move 'async' in front of 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'async' must precede 'throws'", + fixIts: ["move 'async' in front of 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in function"), ], fixedSource: "func test() async throws (MyError) {}" @@ -973,7 +988,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() 1️⃣try2️⃣(MyError) async {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError) async' in function"), ], fixedSource: "func test() throws (MyError) async {}" @@ -982,8 +1001,16 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() 1️⃣try 2️⃣async3️⃣(MyError) {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "'async' must precede 'throws'", fixIts: ["move 'async' in front of 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "'async' must precede 'throws'", + fixIts: ["move 'async' in front of 'throws'"] + ), DiagnosticSpec(locationMarker: "3️⃣", message: "unexpected code '(MyError)' in function"), ], fixedSource: "func test() async throws (MyError) {}" @@ -992,7 +1019,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() throws(MyError) 1️⃣await {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'await' must precede 'throws'", fixIts: ["move 'await' in front of 'throws'"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'await' must precede 'throws'", + fixIts: ["move 'await' in front of 'throws'"] + ) ], fixedSource: "func test() async throws(MyError) {}" ) @@ -1000,7 +1031,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() throws 1️⃣await2️⃣(MyError) {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'await' must precede 'throws'", fixIts: ["move 'await' in front of 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'await' must precede 'throws'", + fixIts: ["move 'await' in front of 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in function"), ], fixedSource: "func test() async throws (MyError) {}" @@ -1009,7 +1044,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() 1️⃣try2️⃣(MyError) await {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError) await' in function"), ], fixedSource: "func test() throws (MyError) await {}" @@ -1018,7 +1057,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() 1️⃣try await2️⃣(MyError) {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in function"), ], fixedSource: "func test() awaitthrows (MyError) {}" // FIXME: spacing @@ -1034,7 +1077,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() 1️⃣await2️⃣(MyError) {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'await' with 'async'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'await' with 'async'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in function"), ], fixedSource: "func test() async (MyError) {}" @@ -1043,7 +1090,11 @@ final class DeclarationTests: ParserTestCase { assertParse( "func test() 1️⃣try2️⃣(MyError) {}", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in function"), ], fixedSource: "func test() throws (MyError) {}" @@ -1111,8 +1162,14 @@ final class DeclarationTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } @@ -1133,7 +1190,10 @@ final class DeclarationTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'reasync' with 'async'"]) + DiagnosticSpec( + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'reasync' with 'async'"] + ) ], fixedSource: """ var bad2 : Int { @@ -1499,10 +1559,22 @@ final class DeclarationTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected '{' in struct", fixIts: ["insert '{'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected condition in conditional compilation clause", fixIts: ["insert condition"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected condition in conditional compilation clause", + fixIts: ["insert condition"] + ), DiagnosticSpec(locationMarker: "3️⃣", message: "expected name in attribute", fixIts: ["insert name"]), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected declaration after attribute", fixIts: ["insert declaration"]), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected '#endif' in conditional compilation block", fixIts: ["insert '#endif'"]), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected declaration after attribute", + fixIts: ["insert declaration"] + ), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected '#endif' in conditional compilation block", + fixIts: ["insert '#endif'"] + ), DiagnosticSpec(locationMarker: "3️⃣", message: "expected '}' to end struct", fixIts: ["insert '}'"]), ], fixedSource: """ @@ -1598,7 +1670,11 @@ final class DeclarationTests: ParserTestCase { "1️⃣}protocol C2️⃣", diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected brace before protocol"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected member block in protocol", fixIts: ["insert member block"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected member block in protocol", + fixIts: ["insert member block"] + ), ], fixedSource: """ }protocol C { @@ -1620,7 +1696,11 @@ final class DeclarationTests: ParserTestCase { "1️⃣}struct C2️⃣", diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected brace before struct"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected member block in struct", fixIts: ["insert member block"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected member block in struct", + fixIts: ["insert member block"] + ), ], fixedSource: """ }struct C { @@ -1631,7 +1711,11 @@ final class DeclarationTests: ParserTestCase { "1️⃣}func C2️⃣", diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected brace before function"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected parameter clause in function signature", + fixIts: ["insert parameter clause"] + ), ], fixedSource: """ }func C() @@ -1641,7 +1725,11 @@ final class DeclarationTests: ParserTestCase { "1️⃣}init2️⃣", diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected brace before initializer"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected parameter clause in function signature", + fixIts: ["insert parameter clause"] + ), ], fixedSource: """ }init() @@ -1651,8 +1739,16 @@ final class DeclarationTests: ParserTestCase { "1️⃣}subscript2️⃣", diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected brace before subscript"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected parameter clause in subscript", fixIts: ["insert parameter clause"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected '->' and return type in subscript", fixIts: ["insert '->' and return type"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected parameter clause in subscript", + fixIts: ["insert parameter clause"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected '->' and return type in subscript", + fixIts: ["insert '->' and return type"] + ), ], fixedSource: """ }subscript() -> <#type#> @@ -1795,7 +1891,10 @@ final class DeclarationTests: ParserTestCase { assertParse( "func 1️⃣{}", diagnostics: [ - DiagnosticSpec(message: "expected identifier and function signature in function", fixIts: ["insert identifier and function signature"]) + DiagnosticSpec( + message: "expected identifier and function signature in function", + fixIts: ["insert identifier and function signature"] + ) ], fixedSource: """ func <#identifier#>() {} @@ -2059,7 +2158,11 @@ final class DeclarationTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code 'myMacroName' in struct"), ], fixedSource: """ @@ -2257,9 +2360,17 @@ final class DeclarationTests: ParserTestCase { macro m5(_: T) """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected parameter clause in function signature", + fixIts: ["insert parameter clause"] + ), DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected code ': Int = A.M1' before macro"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected parameter clause in function signature", + fixIts: ["insert parameter clause"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code ': T = A.M4 where T.Assoc: P' before macro"), ], fixedSource: """ @@ -2276,7 +2387,11 @@ final class DeclarationTests: ParserTestCase { macro m11️⃣ = A """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected parameter clause in function signature", fixIts: ["insert parameter clause"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected parameter clause in function signature", + fixIts: ["insert parameter clause"] + ) ], fixedSource: """ macro m1() = A @@ -2289,9 +2404,17 @@ final class DeclarationTests: ParserTestCase { "protocol1️⃣<2️⃣:3️⃣", diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected identifier in protocol", fixIts: ["insert identifier"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected name and '>' to end primary associated type clause", fixIts: ["insert name and '>'"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected name and '>' to end primary associated type clause", + fixIts: ["insert name and '>'"] + ), DiagnosticSpec(locationMarker: "3️⃣", message: "expected type in inherited type", fixIts: ["insert type"]), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected member block in protocol", fixIts: ["insert member block"]), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected member block in protocol", + fixIts: ["insert member block"] + ), ], fixedSource: """ protocol <#identifier#><<#identifier#>>: <#type#> { @@ -2863,7 +2986,11 @@ final class DeclarationTests: ParserTestCase { diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "editor placeholder in source file"), DiagnosticSpec(locationMarker: "2️⃣", message: "editor placeholder in source file"), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected ':' and type in parameter", fixIts: ["insert ':' and type"]), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected ':' and type in parameter", + fixIts: ["insert ':' and type"] + ), DiagnosticSpec(locationMarker: "4️⃣", message: "editor placeholder in source file"), DiagnosticSpec(locationMarker: "5️⃣", message: "editor placeholder in source file"), ], diff --git a/Tests/SwiftParserTest/ExpressionTests.swift b/Tests/SwiftParserTest/ExpressionTests.swift index 4153ffaab87..eba62a0aec5 100644 --- a/Tests/SwiftParserTest/ExpressionTests.swift +++ b/Tests/SwiftParserTest/ExpressionTests.swift @@ -626,7 +626,10 @@ final class ExpressionTests: ParserTestCase { """1️⃣""" """##, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal closing delimiter must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal closing delimiter must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: ##""" """ @@ -833,7 +836,10 @@ final class ExpressionTests: ParserTestCase { assertParse( "foo ? 11️⃣", diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]) + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ) ], fixedSource: """ foo ? 1 : <#expression#> @@ -1011,7 +1017,11 @@ final class ExpressionTests: ParserTestCase { DiagnosticSpec(locationMarker: "1️⃣", message: "expected pattern in variable", fixIts: ["insert pattern"]), DiagnosticSpec(locationMarker: "2️⃣", message: "expected type in function type", fixIts: ["insert type"]), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '..' in function type"), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected return type in function type", fixIts: ["insert return type"]), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected return type in function type", + fixIts: ["insert return type"] + ), ], fixedSource: """ let <#pattern#>:(<#type#>..)-> <#type#> @@ -1232,7 +1242,9 @@ final class ExpressionTests: ParserTestCase { openingQuote: .multilineStringQuoteToken(leadingTrivia: .spaces(2), trailingTrivia: .newline), segments: StringLiteralSegmentListSyntax([ .stringSegment(StringSegmentSyntax(content: .stringSegment("line 1\n", leadingTrivia: .spaces(2)))), - .stringSegment(StringSegmentSyntax(content: .stringSegment("line 2", leadingTrivia: .spaces(2), trailingTrivia: .newline))), + .stringSegment( + StringSegmentSyntax(content: .stringSegment("line 2", leadingTrivia: .spaces(2), trailingTrivia: .newline)) + ), ]), closingQuote: .multilineStringQuoteToken(leadingTrivia: .spaces(2)) @@ -1251,9 +1263,17 @@ final class ExpressionTests: ParserTestCase { openingQuote: .multilineStringQuoteToken(leadingTrivia: .spaces(2), trailingTrivia: .newline), segments: StringLiteralSegmentListSyntax([ .stringSegment( - StringSegmentSyntax(content: .stringSegment("line 1 ", leadingTrivia: .spaces(2), trailingTrivia: [.backslashes(1), .newlines(1)])) + StringSegmentSyntax( + content: .stringSegment( + "line 1 ", + leadingTrivia: .spaces(2), + trailingTrivia: [.backslashes(1), .newlines(1)] + ) + ) + ), + .stringSegment( + StringSegmentSyntax(content: .stringSegment("line 2", leadingTrivia: .spaces(2), trailingTrivia: .newline)) ), - .stringSegment(StringSegmentSyntax(content: .stringSegment("line 2", leadingTrivia: .spaces(2), trailingTrivia: .newline))), ]), closingQuote: .multilineStringQuoteToken(leadingTrivia: .spaces(2)) @@ -1274,8 +1294,15 @@ final class ExpressionTests: ParserTestCase { .stringSegment(StringSegmentSyntax(content: .stringSegment("line 1\n", leadingTrivia: .spaces(2)))), .stringSegment( StringSegmentSyntax( - UnexpectedNodesSyntax([Syntax(TokenSyntax.stringSegment(" line 2 ", trailingTrivia: [.backslashes(1), .newlines(1)]))]), - content: .stringSegment("line 2 ", leadingTrivia: .spaces(2), trailingTrivia: .newline, presence: .missing) + UnexpectedNodesSyntax([ + Syntax(TokenSyntax.stringSegment(" line 2 ", trailingTrivia: [.backslashes(1), .newlines(1)])) + ]), + content: .stringSegment( + "line 2 ", + leadingTrivia: .spaces(2), + trailingTrivia: .newline, + presence: .missing + ) ) ), ]), @@ -1283,7 +1310,10 @@ final class ExpressionTests: ParserTestCase { ), diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ) ], fixedSource: #""" """ @@ -1321,7 +1351,11 @@ final class ExpressionTests: ParserTestCase { segments: StringLiteralSegmentListSyntax([ .stringSegment(StringSegmentSyntax(content: .stringSegment("line 1\n", leadingTrivia: [.spaces(2)]))), .stringSegment(StringSegmentSyntax(content: .stringSegment("\n"))), - .stringSegment(StringSegmentSyntax(content: .stringSegment("line 2", leadingTrivia: [.spaces(2)], trailingTrivia: .newline))), + .stringSegment( + StringSegmentSyntax( + content: .stringSegment("line 2", leadingTrivia: [.spaces(2)], trailingTrivia: .newline) + ) + ), ]), closingQuote: .multilineStringQuoteToken(leadingTrivia: [.spaces(2)]), closingPounds: nil @@ -1974,8 +2008,16 @@ final class StatementExpressionTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected value and ')' to end tuple", fixIts: ["insert value and ')'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected value and ')' to end tuple", + fixIts: ["insert value and ')'"] + ), ], fixedSource: #""" """ @@ -2281,13 +2323,21 @@ final class StatementExpressionTests: ParserTestCase { "abc"2️⃣#3️⃣ """#, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), DiagnosticSpec( locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"] ), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], applyFixIts: ["insert identifier", "insert ';'"], fixedSource: #""" @@ -2395,8 +2445,16 @@ final class StatementExpressionTests: ParserTestCase { #2️⃣ """#, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: ##"expected '"#' to end string literal"##, fixIts: [##"insert '"#'"##]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: ##"expected '"#' to end string literal"##, + fixIts: [##"insert '"#'"##] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: #""" #"abc""# @@ -2828,7 +2886,11 @@ final class StatementExpressionTests: ParserTestCase { assertParse( "[() throws 1️⃣async2️⃣(MyError) -> Void]()", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'async' must precede 'throws'", fixIts: ["move 'async' in front of 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'async' must precede 'throws'", + fixIts: ["move 'async' in front of 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in array element"), ], fixedSource: "[() async throws (MyError) -> Void]()" @@ -2846,14 +2908,22 @@ final class StatementExpressionTests: ParserTestCase { assertParse( "[() throws(MyError) 1️⃣await -> Void]()", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'await' must precede 'throws'", fixIts: ["move 'await' in front of 'throws'"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'await' must precede 'throws'", + fixIts: ["move 'await' in front of 'throws'"] + ) ], fixedSource: "[() async throws(MyError) -> Void]()" ) assertParse( "[() throws 1️⃣await2️⃣(MyError) -> Void]()", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'await' must precede 'throws'", fixIts: ["move 'await' in front of 'throws'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'await' must precede 'throws'", + fixIts: ["move 'await' in front of 'throws'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(MyError)' in array element"), ], fixedSource: "[() async throws (MyError) -> Void]()" diff --git a/Tests/SwiftParserTest/IsValidIdentifierTests.swift b/Tests/SwiftParserTest/IsValidIdentifierTests.swift index 1ef6c901537..0d5f1b990b3 100644 --- a/Tests/SwiftParserTest/IsValidIdentifierTests.swift +++ b/Tests/SwiftParserTest/IsValidIdentifierTests.swift @@ -34,8 +34,20 @@ private func assertValidIdentifier( file: StaticString = #filePath, line: UInt = #line ) { - XCTAssertEqual(name.isValidSwiftIdentifier(for: .variableName), spec.variableName, "Checking identifier for variableName context", file: file, line: line) - XCTAssertEqual(name.isValidSwiftIdentifier(for: .memberAccess), spec.memberAccess, "Checking identifier for memberAccess context", file: file, line: line) + XCTAssertEqual( + name.isValidSwiftIdentifier(for: .variableName), + spec.variableName, + "Checking identifier for variableName context", + file: file, + line: line + ) + XCTAssertEqual( + name.isValidSwiftIdentifier(for: .memberAccess), + spec.memberAccess, + "Checking identifier for memberAccess context", + file: file, + line: line + ) } class IsValidIdentifierTests: XCTestCase { diff --git a/Tests/SwiftParserTest/LexerTests.swift b/Tests/SwiftParserTest/LexerTests.swift index c692e3910c4..362ea00d389 100644 --- a/Tests/SwiftParserTest/LexerTests.swift +++ b/Tests/SwiftParserTest/LexerTests.swift @@ -836,10 +836,21 @@ class LexerTests: ParserTestCase { "!1️⃣<#b1#> && !2️⃣<#b2#>", lexemes: [ LexemeSpec(.prefixOperator, text: "!"), - LexemeSpec(.identifier, text: "<#b1#>", trailing: " ", errorLocationMarker: "1️⃣", diagnostic: "editor placeholder in source file"), + LexemeSpec( + .identifier, + text: "<#b1#>", + trailing: " ", + errorLocationMarker: "1️⃣", + diagnostic: "editor placeholder in source file" + ), LexemeSpec(.binaryOperator, text: "&&", trailing: " "), LexemeSpec(.prefixOperator, text: "!"), - LexemeSpec(.identifier, text: "<#b2#>", errorLocationMarker: "2️⃣", diagnostic: "editor placeholder in source file"), + LexemeSpec( + .identifier, + text: "<#b2#>", + errorLocationMarker: "2️⃣", + diagnostic: "editor placeholder in source file" + ), ] ) @@ -854,9 +865,20 @@ class LexerTests: ParserTestCase { "let 1️⃣<#name#> = 2️⃣<#value#>", lexemes: [ LexemeSpec(.keyword, text: "let", trailing: " "), - LexemeSpec(.identifier, text: "<#name#>", trailing: " ", errorLocationMarker: "1️⃣", diagnostic: "editor placeholder in source file"), + LexemeSpec( + .identifier, + text: "<#name#>", + trailing: " ", + errorLocationMarker: "1️⃣", + diagnostic: "editor placeholder in source file" + ), LexemeSpec(.equal, text: "=", trailing: " "), - LexemeSpec(.identifier, text: "<#value#>", errorLocationMarker: "2️⃣", diagnostic: "editor placeholder in source file"), + LexemeSpec( + .identifier, + text: "<#value#>", + errorLocationMarker: "2️⃣", + diagnostic: "editor placeholder in source file" + ), ] ) } @@ -908,11 +930,25 @@ class LexerTests: ParserTestCase { func testNumericLiteralDiagnostics() { assertLexemes( " 0x1.01️⃣", - lexemes: [LexemeSpec(.integerLiteral, leading: " ", text: "0x1.0", diagnostic: "hexadecimal floating point literal must end with an exponent")] + lexemes: [ + LexemeSpec( + .integerLiteral, + leading: " ", + text: "0x1.0", + diagnostic: "hexadecimal floating point literal must end with an exponent" + ) + ] ) assertLexemes( " 0x1p1️⃣_", - lexemes: [LexemeSpec(.floatLiteral, leading: " ", text: "0x1p_", diagnostic: "'_' is not a valid first character in floating point exponent")] + lexemes: [ + LexemeSpec( + .floatLiteral, + leading: " ", + text: "0x1p_", + diagnostic: "'_' is not a valid first character in floating point exponent" + ) + ] ) assertLexemes( "01️⃣QWERTY", @@ -920,23 +956,53 @@ class LexerTests: ParserTestCase { ) assertLexemes( "0b1️⃣QWERTY", - lexemes: [LexemeSpec(.integerLiteral, text: "0bQWERTY", diagnostic: "'Q' is not a valid binary digit (0 or 1) in integer literal")] + lexemes: [ + LexemeSpec( + .integerLiteral, + text: "0bQWERTY", + diagnostic: "'Q' is not a valid binary digit (0 or 1) in integer literal" + ) + ] ) assertLexemes( "0x1️⃣QWERTY", - lexemes: [LexemeSpec(.integerLiteral, text: "0xQWERTY", diagnostic: "'Q' is not a valid hexadecimal digit (0-9, A-F) in integer literal")] + lexemes: [ + LexemeSpec( + .integerLiteral, + text: "0xQWERTY", + diagnostic: "'Q' is not a valid hexadecimal digit (0-9, A-F) in integer literal" + ) + ] ) assertLexemes( "0o1️⃣QWERTY", - lexemes: [LexemeSpec(.integerLiteral, text: "0oQWERTY", diagnostic: "'Q' is not a valid octal digit (0-7) in integer literal")] + lexemes: [ + LexemeSpec( + .integerLiteral, + text: "0oQWERTY", + diagnostic: "'Q' is not a valid octal digit (0-7) in integer literal" + ) + ] ) assertLexemes( "1.0e+1️⃣QWERTY", - lexemes: [LexemeSpec(.floatLiteral, text: "1.0e+QWERTY", diagnostic: "'Q' is not a valid digit in floating point exponent")] + lexemes: [ + LexemeSpec( + .floatLiteral, + text: "1.0e+QWERTY", + diagnostic: "'Q' is not a valid digit in floating point exponent" + ) + ] ) assertLexemes( "0x1p+1️⃣QWERTY", - lexemes: [LexemeSpec(.floatLiteral, text: "0x1p+QWERTY", diagnostic: "'Q' is not a valid digit in floating point exponent")] + lexemes: [ + LexemeSpec( + .floatLiteral, + text: "0x1p+QWERTY", + diagnostic: "'Q' is not a valid digit in floating point exponent" + ) + ] ) } @@ -952,23 +1018,45 @@ class LexerTests: ParserTestCase { func testBadNumericLiteralDigits() { assertLexemes( "01️⃣a1234567", - lexemes: [LexemeSpec(.integerLiteral, text: "0a1234567", diagnostic: "'a' is not a valid digit in integer literal")] + lexemes: [ + LexemeSpec(.integerLiteral, text: "0a1234567", diagnostic: "'a' is not a valid digit in integer literal") + ] ) assertLexemes( "01231️⃣A5678", - lexemes: [LexemeSpec(.integerLiteral, text: "0123A5678", diagnostic: "'A' is not a valid digit in integer literal")] + lexemes: [ + LexemeSpec(.integerLiteral, text: "0123A5678", diagnostic: "'A' is not a valid digit in integer literal") + ] ) assertLexemes( "0b101️⃣20101", - lexemes: [LexemeSpec(.integerLiteral, text: "0b1020101", diagnostic: "'2' is not a valid binary digit (0 or 1) in integer literal")] + lexemes: [ + LexemeSpec( + .integerLiteral, + text: "0b1020101", + diagnostic: "'2' is not a valid binary digit (0 or 1) in integer literal" + ) + ] ) assertLexemes( "0o13571️⃣864", - lexemes: [LexemeSpec(.integerLiteral, text: "0o1357864", diagnostic: "'8' is not a valid octal digit (0-7) in integer literal")] + lexemes: [ + LexemeSpec( + .integerLiteral, + text: "0o1357864", + diagnostic: "'8' is not a valid octal digit (0-7) in integer literal" + ) + ] ) assertLexemes( "0x147AD1️⃣G0", - lexemes: [LexemeSpec(.integerLiteral, text: "0x147ADG0", diagnostic: "'G' is not a valid hexadecimal digit (0-9, A-F) in integer literal")] + lexemes: [ + LexemeSpec( + .integerLiteral, + text: "0x147ADG0", + diagnostic: "'G' is not a valid hexadecimal digit (0-9, A-F) in integer literal" + ) + ] ) } @@ -1017,7 +1105,9 @@ class LexerTests: ParserTestCase { } func testBOMAsLeadingTriviaInSourceFile() throws { - let sourceBytes: [UInt8] = [UInt8(ascii: "1"), UInt8(ascii: " "), UInt8(ascii: "+"), UInt8(ascii: " "), 0xef, 0xbb, 0xbf, UInt8(ascii: "2")] + let sourceBytes: [UInt8] = [ + UInt8(ascii: "1"), UInt8(ascii: " "), UInt8(ascii: "+"), UInt8(ascii: " "), 0xef, 0xbb, 0xbf, UInt8(ascii: "2"), + ] lex(sourceBytes) { lexemes in guard lexemes.count == 4 else { return XCTFail("Expected 4 lexemes, got \(lexemes.count)") @@ -1378,7 +1468,11 @@ class LexerTests: ParserTestCase { """#, lexemes: [ LexemeSpec(.stringQuote, text: #"""#), - LexemeSpec(.stringSegment, text: #"\u{}"#, diagnostic: #"\u{...} escape sequence expects between 1 and 8 hex digits"#), + LexemeSpec( + .stringSegment, + text: #"\u{}"#, + diagnostic: #"\u{...} escape sequence expects between 1 and 8 hex digits"# + ), LexemeSpec(.stringQuote, text: #"""#), ] ) @@ -1400,7 +1494,11 @@ class LexerTests: ParserTestCase { """#, lexemes: [ LexemeSpec(.stringQuote, text: #"""#), - LexemeSpec(.stringSegment, text: #"\u{fffffffff}"#, diagnostic: #"\u{...} escape sequence expects between 1 and 8 hex digits"#), + LexemeSpec( + .stringSegment, + text: #"\u{fffffffff}"#, + diagnostic: #"\u{...} escape sequence expects between 1 and 8 hex digits"# + ), LexemeSpec(.stringQuote, text: #"""#), ] ) @@ -1443,7 +1541,12 @@ class LexerTests: ParserTestCase { """, lexemes: [ LexemeSpec(.identifier, text: "a", trailing: " "), - LexemeSpec(.identifier, text: "“curly string”", trailing: " ", diagnostic: #"unicode curly quote found; use '"' instead"#), + LexemeSpec( + .identifier, + text: "“curly string”", + trailing: " ", + diagnostic: #"unicode curly quote found; use '"' instead"# + ), LexemeSpec(.identifier, text: "b"), ] ) @@ -1461,7 +1564,12 @@ class LexerTests: ParserTestCase { assertLexemes( "\u{0330}", lexemes: [ - LexemeSpec(.identifier, text: "\u{0330}", errorLocationMarker: "START", diagnostic: "an identifier cannot begin with this character") + LexemeSpec( + .identifier, + text: "\u{0330}", + errorLocationMarker: "START", + diagnostic: "an identifier cannot begin with this character" + ) ] ) } @@ -1470,7 +1578,12 @@ class LexerTests: ParserTestCase { assertLexemes( "a 1️⃣\u{a0} b", lexemes: [ - LexemeSpec(.identifier, text: "a", trailing: " \u{a0} ", diagnostic: "non-breaking space (U+00A0) used instead of regular space"), + LexemeSpec( + .identifier, + text: "a", + trailing: " \u{a0} ", + diagnostic: "non-breaking space (U+00A0) used instead of regular space" + ), LexemeSpec(.identifier, text: "b"), ] ) @@ -1487,7 +1600,12 @@ class LexerTests: ParserTestCase { assertLexemes( "0x1️⃣ ", lexemes: [ - LexemeSpec(.integerLiteral, text: "0x", trailing: " ", diagnostic: "expected hexadecimal digit (0-9, A-F) in integer literal") + LexemeSpec( + .integerLiteral, + text: "0x", + trailing: " ", + diagnostic: "expected hexadecimal digit (0-9, A-F) in integer literal" + ) ] ) } @@ -1511,7 +1629,12 @@ class LexerTests: ParserTestCase { assertLexemes( "\u{a0}0x1️⃣r", lexemes: [ - LexemeSpec(.integerLiteral, leading: "\u{a0}", text: "0xr", diagnostic: "'r' is not a valid hexadecimal digit (0-9, A-F) in integer literal") + LexemeSpec( + .integerLiteral, + leading: "\u{a0}", + text: "0xr", + diagnostic: "'r' is not a valid hexadecimal digit (0-9, A-F) in integer literal" + ) ] ) } diff --git a/Tests/SwiftParserTest/Parser+EntryTests.swift b/Tests/SwiftParserTest/Parser+EntryTests.swift index fe19fcc1af1..c0b84809f86 100644 --- a/Tests/SwiftParserTest/Parser+EntryTests.swift +++ b/Tests/SwiftParserTest/Parser+EntryTests.swift @@ -63,8 +63,15 @@ class EntryTests: ParserTestCase { 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"]), + 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"] + ), ], fixedSource: """ prefix operator test diff --git a/Tests/SwiftParserTest/RegexLiteralTests.swift b/Tests/SwiftParserTest/RegexLiteralTests.swift index d71554b3ffb..6796f0bffa3 100644 --- a/Tests/SwiftParserTest/RegexLiteralTests.swift +++ b/Tests/SwiftParserTest/RegexLiteralTests.swift @@ -41,7 +41,10 @@ final class RegexLiteralTests: ParserTestCase { #//#1️⃣# """#, diagnostics: [ - DiagnosticSpec(message: "too many '#' characters in closing delimiter", fixIts: ["remove extraneous delimiters"]) + DiagnosticSpec( + message: "too many '#' characters in closing delimiter", + fixIts: ["remove extraneous delimiters"] + ) ], fixedSource: "#//#" ) @@ -52,7 +55,10 @@ final class RegexLiteralTests: ParserTestCase { #/abc/#1️⃣# """, diagnostics: [ - DiagnosticSpec(message: "too many '#' characters in closing delimiter", fixIts: ["remove extraneous delimiters"]) + DiagnosticSpec( + message: "too many '#' characters in closing delimiter", + fixIts: ["remove extraneous delimiters"] + ) ], fixedSource: "#/abc/#" ) @@ -206,7 +212,10 @@ final class RegexLiteralTests: ParserTestCase { ##/##/#1️⃣ """#, diagnostics: [ - DiagnosticSpec(message: "expected additional '#' characters in closing delimiter", fixIts: ["insert additional closing '#' delimiters"]) + DiagnosticSpec( + message: "expected additional '#' characters in closing delimiter", + fixIts: ["insert additional closing '#' delimiters"] + ) ], fixedSource: "##/##/##" ) @@ -358,7 +367,11 @@ final class RegexLiteralTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected '/#' to end regex literal", fixIts: ["insert '/#'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ #/abc/# @@ -375,7 +388,11 @@ final class RegexLiteralTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected '/#' to end regex literal", fixIts: ["insert '/#'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ #/abc/# diff --git a/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift b/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift index 602628c3469..4bc26e1406b 100644 --- a/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift +++ b/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift @@ -337,7 +337,9 @@ final class TranslateSequentialToConcurrentEditsTests: ParserTestCase { let numEdits = Int.random(in: 1..<10) for _ in 0..case @@ -739,7 +759,10 @@ final class StatementTests: ParserTestCase { }1️⃣ {} """, diagnostics: [ - DiagnosticSpec(message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive statements on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], fixedSource: """ if test { diff --git a/Tests/SwiftParserTest/StringLiteralRepresentedLiteralValueTests.swift b/Tests/SwiftParserTest/StringLiteralRepresentedLiteralValueTests.swift index 4f978caf700..69023ff8575 100644 --- a/Tests/SwiftParserTest/StringLiteralRepresentedLiteralValueTests.swift +++ b/Tests/SwiftParserTest/StringLiteralRepresentedLiteralValueTests.swift @@ -252,7 +252,10 @@ class StringLiteralRepresentedLiteralValueTests: ParserTestCase { func testMissingQuoteStringLiteral() throws { var parser = Parser(#""a"#) let stringLiteral = StringLiteralExprSyntax(ExprSyntax.parse(from: &parser))! - XCTAssertNil(stringLiteral.representedLiteralValue, "only fully parsed string literals should produce a literal value") + XCTAssertNil( + stringLiteral.representedLiteralValue, + "only fully parsed string literals should produce a literal value" + ) } func testInterpolatedStringLiteral() throws { @@ -263,7 +266,10 @@ class StringLiteralRepresentedLiteralValueTests: ParserTestCase { func testMalformedMultiLineStringLiteral() throws { var parser = Parser(#""""a""""#) let stringLiteral = StringLiteralExprSyntax(ExprSyntax.parse(from: &parser))! - XCTAssertNil(stringLiteral.representedLiteralValue, "missing newline in multiline string literal cannot produce a literal value") + XCTAssertNil( + stringLiteral.representedLiteralValue, + "missing newline in multiline string literal cannot produce a literal value" + ) } // MARK: supporting code diff --git a/Tests/SwiftParserTest/TypeMemberTests.swift b/Tests/SwiftParserTest/TypeMemberTests.swift index 2b0dd90bafa..9e0e123ccc1 100644 --- a/Tests/SwiftParserTest/TypeMemberTests.swift +++ b/Tests/SwiftParserTest/TypeMemberTests.swift @@ -87,7 +87,9 @@ final class TypeMemberTests: ParserTestCase { assertParse( source, { TypeSyntax.parse(from: &$0) }, - diagnostics: [DiagnosticSpec(message: "extraneous whitespace after '.' is not permitted", fixIts: ["remove whitespace"])], + diagnostics: [ + DiagnosticSpec(message: "extraneous whitespace after '.' is not permitted", fixIts: ["remove whitespace"]) + ], fixedSource: expected, line: line ) diff --git a/Tests/SwiftParserTest/TypeTests.swift b/Tests/SwiftParserTest/TypeTests.swift index a06caabf286..936ef5f817a 100644 --- a/Tests/SwiftParserTest/TypeTests.swift +++ b/Tests/SwiftParserTest/TypeTests.swift @@ -55,7 +55,11 @@ final class TypeTests: ParserTestCase { diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected type in function type", fixIts: ["insert type"]), DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected code '..' in function type"), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected return type in function type", fixIts: ["insert return type"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected return type in function type", + fixIts: ["insert return type"] + ), ], fixedSource: """ t as(<#type#>..)-> <#type#> @@ -334,7 +338,11 @@ final class TypeTests: ParserTestCase { assertParse( "func foo() -> _borrow(1️⃣) X", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected parameter reference in lifetime specifier", fixIts: ["insert parameter reference"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected parameter reference in lifetime specifier", + fixIts: ["insert parameter reference"] + ) ], fixedSource: "func foo() -> _borrow(<#identifier#>) X", experimentalFeatures: [.nonescapableTypes] @@ -343,7 +351,11 @@ final class TypeTests: ParserTestCase { assertParse( "func foo() -> _borrow(x,1️⃣) X", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected parameter reference in lifetime specifier", fixIts: ["insert parameter reference"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected parameter reference in lifetime specifier", + fixIts: ["insert parameter reference"] + ) ], fixedSource: "func foo() -> _borrow(x, <#identifier#>) X", experimentalFeatures: [.nonescapableTypes] @@ -373,7 +385,11 @@ final class TypeTests: ParserTestCase { assertParse( "func foo() -> _borrow(1️⃣*) X", diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected parameter reference in lifetime specifier", fixIts: ["insert parameter reference"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected parameter reference in lifetime specifier", + fixIts: ["insert parameter reference"] + ), DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected code '*' in lifetime specifier"), ], fixedSource: "func foo() -> _borrow(<#identifier#>*) X", @@ -408,7 +424,10 @@ final class TypeTests: ParserTestCase { assertParse( "func foo() -> _borrow(1️⃣-1) X", diagnostics: [ - DiagnosticSpec(message: "expected parameter reference in lifetime specifier", fixIts: ["insert parameter reference"]), + DiagnosticSpec( + message: "expected parameter reference in lifetime specifier", + fixIts: ["insert parameter reference"] + ), DiagnosticSpec(message: "unexpected code '-1' in lifetime specifier"), ], fixedSource: "func foo() -> _borrow(<#identifier#>-1) X", diff --git a/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift b/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift index bd612ddc9e8..051a6ad7521 100644 --- a/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift +++ b/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift @@ -31,7 +31,9 @@ final class AvailabilityQueryTests: ParserTestCase { if (1️⃣#available(OSX 10.51, *)) {} """, diagnostics: [ - DiagnosticSpec(message: "availability condition cannot be used in an expression, only as a condition of 'if' or 'guard'") + DiagnosticSpec( + message: "availability condition cannot be used in an expression, only as a condition of 'if' or 'guard'" + ) ] ) } @@ -42,7 +44,9 @@ final class AvailabilityQueryTests: ParserTestCase { let x = 1️⃣#available(OSX 10.51, *) """, diagnostics: [ - DiagnosticSpec(message: "availability condition cannot be used in an expression, only as a condition of 'if' or 'guard'") + DiagnosticSpec( + message: "availability condition cannot be used in an expression, only as a condition of 'if' or 'guard'" + ) ] ) } @@ -53,7 +57,9 @@ final class AvailabilityQueryTests: ParserTestCase { (1️⃣#available(OSX 10.51, *) ? 1 : 0) """, diagnostics: [ - DiagnosticSpec(message: "availability condition cannot be used in an expression, only as a condition of 'if' or 'guard'") + DiagnosticSpec( + message: "availability condition cannot be used in an expression, only as a condition of 'if' or 'guard'" + ) ] ) } @@ -103,7 +109,10 @@ final class AvailabilityQueryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected ',' joining parts of a multi-clause condition", fixIts: ["replace '&&' with ','"]) + DiagnosticSpec( + message: "expected ',' joining parts of a multi-clause condition", + fixIts: ["replace '&&' with ','"] + ) ], fixedSource: """ if #available(OSX 10.51, *), #available(OSX 10.52, *) { @@ -139,7 +148,10 @@ final class AvailabilityQueryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected platform and ')' to end availability condition", fixIts: ["insert platform and ')'"]) + DiagnosticSpec( + message: "expected platform and ')' to end availability condition", + fixIts: ["insert platform and ')'"] + ) ], fixedSource: """ if #available(<#identifier#>) { @@ -155,7 +167,10 @@ final class AvailabilityQueryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected version restriction in availability argument", fixIts: ["insert version restriction"]) + DiagnosticSpec( + message: "expected version restriction in availability argument", + fixIts: ["insert version restriction"] + ) ], fixedSource: """ if #available(<#identifier#>) { @@ -387,7 +402,10 @@ final class AvailabilityQueryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected version restriction in availability argument", fixIts: ["insert version restriction"]) + DiagnosticSpec( + message: "expected version restriction in availability argument", + fixIts: ["insert version restriction"] + ) ], fixedSource: """ if #available(OSX 10.51, <#identifier#>) { @@ -443,7 +461,10 @@ final class AvailabilityQueryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected ',' joining platforms in availability condition", fixIts: ["replace '||' with ','"]) + DiagnosticSpec( + message: "expected ',' joining platforms in availability condition", + fixIts: ["replace '||' with ','"] + ) ], fixedSource: """ if #available(OSX 10.51, iOS 8.0) { diff --git a/Tests/SwiftParserTest/translated/AvailabilityQueryUnavailabilityTests.swift b/Tests/SwiftParserTest/translated/AvailabilityQueryUnavailabilityTests.swift index 3d5dc7a1220..24d1827bcc0 100644 --- a/Tests/SwiftParserTest/translated/AvailabilityQueryUnavailabilityTests.swift +++ b/Tests/SwiftParserTest/translated/AvailabilityQueryUnavailabilityTests.swift @@ -135,7 +135,10 @@ final class AvailabilityQueryUnavailabilityTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected platform and ')' to end availability condition", fixIts: ["insert platform and ')'"]) + DiagnosticSpec( + message: "expected platform and ')' to end availability condition", + fixIts: ["insert platform and ')'"] + ) ], fixedSource: """ if #unavailable(<#identifier#>) { diff --git a/Tests/SwiftParserTest/translated/ConsecutiveStatementsTests.swift b/Tests/SwiftParserTest/translated/ConsecutiveStatementsTests.swift index 2887ad925c0..eafbfb16f2e 100644 --- a/Tests/SwiftParserTest/translated/ConsecutiveStatementsTests.swift +++ b/Tests/SwiftParserTest/translated/ConsecutiveStatementsTests.swift @@ -19,7 +19,10 @@ final class ConsecutiveStatementsTests: ParserTestCase { assertParse( "let x = 21️⃣ let y = 3", diagnostics: [ - DiagnosticSpec(message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive statements on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert newline"], fixedSource: """ @@ -33,7 +36,10 @@ final class ConsecutiveStatementsTests: ParserTestCase { assertParse( "let x = 21️⃣ let y = 3", diagnostics: [ - DiagnosticSpec(message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive statements on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert ';'"], fixedSource: "let x = 2; let y = 3" @@ -316,7 +322,10 @@ final class ConsecutiveStatementsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert newline"], fixedSource: """ @@ -346,7 +355,10 @@ final class ConsecutiveStatementsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert ';'"], fixedSource: """ @@ -370,7 +382,10 @@ final class ConsecutiveStatementsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert newline"], fixedSource: """ @@ -390,7 +405,10 @@ final class ConsecutiveStatementsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert ';'"], fixedSource: """ diff --git a/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift b/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift index 911ab24bf67..854df6fe100 100644 --- a/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift +++ b/Tests/SwiftParserTest/translated/DiagnoseDynamicReplacementTests.swift @@ -53,7 +53,10 @@ final class DiagnoseDynamicReplacementTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected argument for '@_dynamicReplacement' attribute", fixIts: ["insert attribute argument"]), + DiagnosticSpec( + message: "expected argument for '@_dynamicReplacement' attribute", + fixIts: ["insert attribute argument"] + ), DiagnosticSpec( message: "expected ')' to end attribute", notes: [NoteSpec(message: "to match this opening '('")], diff --git a/Tests/SwiftParserTest/translated/DiagnoseInitializerAsTypedPatternTests.swift b/Tests/SwiftParserTest/translated/DiagnoseInitializerAsTypedPatternTests.swift index ced81997cb9..bd562bf80b0 100644 --- a/Tests/SwiftParserTest/translated/DiagnoseInitializerAsTypedPatternTests.swift +++ b/Tests/SwiftParserTest/translated/DiagnoseInitializerAsTypedPatternTests.swift @@ -22,7 +22,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let a1️⃣:[X]() """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let a = [X]()" ) @@ -34,7 +37,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let b1️⃣: [X]() """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let b = [X]()" ) @@ -46,7 +52,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let c 1️⃣:[X]() """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let c = [X]()" ) @@ -58,7 +67,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let d 1️⃣: [X]() """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let d = [X]()" ) @@ -70,7 +82,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let e1️⃣: X(), ee: Int """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let e = X(), ee: Int" ) @@ -82,7 +97,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let f1️⃣:/*comment*/[X]() """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let f =/*comment*/[X]()" ) @@ -94,7 +112,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let f/*comment*/1️⃣:[X]() """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: "let f/*comment*/ = [X]()" ) @@ -126,7 +147,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let g1️⃣: X(x) """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ let g = X(x) @@ -140,7 +164,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let h1️⃣: X(x, y) """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ let h = X(x, y) @@ -154,7 +181,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let i1️⃣: X() { foo() } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ let i = X() { foo() } @@ -168,7 +198,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let j1️⃣: X(x) { foo() } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ let j = X(x) { foo() } @@ -182,7 +215,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { let k1️⃣: X(x, y) { foo() } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ let k = X(x, y) { foo() } @@ -198,7 +234,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ func nonTopLevel() { @@ -216,7 +255,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ func nonTopLevel() { @@ -234,7 +276,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ func nonTopLevel() { @@ -252,7 +297,10 @@ final class DiagnoseInitializerAsTypedPatternTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' with '='"]) + DiagnosticSpec( + message: "unexpected initializer in pattern; did you mean to use '='?", + fixIts: ["replace ':' with '='"] + ) ], fixedSource: """ func nonTopLevel() { diff --git a/Tests/SwiftParserTest/translated/DollarIdentifierTests.swift b/Tests/SwiftParserTest/translated/DollarIdentifierTests.swift index fd7c3a31b33..de333fb6f96 100644 --- a/Tests/SwiftParserTest/translated/DollarIdentifierTests.swift +++ b/Tests/SwiftParserTest/translated/DollarIdentifierTests.swift @@ -35,7 +35,10 @@ final class DollarIdentifierTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func dollarVar() { @@ -56,7 +59,10 @@ final class DollarIdentifierTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func dollarLet() { @@ -75,7 +81,10 @@ final class DollarIdentifierTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func dollarClass() { @@ -93,7 +102,10 @@ final class DollarIdentifierTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func dollarEnum() { @@ -111,7 +123,10 @@ final class DollarIdentifierTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func dollarStruct() { @@ -127,8 +142,16 @@ final class DollarIdentifierTests: ParserTestCase { func 1️⃣$(2️⃣$ dollarParam: Int) {} """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ), ], fixedSource: "func `$`(`$` dollarParam: Int) {}" ) @@ -140,7 +163,10 @@ final class DollarIdentifierTests: ParserTestCase { $(1️⃣$: 24) """, diagnostics: [ - DiagnosticSpec(message: "'$' is not a valid identifier", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "'$' is not a valid identifier", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ $(`$`: 24) diff --git a/Tests/SwiftParserTest/translated/EnumTests.swift b/Tests/SwiftParserTest/translated/EnumTests.swift index cb33f5bc464..946169ae67c 100644 --- a/Tests/SwiftParserTest/translated/EnumTests.swift +++ b/Tests/SwiftParserTest/translated/EnumTests.swift @@ -250,7 +250,10 @@ final class EnumTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code ':' in enum"), ] ) @@ -279,7 +282,11 @@ final class EnumTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected identifier in enum case", fixIts: ["insert identifier"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected ':' and type in parameter", fixIts: ["insert ':' and type"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected ':' and type in parameter", + fixIts: ["insert ':' and type"] + ), DiagnosticSpec(locationMarker: "3️⃣", message: "unexpected code '0' in parameter clause"), DiagnosticSpec(locationMarker: "4️⃣", message: "unexpected code ':' in enum"), ], diff --git a/Tests/SwiftParserTest/translated/ErrorsTests.swift b/Tests/SwiftParserTest/translated/ErrorsTests.swift index 3cdb753b354..0f86ff82a38 100644 --- a/Tests/SwiftParserTest/translated/ErrorsTests.swift +++ b/Tests/SwiftParserTest/translated/ErrorsTests.swift @@ -292,7 +292,9 @@ final class ErrorsTests: ParserTestCase { bindings: PatternBindingListSyntax([ PatternBindingSyntax( pattern: WildcardPatternSyntax(), - typeAnnotation: TypeAnnotationSyntax(type: TupleTypeSyntax(elements: TupleTypeElementListSyntax([]))) + typeAnnotation: TypeAnnotationSyntax( + type: TupleTypeSyntax(elements: TupleTypeElementListSyntax([])) + ) ) ]) ) @@ -315,7 +317,10 @@ final class ErrorsTests: ParserTestCase { func fixitThrow0() 1️⃣throw {} """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'throw' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'throw' with 'throws'"] + ) ], fixedSource: """ func fixitThrow0() throws {} @@ -329,7 +334,10 @@ final class ErrorsTests: ParserTestCase { func fixitThrow1() 1️⃣throw -> Int {} """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'throw' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'throw' with 'throws'"] + ) ], fixedSource: """ func fixitThrow1() throws -> Int {} @@ -347,7 +355,10 @@ final class ErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'throw' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'throw' with 'throws'"] + ) ], fixedSource: """ func fixitThrow2() throws { @@ -387,7 +398,10 @@ final class ErrorsTests: ParserTestCase { func fixitTry0(a: T) 1️⃣try where T:ExpressibleByStringLiteral {} """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ) ], fixedSource: """ func fixitTry0(a: T) throws where T:ExpressibleByStringLiteral {} @@ -401,7 +415,10 @@ final class ErrorsTests: ParserTestCase { func fixitTry1(a: T) 1️⃣try {} """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ) ], fixedSource: """ func fixitTry1(a: T) throws {} @@ -415,7 +432,10 @@ final class ErrorsTests: ParserTestCase { func fixitTry2() 1️⃣try {} """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ) ], fixedSource: """ func fixitTry2() throws {} @@ -429,7 +449,10 @@ final class ErrorsTests: ParserTestCase { let fixitTry3 : () 1️⃣try -> Int """, diagnostics: [ - DiagnosticSpec(message: "expected throwing specifier; did you mean 'throws'?", fixIts: ["replace 'try' with 'throws'"]) + DiagnosticSpec( + message: "expected throwing specifier; did you mean 'throws'?", + fixIts: ["replace 'try' with 'throws'"] + ) ], fixedSource: """ let fixitTry3 : () throws -> Int @@ -443,7 +466,10 @@ final class ErrorsTests: ParserTestCase { func fixitAwait0() 1️⃣await { } """, diagnostics: [ - DiagnosticSpec(message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'await' with 'async'"]) + DiagnosticSpec( + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'await' with 'async'"] + ) ], fixedSource: """ func fixitAwait0() async { } @@ -457,7 +483,10 @@ final class ErrorsTests: ParserTestCase { func fixitAwait1() 1️⃣await -> Int { } """, diagnostics: [ - DiagnosticSpec(message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'await' with 'async'"]) + DiagnosticSpec( + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'await' with 'async'"] + ) ], fixedSource: """ func fixitAwait1() async -> Int { } diff --git a/Tests/SwiftParserTest/translated/ForwardSlashRegexTests.swift b/Tests/SwiftParserTest/translated/ForwardSlashRegexTests.swift index 1ec12ac09c7..403cca06ecf 100644 --- a/Tests/SwiftParserTest/translated/ForwardSlashRegexTests.swift +++ b/Tests/SwiftParserTest/translated/ForwardSlashRegexTests.swift @@ -605,8 +605,16 @@ final class ForwardSlashRegexTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected expression after operator", fixIts: ["insert expression"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected expression after operator", fixIts: ["insert expression"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected expression after operator", + fixIts: ["insert expression"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected expression after operator", + fixIts: ["insert expression"] + ), ], fixedSource: """ do { @@ -1048,7 +1056,10 @@ final class ForwardSlashRegexTests: ParserTestCase { """ _ = /x// comment """, - substructure: PrefixOperatorExprSyntax(operator: .prefixOperator("/"), expression: DeclReferenceExprSyntax(baseName: "x")) + substructure: PrefixOperatorExprSyntax( + operator: .prefixOperator("/"), + expression: DeclReferenceExprSyntax(baseName: "x") + ) ) } @@ -1057,7 +1068,10 @@ final class ForwardSlashRegexTests: ParserTestCase { """ _ = /x // comment """, - substructure: PrefixOperatorExprSyntax(operator: .prefixOperator("/"), expression: DeclReferenceExprSyntax(baseName: "x")) + substructure: PrefixOperatorExprSyntax( + operator: .prefixOperator("/"), + expression: DeclReferenceExprSyntax(baseName: "x") + ) ) } @@ -1066,7 +1080,10 @@ final class ForwardSlashRegexTests: ParserTestCase { """ _ = /x/*comment*/ """, - substructure: PrefixOperatorExprSyntax(operator: .prefixOperator("/"), expression: DeclReferenceExprSyntax(baseName: "x")) + substructure: PrefixOperatorExprSyntax( + operator: .prefixOperator("/"), + expression: DeclReferenceExprSyntax(baseName: "x") + ) ) } diff --git a/Tests/SwiftParserTest/translated/IdentifiersTests.swift b/Tests/SwiftParserTest/translated/IdentifiersTests.swift index edbee78a25e..fe4a8c5a618 100644 --- a/Tests/SwiftParserTest/translated/IdentifiersTests.swift +++ b/Tests/SwiftParserTest/translated/IdentifiersTests.swift @@ -98,7 +98,10 @@ final class IdentifiersTests: ParserTestCase { class 1️⃣switch {} """, diagnostics: [ - DiagnosticSpec(message: "keyword 'switch' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'switch' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ // Keywords as identifiers @@ -113,7 +116,10 @@ final class IdentifiersTests: ParserTestCase { struct 1️⃣Self {} """, diagnostics: [ - DiagnosticSpec(message: "keyword 'Self' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'Self' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ struct `Self` {} @@ -135,7 +141,10 @@ final class IdentifiersTests: ParserTestCase { struct 1️⃣Any {} """, diagnostics: [ - DiagnosticSpec(message: "keyword 'Any' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'Any' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ struct `Any` {} @@ -149,7 +158,10 @@ final class IdentifiersTests: ParserTestCase { protocol 1️⃣enum {} """, diagnostics: [ - DiagnosticSpec(message: "keyword 'enum' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'enum' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ protocol `enum` {} diff --git a/Tests/SwiftParserTest/translated/IfconfigExprTests.swift b/Tests/SwiftParserTest/translated/IfconfigExprTests.swift index 2b578f84610..4ba95c4e692 100644 --- a/Tests/SwiftParserTest/translated/IfconfigExprTests.swift +++ b/Tests/SwiftParserTest/translated/IfconfigExprTests.swift @@ -106,7 +106,10 @@ final class IfconfigExprTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected code '+ otherExpr' in conditional compilation block"), - DiagnosticSpec(locationMarker: "2️⃣", message: #"unexpected code 'print("debug")' in conditional compilation block"#), + DiagnosticSpec( + locationMarker: "2️⃣", + message: #"unexpected code 'print("debug")' in conditional compilation block"# + ), ] ) } @@ -428,7 +431,8 @@ final class IfconfigExprTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec( - message: "unexpected 'if' keyword following '#else' conditional compilation directive; did you mean '#elseif'?", + message: + "unexpected 'if' keyword following '#else' conditional compilation directive; did you mean '#elseif'?", fixIts: ["replace '#else if' with '#elseif'"] ) ], diff --git a/Tests/SwiftParserTest/translated/InitDeinitTests.swift b/Tests/SwiftParserTest/translated/InitDeinitTests.swift index a75f665729e..b06771b3e07 100644 --- a/Tests/SwiftParserTest/translated/InitDeinitTests.swift +++ b/Tests/SwiftParserTest/translated/InitDeinitTests.swift @@ -456,7 +456,10 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'await' with 'async'"]) + DiagnosticSpec( + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'await' with 'async'"] + ) ], fixedSource: """ class FooClassDeinitializerA { @@ -474,7 +477,10 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'reasync' with 'async'"]) + DiagnosticSpec( + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'reasync' with 'async'"] + ) ], fixedSource: """ class FooClassDeinitializerA { @@ -648,7 +654,11 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'reasync' with 'async'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'reasync' with 'async'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "deinitializers cannot throw", fixIts: ["remove 'throws'"]), ], fixedSource: """ @@ -668,7 +678,11 @@ final class InitDeinitTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "deinitializers cannot have a name", fixIts: ["remove 'x'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'await' with 'async'"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'await' with 'async'"] + ), ], fixedSource: """ class FooClassDeinitializerA { @@ -729,7 +743,11 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "deinitializers cannot have parameters", fixIts: ["remove parameter clause"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "deinitializers cannot have parameters", + fixIts: ["remove parameter clause"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "deinitializers cannot throw", fixIts: ["remove 'throws'"]), ], fixedSource: """ @@ -894,7 +912,10 @@ final class InitDeinitTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(message: "expected 'async' in effect specifiers", fixIts: ["insert 'async'"]), - DiagnosticSpec(message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'async', and return type"]), + DiagnosticSpec( + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'async', and return type"] + ), ], fixedSource: """ class FooClassDeinitializerA { @@ -912,7 +933,10 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'async', and return type"]) + DiagnosticSpec( + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'async', and return type"] + ) ], fixedSource: """ class FooClassDeinitializerA { @@ -930,8 +954,16 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected async specifier; did you mean 'async'?", fixIts: ["replace 'await' with 'async'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'async', and return type"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected async specifier; did you mean 'async'?", + fixIts: ["replace 'await' with 'async'"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'async', and return type"] + ), ], fixedSource: """ class FooClassDeinitializerA { @@ -949,7 +981,10 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'await', and return type"]) + DiagnosticSpec( + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'await', and return type"] + ) ], fixedSource: """ class FooClassDeinitializerA { @@ -967,7 +1002,10 @@ final class InitDeinitTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'throws', and return type"]) + DiagnosticSpec( + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'throws', and return type"] + ) ], fixedSource: """ class FooClassDeinitializerA { @@ -986,7 +1024,11 @@ final class InitDeinitTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "deinitializers cannot throw", fixIts: ["remove 'throws'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'throws', and return type"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'throws', and return type"] + ), ], fixedSource: """ class FooClassDeinitializerA { @@ -1005,7 +1047,10 @@ final class InitDeinitTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(message: "expected 'async' in effect specifiers", fixIts: ["insert 'async'"]), - DiagnosticSpec(message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'async throws', and return type"]), + DiagnosticSpec( + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'async throws', and return type"] + ), ], fixedSource: """ class FooClassDeinitializerA { @@ -1024,7 +1069,10 @@ final class InitDeinitTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(message: "expected 'async' in effect specifiers", fixIts: ["insert 'async'"]), - DiagnosticSpec(message: "deinitializers cannot have a return clause", fixIts: ["remove '->', 'throws async', and return type"]), + DiagnosticSpec( + message: "deinitializers cannot have a return clause", + fixIts: ["remove '->', 'throws async', and return type"] + ), ], fixedSource: """ class FooClassDeinitializerA { diff --git a/Tests/SwiftParserTest/translated/InvalidIfExprTests.swift b/Tests/SwiftParserTest/translated/InvalidIfExprTests.swift index e97b5ef041f..f7a0fd797f0 100644 --- a/Tests/SwiftParserTest/translated/InvalidIfExprTests.swift +++ b/Tests/SwiftParserTest/translated/InvalidIfExprTests.swift @@ -21,7 +21,10 @@ final class InvalidIfExprTests: ParserTestCase { (a ? b1️⃣) """, diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]) + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ) ], fixedSource: "(a ? b : <#expression#>)" ) @@ -33,7 +36,10 @@ final class InvalidIfExprTests: ParserTestCase { (a ? b : c ? d1️⃣) """, diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]) + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ) ], fixedSource: "(a ? b : c ? d : <#expression#>)" ) @@ -45,7 +51,10 @@ final class InvalidIfExprTests: ParserTestCase { ℹ️(a ? b ? c : d1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]), + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ), DiagnosticSpec( message: "expected ')' to end tuple", notes: [NoteSpec(message: "to match this opening '('")], @@ -62,8 +71,14 @@ final class InvalidIfExprTests: ParserTestCase { (a ? b ? c1️⃣) """, diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]), - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]), + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ), + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ), ], fixedSource: "(a ? b ? c : <#expression#> : <#expression#>)" ) @@ -87,7 +102,10 @@ final class InvalidIfExprTests: ParserTestCase { foo ? 1 1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]) + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ) ], fixedSource: "foo ? 1 : <#expression#>" ) @@ -100,7 +118,10 @@ final class InvalidIfExprTests: ParserTestCase { someOtherVariable """, diagnostics: [ - DiagnosticSpec(message: "expected ':' and expression after '? ...' in ternary expression", fixIts: ["insert ':' and expression"]) + DiagnosticSpec( + message: "expected ':' and expression after '? ...' in ternary expression", + fixIts: ["insert ':' and expression"] + ) ], fixedSource: """ condition ? 1 : <#expression#> diff --git a/Tests/SwiftParserTest/translated/InvalidTests.swift b/Tests/SwiftParserTest/translated/InvalidTests.swift index bc03c8f92f6..8ee85a3104a 100644 --- a/Tests/SwiftParserTest/translated/InvalidTests.swift +++ b/Tests/SwiftParserTest/translated/InvalidTests.swift @@ -22,7 +22,10 @@ final class InvalidTests: ParserTestCase { func test1(1️⃣inout var x : Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: "func test1(var x : inout Int) {}" ) @@ -34,7 +37,10 @@ final class InvalidTests: ParserTestCase { func test2(1️⃣inout let x : Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: """ func test2(let x : inout Int) {} @@ -48,7 +54,10 @@ final class InvalidTests: ParserTestCase { func test3(f : (1️⃣inout _ x : Int) -> Void) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: "func test3(f : (_ x : inout Int) -> Void) {}" ) @@ -60,7 +69,10 @@ final class InvalidTests: ParserTestCase { func test1s(1️⃣__shared var x : Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'__shared' before a parameter name is not allowed", fixIts: ["move '__shared' in front of type"]) + DiagnosticSpec( + message: "'__shared' before a parameter name is not allowed", + fixIts: ["move '__shared' in front of type"] + ) ], fixedSource: """ func test1s(var x : __shared Int) {} @@ -74,7 +86,10 @@ final class InvalidTests: ParserTestCase { func test2s(1️⃣__shared let x : Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'__shared' before a parameter name is not allowed", fixIts: ["move '__shared' in front of type"]) + DiagnosticSpec( + message: "'__shared' before a parameter name is not allowed", + fixIts: ["move '__shared' in front of type"] + ) ], fixedSource: """ func test2s(let x : __shared Int) {} @@ -88,7 +103,10 @@ final class InvalidTests: ParserTestCase { func test1o(1️⃣__owned var x : Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'__owned' before a parameter name is not allowed", fixIts: ["move '__owned' in front of type"]) + DiagnosticSpec( + message: "'__owned' before a parameter name is not allowed", + fixIts: ["move '__owned' in front of type"] + ) ], fixedSource: """ func test1o(var x : __owned Int) {} @@ -102,7 +120,10 @@ final class InvalidTests: ParserTestCase { func test2o(1️⃣__owned let x : Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'__owned' before a parameter name is not allowed", fixIts: ["move '__owned' in front of type"]) + DiagnosticSpec( + message: "'__owned' before a parameter name is not allowed", + fixIts: ["move '__owned' in front of type"] + ) ], fixedSource: """ func test2o(let x : __owned Int) {} @@ -179,7 +200,10 @@ final class InvalidTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]) + DiagnosticSpec( + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ) ], fixedSource: """ switch state { @@ -212,7 +236,11 @@ final class InvalidTests: ParserTestCase { } """#, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ), DiagnosticSpec( locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by newline or ';'", @@ -283,7 +311,11 @@ final class InvalidTests: ParserTestCase { message: "expected ')' in function type", fixIts: ["insert ')'"] ), - DiagnosticSpec(locationMarker: "3️⃣", message: "expected return type in function type", fixIts: ["insert return type"]), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "expected return type in function type", + fixIts: ["insert return type"] + ), DiagnosticSpec( locationMarker: "3️⃣", message: "expected ')' to end parameter clause", @@ -372,7 +404,10 @@ final class InvalidTests: ParserTestCase { func f2_43591(1️⃣inout inout b: Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout inout' before a parameter name is not allowed", fixIts: ["move 'inout inout' in front of type"]) + DiagnosticSpec( + message: "'inout inout' before a parameter name is not allowed", + fixIts: ["move 'inout inout' in front of type"] + ) ], fixedSource: "func f2_43591(b: inout inout Int) {}" ) @@ -395,7 +430,10 @@ final class InvalidTests: ParserTestCase { func f4_43591(1️⃣inout x: inout String) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: """ func f4_43591(x: inout inout String) {} @@ -409,7 +447,10 @@ final class InvalidTests: ParserTestCase { func f5_43591(1️⃣inout i: inout Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: """ func f5_43591(i: inout inout Int) {} @@ -423,7 +464,10 @@ final class InvalidTests: ParserTestCase { func 1️⃣repeat() {} """, diagnostics: [ - DiagnosticSpec(message: "keyword 'repeat' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'repeat' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func `repeat`() {} @@ -437,7 +481,10 @@ final class InvalidTests: ParserTestCase { let 1️⃣for = 2 """, diagnostics: [ - DiagnosticSpec(message: "keyword 'for' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'for' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ let `for` = 2 @@ -451,7 +498,10 @@ final class InvalidTests: ParserTestCase { func f4_43591(1️⃣inout x: inout String) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: """ func f4_43591(x: inout inout String) {} @@ -465,7 +515,10 @@ final class InvalidTests: ParserTestCase { func f5_43591(1️⃣inout i: inout Int) {} """, diagnostics: [ - DiagnosticSpec(message: "'inout' before a parameter name is not allowed", fixIts: ["move 'inout' in front of type"]) + DiagnosticSpec( + message: "'inout' before a parameter name is not allowed", + fixIts: ["move 'inout' in front of type"] + ) ], fixedSource: "func f5_43591(i: inout inout Int) {}" ) @@ -477,7 +530,10 @@ final class InvalidTests: ParserTestCase { func 1️⃣repeat() {} """, diagnostics: [ - DiagnosticSpec(message: "keyword 'repeat' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'repeat' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ func `repeat`() {} @@ -491,7 +547,10 @@ final class InvalidTests: ParserTestCase { let 1️⃣for = 2 """, diagnostics: [ - DiagnosticSpec(message: "keyword 'for' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'for' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ let `for` = 2 @@ -606,7 +665,11 @@ final class InvalidTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected '(' to start parameter clause", fixIts: ["insert '('"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected ':' and type in parameter", fixIts: ["insert ':' and type"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected ':' and type in parameter", + fixIts: ["insert ':' and type"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected ')' to end parameter clause", fixIts: ["insert ')'"]), DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '(x: T)' in function"), ], @@ -634,7 +697,10 @@ final class InvalidTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'class' constraint can only appear on protocol declarations", fixIts: ["replace 'class' with 'AnyObject'"]) + DiagnosticSpec( + message: "'class' constraint can only appear on protocol declarations", + fixIts: ["replace 'class' with 'AnyObject'"] + ) ], fixedSource: """ struct Weak { diff --git a/Tests/SwiftParserTest/translated/MultilineErrorsTests.swift b/Tests/SwiftParserTest/translated/MultilineErrorsTests.swift index 4dd66752bec..ce4704f1798 100644 --- a/Tests/SwiftParserTest/translated/MultilineErrorsTests.swift +++ b/Tests/SwiftParserTest/translated/MultilineErrorsTests.swift @@ -320,7 +320,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: #""" _ = """ @@ -339,7 +342,10 @@ final class MultilineErrorsTests: ParserTestCase { Pi1️⃣""" """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal closing delimiter must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal closing delimiter must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: #""" _ = """ @@ -356,7 +362,10 @@ final class MultilineErrorsTests: ParserTestCase { _ = """1️⃣""" """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal closing delimiter must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal closing delimiter must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: #""" _ = """ @@ -371,7 +380,10 @@ final class MultilineErrorsTests: ParserTestCase { _ = """ 1️⃣""" """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal closing delimiter must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal closing delimiter must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: #""" _ = """ @@ -620,7 +632,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove '\'"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove '\'"] + ) ], fixedSource: #""" _ = """ @@ -639,7 +654,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ) ], fixedSource: #""" _ = """ @@ -657,7 +675,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ) ], fixedSource: #""" _ = """ @@ -675,7 +696,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ) ], fixedSource: #""" _ = """ @@ -693,7 +717,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ) ], fixedSource: #""" _ = """ @@ -737,7 +764,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]) + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ) ], fixedSource: #""" _ = """ @@ -754,8 +784,14 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]), - DiagnosticSpec(message: "escaped newline at the last line of a multi-line string literal is not allowed", fixIts: ["remove ''"]), + DiagnosticSpec( + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ), + DiagnosticSpec( + message: "escaped newline at the last line of a multi-line string literal is not allowed", + fixIts: ["remove ''"] + ), ], fixedSource: #""" _ = """ @@ -850,7 +886,10 @@ final class MultilineErrorsTests: ParserTestCase { \(1)1️⃣""" """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal closing delimiter must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal closing delimiter must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: #""" _ = """ @@ -960,7 +999,10 @@ final class MultilineErrorsTests: ParserTestCase { """ """#, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: #""" """ diff --git a/Tests/SwiftParserTest/translated/MultilineStringTests.swift b/Tests/SwiftParserTest/translated/MultilineStringTests.swift index 62636a32f7c..9f444d09615 100644 --- a/Tests/SwiftParserTest/translated/MultilineStringTests.swift +++ b/Tests/SwiftParserTest/translated/MultilineStringTests.swift @@ -499,7 +499,9 @@ final class MultilineStringTests: ParserTestCase { openingQuote: .multilineStringQuoteToken(trailingTrivia: .newline), segments: StringLiteralSegmentListSyntax([ .stringSegment( - StringSegmentSyntax(content: .stringSegment("Three ", trailingTrivia: [.backslashes(1), .pounds(1), .newlines(1)])) + StringSegmentSyntax( + content: .stringSegment("Three ", trailingTrivia: [.backslashes(1), .pounds(1), .newlines(1)]) + ) ), .stringSegment(StringSegmentSyntax(content: .stringSegment("Gamma", trailingTrivia: .newline))), ]), @@ -526,9 +528,15 @@ final class MultilineStringTests: ParserTestCase { openingQuote: .multilineStringQuoteToken(trailingTrivia: .newline), segments: StringLiteralSegmentListSyntax([ .stringSegment( - StringSegmentSyntax(content: .stringSegment("Three ", trailingTrivia: [.backslashes(1), .pounds(1), .newlines(1)])) + StringSegmentSyntax( + content: .stringSegment("Three ", trailingTrivia: [.backslashes(1), .pounds(1), .newlines(1)]) + ) + ), + .stringSegment( + StringSegmentSyntax( + content: .stringSegment("Gamma ", trailingTrivia: [.backslashes(1), .pounds(1), .newlines(1)]) + ) ), - .stringSegment(StringSegmentSyntax(content: .stringSegment("Gamma ", trailingTrivia: [.backslashes(1), .pounds(1), .newlines(1)]))), ]), closingQuote: .multilineStringQuoteToken(), closingPounds: .rawStringPoundDelimiter("#") diff --git a/Tests/SwiftParserTest/translated/NumberIdentifierErrorsTests.swift b/Tests/SwiftParserTest/translated/NumberIdentifierErrorsTests.swift index 8239b768474..c9806a481d0 100644 --- a/Tests/SwiftParserTest/translated/NumberIdentifierErrorsTests.swift +++ b/Tests/SwiftParserTest/translated/NumberIdentifierErrorsTests.swift @@ -66,8 +66,14 @@ final class NumberIdentifierErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } @@ -80,8 +86,14 @@ final class NumberIdentifierErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } @@ -94,8 +106,14 @@ final class NumberIdentifierErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } @@ -207,8 +225,14 @@ final class NumberIdentifierErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } @@ -221,8 +245,14 @@ final class NumberIdentifierErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } @@ -235,8 +265,14 @@ final class NumberIdentifierErrorsTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "identifier can only start with a letter or underscore, not a number"), - DiagnosticSpec(locationMarker: "2️⃣", message: "identifier can only start with a letter or underscore, not a number"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "identifier can only start with a letter or underscore, not a number" + ), ] ) } diff --git a/Tests/SwiftParserTest/translated/ObjectLiteralsTests.swift b/Tests/SwiftParserTest/translated/ObjectLiteralsTests.swift index 21db15f792a..01df7fdb324 100644 --- a/Tests/SwiftParserTest/translated/ObjectLiteralsTests.swift +++ b/Tests/SwiftParserTest/translated/ObjectLiteralsTests.swift @@ -22,7 +22,11 @@ final class ObjectLiteralsTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected ',' in array element", fixIts: ["insert ','"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ let _ = [#Color(colorLiteralRed: red, green: green, blue: blue, alpha: alpha), #<#identifier#>] @@ -37,7 +41,11 @@ final class ObjectLiteralsTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected ',' in array element", fixIts: ["insert ','"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ let _ = [#Image(imageLiteral: localResourceNameAsString), #<#identifier#>] @@ -52,7 +60,11 @@ final class ObjectLiteralsTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected ',' in array element", fixIts: ["insert ','"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ let _ = [#FileReference(fileReferenceLiteral: localResourceNameAsString), #<#identifier#>] @@ -114,9 +126,17 @@ final class ObjectLiteralsTests: ParserTestCase { let _ = [#1️⃣#2️⃣] """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), DiagnosticSpec(locationMarker: "1️⃣", message: "expected ',' in array element", fixIts: ["insert ','"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ let _ = [#<#identifier#>, #<#identifier#>] @@ -178,7 +198,11 @@ final class ObjectLiteralsTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected ',' in array element", fixIts: ["insert ','"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: """ let _ = [#Color(withRed: 1, green: 1, whatever: 2), #<#identifier#>] diff --git a/Tests/SwiftParserTest/translated/OperatorDeclTests.swift b/Tests/SwiftParserTest/translated/OperatorDeclTests.swift index 6d1245b0543..a8e79ba960f 100644 --- a/Tests/SwiftParserTest/translated/OperatorDeclTests.swift +++ b/Tests/SwiftParserTest/translated/OperatorDeclTests.swift @@ -158,7 +158,11 @@ final class OperatorDeclTests: ParserTestCase { 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"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "operator should not be declared with body", + fixIts: ["remove operator body"] + ), ], fixedSource: """ prefix operator +*+++ @@ -177,7 +181,11 @@ final class OperatorDeclTests: ParserTestCase { 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"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "operator should not be declared with body", + fixIts: ["remove operator body"] + ), ], fixedSource: """ prefix operator +*++* : A @@ -254,7 +262,10 @@ final class OperatorDeclTests: ParserTestCase { postfix operator ?1️⃣$$ """, diagnostics: [ - DiagnosticSpec(message: "'$$' is considered an identifier and must not appear within an operator name", fixIts: ["remove '$$'"]) + DiagnosticSpec( + message: "'$$' is considered an identifier and must not appear within an operator name", + fixIts: ["remove '$$'"] + ) ], fixedSource: "postfix operator ?" ) @@ -266,7 +277,10 @@ final class OperatorDeclTests: ParserTestCase { infix operator --1️⃣aa """, diagnostics: [ - DiagnosticSpec(message: "'aa' is considered an identifier and must not appear within an operator name", fixIts: ["remove 'aa'"]) + DiagnosticSpec( + message: "'aa' is considered an identifier and must not appear within an operator name", + fixIts: ["remove 'aa'"] + ) ], fixedSource: "infix operator --" ) @@ -278,7 +292,11 @@ final class OperatorDeclTests: ParserTestCase { infix operator 1️⃣aa--: A """, diagnostics: [ - DiagnosticSpec(message: "'aa' is considered an identifier and must not appear within an operator name", highlight: "aa", fixIts: ["remove 'aa'"]) + DiagnosticSpec( + message: "'aa' is considered an identifier and must not appear within an operator name", + highlight: "aa", + fixIts: ["remove 'aa'"] + ) ], fixedSource: "infix operator --: A" ) @@ -372,7 +390,10 @@ final class OperatorDeclTests: ParserTestCase { infix operator --- : 1️⃣; """, diagnostics: [ - DiagnosticSpec(message: "expected precedence group in operator declaration", fixIts: ["insert precedence group"]) + DiagnosticSpec( + message: "expected precedence group in operator declaration", + fixIts: ["insert precedence group"] + ) ], fixedSource: """ infix operator +++= @@ -548,7 +569,10 @@ final class OperatorDeclTests: ParserTestCase { postfix operator ++:1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected precedence group in operator declaration", fixIts: ["insert precedence group"]) + DiagnosticSpec( + message: "expected precedence group in operator declaration", + fixIts: ["insert precedence group"] + ) ], fixedSource: """ postfix operator ++: <#identifier#> diff --git a/Tests/SwiftParserTest/translated/OperatorsTests.swift b/Tests/SwiftParserTest/translated/OperatorsTests.swift index 2f618be101f..06690e6e6e2 100644 --- a/Tests/SwiftParserTest/translated/OperatorsTests.swift +++ b/Tests/SwiftParserTest/translated/OperatorsTests.swift @@ -337,7 +337,10 @@ final class OperatorsTests: ParserTestCase { foo!!1️⃣foo """, diagnostics: [ - DiagnosticSpec(message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive statements on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert newline"], fixedSource: """ diff --git a/Tests/SwiftParserTest/translated/PoundAssertTests.swift b/Tests/SwiftParserTest/translated/PoundAssertTests.swift index f43f7b62116..f2b57c8b173 100644 --- a/Tests/SwiftParserTest/translated/PoundAssertTests.swift +++ b/Tests/SwiftParserTest/translated/PoundAssertTests.swift @@ -37,7 +37,10 @@ final class PoundAssertTests: ParserTestCase { #assert1️⃣ true2️⃣, "error message") """#, diagnostics: [ - DiagnosticSpec(message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]), + DiagnosticSpec( + message: "consecutive statements on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: #"extraneous code ', "error message")' at top level"#), ], applyFixIts: ["insert newline"], @@ -54,7 +57,10 @@ final class PoundAssertTests: ParserTestCase { #assert1️⃣ true2️⃣, "error message") """#, diagnostics: [ - DiagnosticSpec(message: "consecutive statements on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]), + DiagnosticSpec( + message: "consecutive statements on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: #"extraneous code ', "error message")' at top level"#), ], applyFixIts: ["insert ';'"], diff --git a/Tests/SwiftParserTest/translated/RawStringErrorsTests.swift b/Tests/SwiftParserTest/translated/RawStringErrorsTests.swift index e3b38da7f72..a8266f82a20 100644 --- a/Tests/SwiftParserTest/translated/RawStringErrorsTests.swift +++ b/Tests/SwiftParserTest/translated/RawStringErrorsTests.swift @@ -21,7 +21,10 @@ final class RawStringErrorsTests: ParserTestCase { let _ = "foo\(#"bar"#1️⃣#)baz" """###, diagnostics: [ - DiagnosticSpec(message: "too many '#' characters in closing delimiter", fixIts: ["remove extraneous delimiters"]) + DiagnosticSpec( + message: "too many '#' characters in closing delimiter", + fixIts: ["remove extraneous delimiters"] + ) ], fixedSource: ###""" let _ = "foo\(#"bar"#)baz" @@ -35,7 +38,10 @@ final class RawStringErrorsTests: ParserTestCase { let _ = #"\#1️⃣#("invalid")"# """###, diagnostics: [ - DiagnosticSpec(message: "too many '#' characters to start string interpolation", fixIts: ["remove extraneous delimiters"]) + DiagnosticSpec( + message: "too many '#' characters to start string interpolation", + fixIts: ["remove extraneous delimiters"] + ) ], fixedSource: ###""" let _ = #"\#("invalid")"# @@ -49,7 +55,10 @@ final class RawStringErrorsTests: ParserTestCase { let _ = ###"""invalid"###1️⃣### """#####, diagnostics: [ - DiagnosticSpec(message: "too many '#' characters in closing delimiter", fixIts: ["remove extraneous delimiters"]) + DiagnosticSpec( + message: "too many '#' characters in closing delimiter", + fixIts: ["remove extraneous delimiters"] + ) ], fixedSource: #####""" let _ = ###"""invalid"### @@ -63,7 +72,10 @@ final class RawStringErrorsTests: ParserTestCase { let _ = ####"invalid"###1️⃣ """#####, diagnostics: [ - DiagnosticSpec(message: #####"expected '"####' to end string literal"#####, fixIts: [#####"insert '"####'"#####]) + DiagnosticSpec( + message: #####"expected '"####' to end string literal"#####, + fixIts: [#####"insert '"####'"#####] + ) ], fixedSource: #####""" let _ = ####"invalid"###"#### @@ -77,7 +89,11 @@ final class RawStringErrorsTests: ParserTestCase { let _ = ###"invalid"###1️⃣### """#####, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "too many '#' characters in closing delimiter", fixIts: ["remove extraneous delimiters"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "too many '#' characters in closing delimiter", + fixIts: ["remove extraneous delimiters"] + ) ], fixedSource: #####""" let _ = ###"invalid"### @@ -93,8 +109,16 @@ final class RawStringErrorsTests: ParserTestCase { aa2️⃣"""## """###, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "multi-line string literal closing delimiter must begin on a new line", fixIts: ["insert newline"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "multi-line string literal closing delimiter must begin on a new line", + fixIts: ["insert newline"] + ), ], fixedSource: ###""" let _ = ##""" @@ -113,7 +137,10 @@ final class RawStringErrorsTests: ParserTestCase { """# """##, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: ##""" let _ = #""" @@ -130,7 +157,10 @@ final class RawStringErrorsTests: ParserTestCase { """### """####, diagnostics: [ - DiagnosticSpec(message: "multi-line string literal content must begin on a new line", fixIts: ["insert newline"]) + DiagnosticSpec( + message: "multi-line string literal content must begin on a new line", + fixIts: ["insert newline"] + ) ], fixedSource: ####""" let _ = ###""" diff --git a/Tests/SwiftParserTest/translated/RecoveryTests.swift b/Tests/SwiftParserTest/translated/RecoveryTests.swift index e215051f31a..c158d4beba1 100644 --- a/Tests/SwiftParserTest/translated/RecoveryTests.swift +++ b/Tests/SwiftParserTest/translated/RecoveryTests.swift @@ -26,7 +26,10 @@ final class RecoveryTests: ParserTestCase { } """#, diagnostics: [ - DiagnosticSpec(message: "unexpected code ') this line is invalid, but we will stop at the keyword below...' before 'return' statement") + DiagnosticSpec( + message: + "unexpected code ') this line is invalid, but we will stop at the keyword below...' before 'return' statement" + ) ] ) } @@ -41,7 +44,9 @@ final class RecoveryTests: ParserTestCase { } """#, diagnostics: [ - DiagnosticSpec(message: "unexpected code ') this line is invalid, but we will stop at the declaration...' before function") + DiagnosticSpec( + message: "unexpected code ') this line is invalid, but we will stop at the declaration...' before function" + ) ] ) } @@ -234,7 +239,10 @@ final class RecoveryTests: ParserTestCase { if1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected expression and body in 'if' statement", fixIts: ["insert expression and body"]) + DiagnosticSpec( + message: "expected expression and body in 'if' statement", + fixIts: ["insert expression and body"] + ) ], fixedSource: """ if <#expression#> { @@ -325,7 +333,10 @@ final class RecoveryTests: ParserTestCase { while1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected expression and code block in 'while' statement", fixIts: ["insert expression and code block"]) + DiagnosticSpec( + message: "expected expression and code block in 'while' statement", + fixIts: ["insert expression and code block"] + ) ], fixedSource: """ while <#expression#> { @@ -445,7 +456,10 @@ final class RecoveryTests: ParserTestCase { }1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected 'while' and condition in 'repeat' statement", fixIts: ["insert 'while' and condition"]) + DiagnosticSpec( + message: "expected 'while' and condition in 'repeat' statement", + fixIts: ["insert 'while' and condition"] + ) ], fixedSource: """ repeat { @@ -461,7 +475,10 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected pattern, 'in', and expression in 'for' statement", fixIts: ["insert pattern, 'in', and expression"]), + DiagnosticSpec( + message: "expected pattern, 'in', and expression in 'for' statement", + fixIts: ["insert pattern, 'in', and expression"] + ), DiagnosticSpec(message: "unexpected ';' separator", fixIts: ["remove ';'"]), ], fixedSource: """ @@ -479,7 +496,10 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected pattern, 'in', and expression in 'for' statement", fixIts: ["insert pattern, 'in', and expression"]), + DiagnosticSpec( + message: "expected pattern, 'in', and expression in 'for' statement", + fixIts: ["insert pattern, 'in', and expression"] + ), DiagnosticSpec(message: "unexpected ';' separator", fixIts: ["remove ';'"]), ], fixedSource: """ @@ -497,7 +517,10 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected pattern, 'in', and expression in 'for' statement", fixIts: ["insert pattern, 'in', and expression"]), + DiagnosticSpec( + message: "expected pattern, 'in', and expression in 'for' statement", + fixIts: ["insert pattern, 'in', and expression"] + ), DiagnosticSpec(message: "unexpected code '; true' in 'for' statement"), ], fixedSource: """ @@ -515,7 +538,10 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "expected 'in' and expression in 'for' statement", fixIts: ["insert 'in' and expression"]), + DiagnosticSpec( + message: "expected 'in' and expression in 'for' statement", + fixIts: ["insert 'in' and expression"] + ), DiagnosticSpec(message: "unexpected code '= 0; true' in 'for' statement"), ], fixedSource: """ @@ -532,7 +558,10 @@ final class RecoveryTests: ParserTestCase { for1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected pattern, 'in', expression, and body in 'for' statement", fixIts: ["insert pattern, 'in', expression, and body"]) + DiagnosticSpec( + message: "expected pattern, 'in', expression, and body in 'for' statement", + fixIts: ["insert pattern, 'in', expression, and body"] + ) ], fixedSource: """ for <#pattern#> in <#expression#> { @@ -590,7 +619,11 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected 'in' and expression in 'for' statement", fixIts: ["insert 'in' and expression"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected 'in' and expression in 'for' statement", + fixIts: ["insert 'in' and expression"] + ) ], fixedSource: """ for i in <#expression#> { @@ -606,7 +639,11 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected 'in' and expression in 'for' statement", fixIts: ["insert 'in' and expression"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected 'in' and expression in 'for' statement", + fixIts: ["insert 'in' and expression"] + ) ], fixedSource: """ for var i in <#expression#> { @@ -627,7 +664,11 @@ final class RecoveryTests: ParserTestCase { 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"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected 'in' and expression in 'for' statement", + fixIts: ["insert 'in' and expression"] + ), ], fixedSource: """ for `in` in <#expression#> { @@ -664,7 +705,11 @@ final class RecoveryTests: ParserTestCase { 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"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected Sequence expression for for-each loop", + fixIts: ["insert expression"] + ), ], fixedSource: """ for `for` in <#expression#> { @@ -722,7 +767,11 @@ final class RecoveryTests: ParserTestCase { 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 ';'"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "standalone ';' statements are not allowed", + fixIts: ["remove ';'"] + ), ], fixedSource: """ for <#pattern#> in <#expression#> { @@ -737,7 +786,10 @@ final class RecoveryTests: ParserTestCase { switch1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected expression and '{}' to end 'switch' statement", fixIts: ["insert expression and '{}'"]) + DiagnosticSpec( + message: "expected expression and '{}' to end 'switch' statement", + fixIts: ["insert expression and '{}'"] + ) ], fixedSource: """ switch <#expression#> { @@ -753,7 +805,11 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected expression in 'switch' statement", fixIts: ["insert expression"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected expression in 'switch' statement", + fixIts: ["insert expression"] + ) ], fixedSource: """ switch <#expression#> { @@ -770,7 +826,11 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected expression in 'switch' statement", fixIts: ["insert expression"]) + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected expression in 'switch' statement", + fixIts: ["insert expression"] + ) ], fixedSource: """ switch <#expression#> @@ -816,8 +876,15 @@ final class RecoveryTests: ParserTestCase { """, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected expression in 'switch' statement"), - DiagnosticSpec(locationMarker: "2️⃣", message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]), - DiagnosticSpec(locationMarker: "3️⃣", message: "'case' can only appear inside a 'switch' statement or 'enum' declaration"), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ), + DiagnosticSpec( + locationMarker: "3️⃣", + message: "'case' can only appear inside a 'switch' statement or 'enum' declaration" + ), ], fixedSource: """ switch { @@ -935,7 +1002,11 @@ final class RecoveryTests: ParserTestCase { DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code '()' before protocol"), DiagnosticSpec(locationMarker: "3️⃣", message: "expected '{' in protocol", fixIts: ["insert '{'"]), DiagnosticSpec(locationMarker: "3️⃣", message: "unexpected code '()' before extension"), - DiagnosticSpec(locationMarker: "4️⃣", message: "expected member block in extension", fixIts: ["insert member block"]), + DiagnosticSpec( + locationMarker: "4️⃣", + message: "expected member block in extension", + fixIts: ["insert member block"] + ), DiagnosticSpec(locationMarker: "4️⃣", message: "expected '}' to end protocol", fixIts: ["insert '}'"]), DiagnosticSpec(locationMarker: "4️⃣", message: "expected '}' to end class", fixIts: ["insert '}'"]), DiagnosticSpec(locationMarker: "4️⃣", message: "expected '}' to end enum", fixIts: ["insert '}'"]), @@ -967,7 +1038,11 @@ final class RecoveryTests: ParserTestCase { DiagnosticSpec(locationMarker: "2️⃣", message: "expected '{' in enum", fixIts: ["insert '{'"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected '{' in class", fixIts: ["insert '{'"]), DiagnosticSpec(locationMarker: "4️⃣", message: "expected '{' in protocol", fixIts: ["insert '{'"]), - DiagnosticSpec(locationMarker: "5️⃣", message: "expected member block in extension", fixIts: ["insert member block"]), + DiagnosticSpec( + locationMarker: "5️⃣", + message: "expected member block in extension", + fixIts: ["insert member block"] + ), DiagnosticSpec(locationMarker: "5️⃣", message: "expected '}' to end protocol", fixIts: ["insert '}'"]), DiagnosticSpec(locationMarker: "5️⃣", message: "expected '}' to end class", fixIts: ["insert '}'"]), DiagnosticSpec(locationMarker: "5️⃣", message: "expected '}' to end enum", fixIts: ["insert '}'"]), @@ -1641,7 +1716,11 @@ final class RecoveryTests: ParserTestCase { assertParse( testCase.testCase, diagnostics: [ - DiagnosticSpec(message: "unexpected ']' in type; did you mean to write an array type?", fixIts: ["insert '['"], line: line) + DiagnosticSpec( + message: "unexpected ']' in type; did you mean to write an array type?", + fixIts: ["insert '['"], + line: line + ) ], fixedSource: testCase.fixedSource, line: line @@ -2090,7 +2169,10 @@ final class RecoveryTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected 'func' in function", fixIts: ["insert 'func'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: #"unexpected code '"No one else was in the room where it happened"' in parameter clause"#), + DiagnosticSpec( + locationMarker: "2️⃣", + message: #"unexpected code '"No one else was in the room where it happened"' in parameter clause"# + ), ], fixedSource: #""" class С_43383 { @@ -2109,7 +2191,10 @@ final class RecoveryTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected 'func' in function", fixIts: ["insert 'func'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: #"unexpected code '"The room where it happened, the room where it happened"' in parameter clause"#), + DiagnosticSpec( + locationMarker: "2️⃣", + message: #"unexpected code '"The room where it happened, the room where it happened"' in parameter clause"# + ), ], fixedSource: #""" extension С_43383 { @@ -2320,7 +2405,10 @@ final class RecoveryTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(message: "expected ':' and type in parameter", fixIts: ["insert ':' and type"]), - DiagnosticSpec(message: #"unexpected code '._core.count != 0, "Can't form a Character from an empty String"' in parameter clause"#), + DiagnosticSpec( + message: + #"unexpected code '._core.count != 0, "Can't form a Character from an empty String"' in parameter clause"# + ), ], fixedSource: #""" public enum TestA { @@ -2341,7 +2429,10 @@ final class RecoveryTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(message: "expected ':' and type in parameter", fixIts: ["insert ':' and type"]), - DiagnosticSpec(message: #"unexpected code '._core.count ?= 0, "Can't form a Character from an empty String"' in parameter clause"#), + DiagnosticSpec( + message: + #"unexpected code '._core.count ?= 0, "Can't form a Character from an empty String"' in parameter clause"# + ), ], fixedSource: #""" public enum TestB { @@ -2698,7 +2789,10 @@ final class RecoveryTests: ParserTestCase { let curlyQuotes1 = 1️⃣“hello world!” """, diagnostics: [ - DiagnosticSpec(message: #"unicode curly quote found; use '"' instead"#, fixIts: [#"replace curly quotes with '"'"#]) + DiagnosticSpec( + message: #"unicode curly quote found; use '"' instead"#, + fixIts: [#"replace curly quotes with '"'"#] + ) ], fixedSource: """ let curlyQuotes1 = "hello world!" @@ -2712,7 +2806,10 @@ final class RecoveryTests: ParserTestCase { let curlyQuotes2 = 1️⃣“hello world!" """#, diagnostics: [ - DiagnosticSpec(message: #"unicode curly quote found; use '"' instead"#, fixIts: [#"replace curly quotes with '"'"#]) + DiagnosticSpec( + message: #"unicode curly quote found; use '"' instead"#, + fixIts: [#"replace curly quotes with '"'"#] + ) ], fixedSource: #""" let curlyQuotes2 = "hello world!" @@ -2771,8 +2868,16 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'=' must have consistent whitespace on both sides", fixIts: ["insert whitespace"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "'=' must have consistent whitespace on both sides", fixIts: ["insert whitespace"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'=' must have consistent whitespace on both sides", + fixIts: ["insert whitespace"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "'=' must have consistent whitespace on both sides", + fixIts: ["insert whitespace"] + ), ], fixedSource: """ func r22387625() { @@ -2793,8 +2898,16 @@ final class RecoveryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'=' must have consistent whitespace on both sides", fixIts: ["insert whitespace"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "'=' must have consistent whitespace on both sides", fixIts: ["insert whitespace"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'=' must have consistent whitespace on both sides", + fixIts: ["insert whitespace"] + ), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "'=' must have consistent whitespace on both sides", + fixIts: ["insert whitespace"] + ), ], fixedSource: """ do { @@ -3021,7 +3134,11 @@ final class RecoveryTests: ParserTestCase { } """#, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "extraneous whitespace after '.' is not permitted", fixIts: ["remove whitespace"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "extraneous whitespace after '.' is not permitted", + fixIts: ["remove whitespace"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected name in member access", fixIts: ["insert name"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected name in member access", fixIts: ["insert name"]), ], @@ -3063,7 +3180,10 @@ final class RecoveryTests: ParserTestCase { func f_53396(a: Int 1️⃣== 0) {} """, diagnostics: [ - DiagnosticSpec(message: "expected '=' instead of '==' to assign default value for parameter", fixIts: ["replace '==' with '='"]) + DiagnosticSpec( + message: "expected '=' instead of '==' to assign default value for parameter", + fixIts: ["replace '==' with '='"] + ) ], fixedSource: """ func f_53396(a: Int = 0) {} @@ -3078,7 +3198,10 @@ final class RecoveryTests: ParserTestCase { extension Collection where Element == Int 1️⃣&& Index == Int {} """, diagnostics: [ - DiagnosticSpec(message: "expected ',' to separate the requirements of this 'where' clause", fixIts: ["replace '&&' with ','"]) + DiagnosticSpec( + message: "expected ',' to separate the requirements of this 'where' clause", + fixIts: ["replace '&&' with ','"] + ) ], fixedSource: """ extension Collection where Element == Int, Index == Int {} diff --git a/Tests/SwiftParserTest/translated/RegexParseErrorTests.swift b/Tests/SwiftParserTest/translated/RegexParseErrorTests.swift index fbeda323b8d..4c7761ed548 100644 --- a/Tests/SwiftParserTest/translated/RegexParseErrorTests.swift +++ b/Tests/SwiftParserTest/translated/RegexParseErrorTests.swift @@ -179,7 +179,11 @@ final class RegexParseErrorTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected root in key path", fixIts: ["insert root"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected expression after operator", fixIts: ["insert expression"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected expression after operator", + fixIts: ["insert expression"] + ), ], fixedSource: #""" do { @@ -200,7 +204,11 @@ final class RegexParseErrorTests: ParserTestCase { """#, diagnostics: [ DiagnosticSpec(locationMarker: "1️⃣", message: "expected '/#' to end regex literal", fixIts: ["insert '/#'"]), - DiagnosticSpec(locationMarker: "2️⃣", message: "expected identifier in macro expansion", fixIts: ["insert identifier"]), + DiagnosticSpec( + locationMarker: "2️⃣", + message: "expected identifier in macro expansion", + fixIts: ["insert identifier"] + ), ], fixedSource: #""" do { diff --git a/Tests/SwiftParserTest/translated/SelfRebindingTests.swift b/Tests/SwiftParserTest/translated/SelfRebindingTests.swift index 3d373a1ee32..77e05da1506 100644 --- a/Tests/SwiftParserTest/translated/SelfRebindingTests.swift +++ b/Tests/SwiftParserTest/translated/SelfRebindingTests.swift @@ -63,7 +63,10 @@ final class SelfRebindingTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "keyword 'self' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'self' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: """ struct T { diff --git a/Tests/SwiftParserTest/translated/SubscriptingTests.swift b/Tests/SwiftParserTest/translated/SubscriptingTests.swift index f2747362619..1aa4e12f73d 100644 --- a/Tests/SwiftParserTest/translated/SubscriptingTests.swift +++ b/Tests/SwiftParserTest/translated/SubscriptingTests.swift @@ -203,7 +203,11 @@ final class SubscriptingTests: ParserTestCase { DiagnosticSpec(locationMarker: "2️⃣", message: "expected '(' to start function type", fixIts: ["insert '('"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected ')' in function type", fixIts: ["insert ')'"]), DiagnosticSpec(locationMarker: "4️⃣", message: "expected ')' to end parameter clause", fixIts: ["insert ')'"]), - DiagnosticSpec(locationMarker: "5️⃣", message: "expected '->' and return type in subscript", fixIts: ["insert '->' and return type"]), + DiagnosticSpec( + locationMarker: "5️⃣", + message: "expected '->' and return type in subscript", + fixIts: ["insert '->' and return type"] + ), ], fixedSource: """ struct A0 { @@ -529,7 +533,11 @@ final class SubscriptingTests: ParserTestCase { DiagnosticSpec(locationMarker: "2️⃣", message: "expected '(' to start function type", fixIts: ["insert '('"]), DiagnosticSpec(locationMarker: "3️⃣", message: "expected ')' in function type", fixIts: ["insert ')'"]), DiagnosticSpec(locationMarker: "4️⃣", message: "expected ')' to end parameter clause", fixIts: ["insert ')'"]), - DiagnosticSpec(locationMarker: "5️⃣", message: "expected '->' and return type in subscript", fixIts: ["insert '->' and return type"]), + DiagnosticSpec( + locationMarker: "5️⃣", + message: "expected '->' and return type in subscript", + fixIts: ["insert '->' and return type"] + ), ], fixedSource: """ struct A11 { diff --git a/Tests/SwiftParserTest/translated/SwitchTests.swift b/Tests/SwiftParserTest/translated/SwitchTests.swift index 4d1f814135c..2b08b5b6ba8 100644 --- a/Tests/SwiftParserTest/translated/SwitchTests.swift +++ b/Tests/SwiftParserTest/translated/SwitchTests.swift @@ -33,7 +33,11 @@ final class SwitchTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected expression and '{}' to end 'switch' statement", fixIts: ["insert expression and '{}'"]), + 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", @@ -294,7 +298,10 @@ final class SwitchTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]) + DiagnosticSpec( + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ) ], fixedSource: """ switch x { @@ -321,7 +328,10 @@ final class SwitchTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]) + DiagnosticSpec( + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ) ], fixedSource: """ switch x { @@ -355,7 +365,10 @@ final class SwitchTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]) + DiagnosticSpec( + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ) ], fixedSource: """ switch x { @@ -375,7 +388,10 @@ final class SwitchTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "all statements inside a switch must be covered by a 'case' or 'default' label", fixIts: ["insert label"]) + DiagnosticSpec( + message: "all statements inside a switch must be covered by a 'case' or 'default' label", + fixIts: ["insert label"] + ) ], fixedSource: """ switch x { @@ -468,7 +484,10 @@ final class SwitchTests: ParserTestCase { var z = 1 """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'case' can only appear inside a 'switch' statement or 'enum' declaration"), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'case' can only appear inside a 'switch' statement or 'enum' declaration" + ), DiagnosticSpec(locationMarker: "2️⃣", message: "'default' label can only appear inside a 'switch' statement"), ] ) diff --git a/Tests/SwiftParserTest/translated/ToplevelLibraryTests.swift b/Tests/SwiftParserTest/translated/ToplevelLibraryTests.swift index d7fba689b8d..a210073db9b 100644 --- a/Tests/SwiftParserTest/translated/ToplevelLibraryTests.swift +++ b/Tests/SwiftParserTest/translated/ToplevelLibraryTests.swift @@ -43,7 +43,10 @@ final class ToplevelLibraryTests: ParserTestCase { for i1️⃣ """, diagnostics: [ - DiagnosticSpec(message: "expected 'in', expression, and body in 'for' statement", fixIts: ["insert 'in', expression, and body"]) + DiagnosticSpec( + message: "expected 'in', expression, and body in 'for' statement", + fixIts: ["insert 'in', expression, and body"] + ) ], fixedSource: """ for i in <#expression#> { diff --git a/Tests/SwiftParserTest/translated/TrailingSemiTests.swift b/Tests/SwiftParserTest/translated/TrailingSemiTests.swift index 8d55b94e36b..72daab95b99 100644 --- a/Tests/SwiftParserTest/translated/TrailingSemiTests.swift +++ b/Tests/SwiftParserTest/translated/TrailingSemiTests.swift @@ -183,7 +183,10 @@ final class TrailingSemiTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert ';'"], fixedSource: """ @@ -208,7 +211,10 @@ final class TrailingSemiTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert newline"], fixedSource: """ @@ -287,7 +293,10 @@ final class TrailingSemiTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert ';'"], fixedSource: """ @@ -310,7 +319,10 @@ final class TrailingSemiTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "consecutive declarations on a line must be separated by newline or ';'", fixIts: ["insert newline", "insert ';'"]) + DiagnosticSpec( + message: "consecutive declarations on a line must be separated by newline or ';'", + fixIts: ["insert newline", "insert ';'"] + ) ], applyFixIts: ["insert newline"], fixedSource: """ diff --git a/Tests/SwiftParserTest/translated/TryTests.swift b/Tests/SwiftParserTest/translated/TryTests.swift index 0f97c10c700..ae17d1052e4 100644 --- a/Tests/SwiftParserTest/translated/TryTests.swift +++ b/Tests/SwiftParserTest/translated/TryTests.swift @@ -140,7 +140,10 @@ final class TryTests: ParserTestCase { 1️⃣try let singleLet = try foo() """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["remove redundant 'try'"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["remove redundant 'try'"] + ) ], fixedSource: "let singleLet = try foo()" ) @@ -152,7 +155,10 @@ final class TryTests: ParserTestCase { 1️⃣try let singleLet = foo() """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["move 'try' after '='"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["move 'try' after '='"] + ) ], fixedSource: "let singleLet = try foo()" ) @@ -164,7 +170,10 @@ final class TryTests: ParserTestCase { 1️⃣try var singleVar = foo() """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["move 'try' after '='"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["move 'try' after '='"] + ) ], fixedSource: "var singleVar = try foo()" ) @@ -187,7 +196,10 @@ final class TryTests: ParserTestCase { 1️⃣try let (destructure1, destructure2) = (foo(), bar()) """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["move 'try' after '='"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["move 'try' after '='"] + ) ], fixedSource: "let (destructure1, destructure2) = try (foo(), bar())" ) @@ -199,7 +211,10 @@ final class TryTests: ParserTestCase { 1️⃣try let multi1 = foo(), multi2 = bar() """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["move 'try' after '='"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["move 'try' after '='"] + ) ], fixedSource: "let multi1 = try foo(), multi2 = try bar()" ) @@ -213,7 +228,10 @@ final class TryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["move 'try' after '='"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["move 'try' after '='"] + ) ], fixedSource: """ class TryDecl { @@ -231,7 +249,10 @@ final class TryTests: ParserTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the initial value expression", fixIts: ["move 'try' after '='"]) + DiagnosticSpec( + message: "'try' must be placed on the initial value expression", + fixIts: ["move 'try' after '='"] + ) ], fixedSource: """ class TryDecl { @@ -288,7 +309,11 @@ final class TryTests: ParserTestCase { 1️⃣try throw 2️⃣ """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "'try' must be placed on the thrown expression", fixIts: ["move 'try' after 'throw'"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "'try' must be placed on the thrown expression", + fixIts: ["move 'try' after 'throw'"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected expression after 'try'", fixIts: ["insert expression"]), ], fixedSource: "throw try <#expression#>" @@ -324,7 +349,10 @@ final class TryTests: ParserTestCase { 1️⃣try return foo() """, diagnostics: [ - DiagnosticSpec(message: "'try' must be placed on the returned expression", fixIts: ["move 'try' after 'return'"]) + DiagnosticSpec( + message: "'try' must be placed on the returned expression", + fixIts: ["move 'try' after 'return'"] + ) ], fixedSource: "return try foo()" ) diff --git a/Tests/SwiftParserTest/translated/TypealiasTests.swift b/Tests/SwiftParserTest/translated/TypealiasTests.swift index 05f407ef765..05e769667ac 100644 --- a/Tests/SwiftParserTest/translated/TypealiasTests.swift +++ b/Tests/SwiftParserTest/translated/TypealiasTests.swift @@ -116,7 +116,11 @@ final class TypealiasTests: ParserTestCase { typealias Recovery2 1️⃣:2️⃣ """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected '=' in typealias declaration", fixIts: ["replace ':' with '='"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected '=' in typealias declaration", + fixIts: ["replace ':' with '='"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "expected type in typealias declaration", fixIts: ["insert type"]), ], fixedSource: """ @@ -159,7 +163,11 @@ final class TypealiasTests: ParserTestCase { typealias Recovery5 1️⃣: Int2️⃣, Float """, diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "expected '=' in typealias declaration", fixIts: ["replace ':' with '='"]), + DiagnosticSpec( + locationMarker: "1️⃣", + message: "expected '=' in typealias declaration", + fixIts: ["replace ':' with '='"] + ), DiagnosticSpec(locationMarker: "2️⃣", message: "extraneous code ', Float' at top level"), ], fixedSource: """ @@ -189,7 +197,10 @@ final class TypealiasTests: ParserTestCase { typealias 1️⃣switch = Int """, diagnostics: [ - DiagnosticSpec(message: "keyword 'switch' cannot be used as an identifier here", fixIts: ["if this name is unavoidable, use backticks to escape it"]) + DiagnosticSpec( + message: "keyword 'switch' cannot be used as an identifier here", + fixIts: ["if this name is unavoidable, use backticks to escape it"] + ) ], fixedSource: "typealias `switch` = Int" ) diff --git a/Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift b/Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift index 6aad11f0c19..bec587bf200 100644 --- a/Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift +++ b/Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift @@ -255,7 +255,11 @@ final class UnclosedStringInterpolationTests: ParserTestCase { """#, diagnostics: [ - DiagnosticSpec(locationMarker: "4️⃣", message: "expected value and ')' in string literal", fixIts: ["insert value and ')'"]), + DiagnosticSpec( + locationMarker: "4️⃣", + message: "expected value and ')' in string literal", + fixIts: ["insert value and ')'"] + ), DiagnosticSpec( locationMarker: "4️⃣", message: #"expected '"' to end string literal"#, diff --git a/Tests/SwiftRefactorTest/ExpandEditorPlaceholderTests.swift b/Tests/SwiftRefactorTest/ExpandEditorPlaceholderTests.swift index 069c5eebf86..3818c772aaa 100644 --- a/Tests/SwiftRefactorTest/ExpandEditorPlaceholderTests.swift +++ b/Tests/SwiftRefactorTest/ExpandEditorPlaceholderTests.swift @@ -19,7 +19,9 @@ import XCTest import _SwiftSyntaxTestSupport fileprivate let closurePlaceholder = wrapInPlaceholder("T##closure##() -> Void") -fileprivate let closureWithArgPlaceholder = wrapInPlaceholder("T##(Int) -> String##(Int) -> String##(_ someInt: Int) -> String") +fileprivate let closureWithArgPlaceholder = wrapInPlaceholder( + "T##(Int) -> String##(Int) -> String##(_ someInt: Int) -> String" +) fileprivate let voidPlaceholder = wrapInPlaceholder("T##code##Void") fileprivate let intPlaceholder = wrapInPlaceholder("T##Int##Int") fileprivate let stringPlaceholder = wrapInPlaceholder("T##String##String") @@ -359,7 +361,8 @@ fileprivate func assertRefactorPlaceholderCall( var parser = Parser(expr) let call = try XCTUnwrap(ExprSyntax.parse(from: &parser).as(FunctionCallExprSyntax.self), file: file, line: line) let arg = call.arguments[call.arguments.index(at: placeholder)] - let token: TokenSyntax = try XCTUnwrap(arg.expression.as(DeclReferenceExprSyntax.self), file: file, line: line).baseName + let token: TokenSyntax = try XCTUnwrap(arg.expression.as(DeclReferenceExprSyntax.self), file: file, line: line) + .baseName try assertRefactor( token, @@ -382,7 +385,8 @@ fileprivate func assertRefactorPlaceholderToken( var parser = Parser(expr) let call = try XCTUnwrap(ExprSyntax.parse(from: &parser).as(FunctionCallExprSyntax.self), file: file, line: line) let arg = call.arguments[call.arguments.index(at: placeholder)] - let token: TokenSyntax = try XCTUnwrap(arg.expression.as(DeclReferenceExprSyntax.self), file: file, line: line).baseName + let token: TokenSyntax = try XCTUnwrap(arg.expression.as(DeclReferenceExprSyntax.self), file: file, line: line) + .baseName try assertRefactor( token, diff --git a/Tests/SwiftRefactorTest/FormatRawStringLiteral.swift b/Tests/SwiftRefactorTest/FormatRawStringLiteral.swift index 414c26263a6..59d5f3e8012 100644 --- a/Tests/SwiftRefactorTest/FormatRawStringLiteral.swift +++ b/Tests/SwiftRefactorTest/FormatRawStringLiteral.swift @@ -26,14 +26,23 @@ final class FormatRawStringLiteralTest: XCTestCase { (#line, literal: #####" "####" "#####, expectation: #####" "####" "#####), (#line, literal: #####" #"####"# "#####, expectation: ######" #####"####"##### "######), (#line, literal: #####" #"\####(hello)"# "#####, expectation: ######" #####"\####(hello)"##### "######), - (#line, literal: #######" #"###### \####(hello) ##"# "#######, expectation: ########" #######"###### \####(hello) ##"####### "########), + ( + #line, literal: #######" #"###### \####(hello) ##"# "#######, + expectation: ########" #######"###### \####(hello) ##"####### "######## + ), (#line, literal: ########" #######"hello \(world) "####### "########, expectation: #" "hello \(world) " "#), ] for (line, literal, expectation) in tests { let literal = try XCTUnwrap(StringLiteralExprSyntax.parseWithoutDiagnostics(from: literal)) let expectation = try XCTUnwrap(StringLiteralExprSyntax.parseWithoutDiagnostics(from: expectation)) - try assertRefactor(literal, context: (), provider: FormatRawStringLiteral.self, expected: expectation, line: UInt(line)) + try assertRefactor( + literal, + context: (), + provider: FormatRawStringLiteral.self, + expected: expectation, + line: UInt(line) + ) } } } diff --git a/Tests/SwiftRefactorTest/MigrateToNewIfLetSyntax.swift b/Tests/SwiftRefactorTest/MigrateToNewIfLetSyntax.swift index c44fdce80a4..34332dd32e5 100644 --- a/Tests/SwiftRefactorTest/MigrateToNewIfLetSyntax.swift +++ b/Tests/SwiftRefactorTest/MigrateToNewIfLetSyntax.swift @@ -99,6 +99,11 @@ final class MigrateToNewIfLetSyntaxTest: XCTestCase { """ let exprStmt = try XCTUnwrap(baselineSyntax.as(ExpressionStmtSyntax.self)) - try assertRefactor(exprStmt.expression, context: (), provider: MigrateToNewIfLetSyntax.self, expected: expectedSyntax) + try assertRefactor( + exprStmt.expression, + context: (), + provider: MigrateToNewIfLetSyntax.self, + expected: expectedSyntax + ) } } diff --git a/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift b/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift index a9b6d42080d..b5071126545 100644 --- a/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/DoStmtTests.swift @@ -68,7 +68,10 @@ final class DoStmtTests: XCTestCase { func testDoStmtWithExclamationMark() { let buildable = DoStmtSyntax( body: CodeBlockSyntax(statementsBuilder: { - TryExprSyntax(questionOrExclamationMark: .exclamationMarkToken(), expression: FunctionCallExprSyntax(callee: ExprSyntax("a.b"))) + TryExprSyntax( + questionOrExclamationMark: .exclamationMarkToken(), + expression: FunctionCallExprSyntax(callee: ExprSyntax("a.b")) + ) }), catchClauses: [ CatchClauseSyntax( @@ -118,7 +121,10 @@ final class DoStmtTests: XCTestCase { func testDoStmtWithPostfixQuestionMark() { let buildable = DoStmtSyntax( body: CodeBlockSyntax(statementsBuilder: { - TryExprSyntax(questionOrExclamationMark: .postfixQuestionMarkToken(), expression: FunctionCallExprSyntax(callee: ExprSyntax("a.b"))) + TryExprSyntax( + questionOrExclamationMark: .postfixQuestionMarkToken(), + expression: FunctionCallExprSyntax(callee: ExprSyntax("a.b")) + ) }), catchClauses: [ CatchClauseSyntax( diff --git a/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift b/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift index c18f22f6d85..b8c64162f86 100644 --- a/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/FunctionTests.swift @@ -182,7 +182,9 @@ final class FunctionTests: XCTestCase { #line: ( DeclSyntax( FunctionDeclSyntax( - attributes: [.attribute(AttributeSyntax("@inline(__always)")), .attribute(AttributeSyntax("@discardableResult"))], + attributes: [ + .attribute(AttributeSyntax("@inline(__always)")), .attribute(AttributeSyntax("@discardableResult")), + ], modifiers: [DeclModifierSyntax(name: .keyword(.public))], name: TokenSyntax.identifier("foo"), signature: FunctionSignatureSyntax( @@ -212,8 +214,16 @@ final class FunctionTests: XCTestCase { signature: FunctionSignatureSyntax( parameterClause: FunctionParameterClauseSyntax( parameters: FunctionParameterListSyntax { - FunctionParameterSyntax(firstName: TokenSyntax.identifier("lhs"), colon: .colonToken(), type: TypeSyntax("String")) - FunctionParameterSyntax(firstName: TokenSyntax.identifier("rhs"), colon: .colonToken(), type: TypeSyntax("String")) + FunctionParameterSyntax( + firstName: TokenSyntax.identifier("lhs"), + colon: .colonToken(), + type: TypeSyntax("String") + ) + FunctionParameterSyntax( + firstName: TokenSyntax.identifier("rhs"), + colon: .colonToken(), + type: TypeSyntax("String") + ) } ), returnClause: ReturnClauseSyntax( @@ -247,10 +257,26 @@ final class FunctionTests: XCTestCase { signature: FunctionSignatureSyntax( parameterClause: FunctionParameterClauseSyntax( parameters: FunctionParameterListSyntax { - FunctionParameterSyntax(firstName: TokenSyntax.identifier("lhs1"), colon: .colonToken(), type: TypeSyntax("String")) - FunctionParameterSyntax(firstName: TokenSyntax.identifier("lhs2"), colon: .colonToken(), type: TypeSyntax("String")) - FunctionParameterSyntax(firstName: TokenSyntax.identifier("rhs1"), colon: .colonToken(), type: TypeSyntax("String")) - FunctionParameterSyntax(firstName: TokenSyntax.identifier("rhs2"), colon: .colonToken(), type: TypeSyntax("String")) + FunctionParameterSyntax( + firstName: TokenSyntax.identifier("lhs1"), + colon: .colonToken(), + type: TypeSyntax("String") + ) + FunctionParameterSyntax( + firstName: TokenSyntax.identifier("lhs2"), + colon: .colonToken(), + type: TypeSyntax("String") + ) + FunctionParameterSyntax( + firstName: TokenSyntax.identifier("rhs1"), + colon: .colonToken(), + type: TypeSyntax("String") + ) + FunctionParameterSyntax( + firstName: TokenSyntax.identifier("rhs2"), + colon: .colonToken(), + type: TypeSyntax("String") + ) } ), returnClause: ReturnClauseSyntax( @@ -287,7 +313,10 @@ final class FunctionTests: XCTestCase { func testArguments() { let buildable = FunctionCallExprSyntax(callee: ExprSyntax("test")) { for param in (1...5) { - LabeledExprSyntax(label: param.isMultiple(of: 2) ? "p\(param)" : nil, expression: ExprSyntax("value\(raw: param)")) + LabeledExprSyntax( + label: param.isMultiple(of: 2) ? "p\(param)" : nil, + expression: ExprSyntax("value\(raw: param)") + ) } } assertBuildResult(buildable, "test(value1, p2: value2, value3, p4: value4, value5)") diff --git a/Tests/SwiftSyntaxBuilderTest/FunctionTypeSyntaxTests.swift b/Tests/SwiftSyntaxBuilderTest/FunctionTypeSyntaxTests.swift index 4c20c041124..9b00392cf42 100644 --- a/Tests/SwiftSyntaxBuilderTest/FunctionTypeSyntaxTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/FunctionTypeSyntaxTests.swift @@ -16,7 +16,10 @@ import XCTest final class FunctionTypeSyntaxTests: XCTestCase { func testFunctionEffectSpecifiersSyntax() throws { - let typeEffects = TypeEffectSpecifiersSyntax(asyncSpecifier: .keyword(.async), throwsClause: ThrowsClauseSyntax(throwsSpecifier: .keyword(.throws))) + let typeEffects = TypeEffectSpecifiersSyntax( + asyncSpecifier: .keyword(.async), + throwsClause: ThrowsClauseSyntax(throwsSpecifier: .keyword(.throws)) + ) let buildable = FunctionTypeSyntax( parameters: [], effectSpecifiers: typeEffects, diff --git a/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift b/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift index d85b07ae3e7..2fd4cd6bb63 100644 --- a/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/IfStmtTests.swift @@ -88,7 +88,11 @@ final class IfStmtTests: XCTestCase { """ ), #line: ( - try IfExprSyntax("if foo == x", bodyBuilder: { StmtSyntax("return foo") }, elseIf: IfExprSyntax("if foo == z") { StmtSyntax("return baz") }), + try IfExprSyntax( + "if foo == x", + bodyBuilder: { StmtSyntax("return foo") }, + elseIf: IfExprSyntax("if foo == z") { StmtSyntax("return baz") } + ), """ if foo == x { return foo diff --git a/Tests/SwiftSyntaxBuilderTest/StringInterpolationTests.swift b/Tests/SwiftSyntaxBuilderTest/StringInterpolationTests.swift index 605d1e2df7c..d5e57c2bbaa 100644 --- a/Tests/SwiftSyntaxBuilderTest/StringInterpolationTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/StringInterpolationTests.swift @@ -442,7 +442,10 @@ final class StringInterpolationTests: XCTestCase { func testInvalidTrivia() { let invalid = Trivia("/*comment*/ invalid /*comm*/") - XCTAssertEqual(invalid, [.blockComment("/*comment*/"), .spaces(1), .unexpectedText("invalid"), .spaces(1), .blockComment("/*comm*/")]) + XCTAssertEqual( + invalid, + [.blockComment("/*comment*/"), .spaces(1), .unexpectedText("invalid"), .spaces(1), .blockComment("/*comm*/")] + ) XCTAssertThrowsError(try Trivia(validating: "/*comment*/ invalid /*comm*/")) { error in assertStringsEqualWithDiff( diff --git a/Tests/SwiftSyntaxBuilderTest/StringLiteralExprSyntaxTests.swift b/Tests/SwiftSyntaxBuilderTest/StringLiteralExprSyntaxTests.swift index 3edeec0e47e..6120681456c 100644 --- a/Tests/SwiftSyntaxBuilderTest/StringLiteralExprSyntaxTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/StringLiteralExprSyntaxTests.swift @@ -214,7 +214,9 @@ final class StringLiteralExprSyntaxTests: XCTestCase { } func testStringSegmentWithCode() { - let buildable = StringSegmentSyntax(content: .stringSegment(#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#)) + let buildable = StringSegmentSyntax( + content: .stringSegment(#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#) + ) assertBuildResult( buildable, @@ -224,10 +226,18 @@ final class StringLiteralExprSyntaxTests: XCTestCase { func testStringLiteralSegmentWithCode() { let buildable = StringLiteralSegmentListSyntax { - StringSegmentSyntax(content: .stringSegment(#"Error validating child at index \(index) of \(nodeKind):"#), trailingTrivia: .newline) - StringSegmentSyntax(content: .stringSegment(#"Node did not satisfy any node choice requirement."#), trailingTrivia: .newline) + StringSegmentSyntax( + content: .stringSegment(#"Error validating child at index \(index) of \(nodeKind):"#), + trailingTrivia: .newline + ) + StringSegmentSyntax( + content: .stringSegment(#"Node did not satisfy any node choice requirement."#), + trailingTrivia: .newline + ) StringSegmentSyntax(content: .stringSegment(#"Validation failures:"#), trailingTrivia: .newline) - StringSegmentSyntax(content: .stringSegment(#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#)) + StringSegmentSyntax( + content: .stringSegment(#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#) + ) } assertBuildResult( @@ -245,12 +255,20 @@ final class StringLiteralExprSyntaxTests: XCTestCase { let buildable = StringLiteralExprSyntax( openingQuote: .multilineStringQuoteToken(), segments: StringLiteralSegmentListSyntax { - StringSegmentSyntax(content: .stringSegment(#"Error validating child at index \(index) of \(nodeKind):"#), trailingTrivia: .newline) - StringSegmentSyntax(content: .stringSegment(#"Node did not satisfy any node choice requirement."#), trailingTrivia: .newline) + StringSegmentSyntax( + content: .stringSegment(#"Error validating child at index \(index) of \(nodeKind):"#), + trailingTrivia: .newline + ) + StringSegmentSyntax( + content: .stringSegment(#"Node did not satisfy any node choice requirement."#), + trailingTrivia: .newline + ) StringSegmentSyntax(content: .stringSegment(#"Validation failures:"#), trailingTrivia: .newline) ExpressionSegmentSyntax( expressions: LabeledExprListSyntax { - LabeledExprSyntax(expression: ExprSyntax(#"nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n")"#)) + LabeledExprSyntax( + expression: ExprSyntax(#"nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n")"#) + ) } ) }, @@ -355,7 +373,11 @@ final class StringLiteralExprSyntaxTests: XCTestCase { func testMultiStringOpeningQuote() { assertBuildResult( - StringLiteralExprSyntax(openingQuote: .multilineStringQuoteToken(), content: "a", closingQuote: .multilineStringQuoteToken()), + StringLiteralExprSyntax( + openingQuote: .multilineStringQuoteToken(), + content: "a", + closingQuote: .multilineStringQuoteToken() + ), #""" """ a diff --git a/Tests/SwiftSyntaxBuilderTest/VariableTests.swift b/Tests/SwiftSyntaxBuilderTest/VariableTests.swift index 9c384a1f470..e2b6905de63 100644 --- a/Tests/SwiftSyntaxBuilderTest/VariableTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/VariableTests.swift @@ -19,7 +19,10 @@ final class VariableTests: XCTestCase { let leadingTrivia = Trivia.unexpectedText("␣") let buildable = VariableDeclSyntax(leadingTrivia: leadingTrivia, bindingSpecifier: .keyword(.let)) { - PatternBindingSyntax(pattern: PatternSyntax("a"), typeAnnotation: TypeAnnotationSyntax(type: ArrayTypeSyntax(element: TypeSyntax("Int")))) + PatternBindingSyntax( + pattern: PatternSyntax("a"), + typeAnnotation: TypeAnnotationSyntax(type: ArrayTypeSyntax(element: TypeSyntax("Int"))) + ) } assertBuildResult(buildable, "␣let a: [Int]") @@ -29,7 +32,10 @@ final class VariableTests: XCTestCase { let leadingTrivia = Trivia.unexpectedText("␣") let buildable = VariableDeclSyntax(leadingTrivia: leadingTrivia, bindingSpecifier: .keyword(.inout)) { - PatternBindingSyntax(pattern: PatternSyntax("a"), typeAnnotation: TypeAnnotationSyntax(type: ArrayTypeSyntax(element: TypeSyntax("Int")))) + PatternBindingSyntax( + pattern: PatternSyntax("a"), + typeAnnotation: TypeAnnotationSyntax(type: ArrayTypeSyntax(element: TypeSyntax("Int"))) + ) } assertBuildResult(buildable, "␣inout a: [Int]") @@ -161,7 +167,9 @@ final class VariableTests: XCTestCase { let buildable = VariableDeclSyntax(leadingTrivia: leadingTrivia, bindingSpecifier: .keyword(.var)) { PatternBindingSyntax( pattern: PatternSyntax("d"), - typeAnnotation: TypeAnnotationSyntax(type: DictionaryTypeSyntax(key: TypeSyntax("String"), value: TypeSyntax("Int"))), + typeAnnotation: TypeAnnotationSyntax( + type: DictionaryTypeSyntax(key: TypeSyntax("String"), value: TypeSyntax("Int")) + ), initializer: InitializerClauseSyntax(value: DictionaryExprSyntax()) ) } @@ -213,13 +221,19 @@ final class VariableTests: XCTestCase { initializer: InitializerClauseSyntax( value: DictionaryExprSyntax { for i in 1...3 { - DictionaryElementSyntax(key: StringLiteralExprSyntax(content: "key\(i)"), value: IntegerLiteralExprSyntax(i)) + DictionaryElementSyntax( + key: StringLiteralExprSyntax(content: "key\(i)"), + value: IntegerLiteralExprSyntax(i) + ) } } ) ) PatternBindingSyntax(pattern: PatternSyntax("i"), typeAnnotation: TypeAnnotationSyntax(type: TypeSyntax("Int"))) - PatternBindingSyntax(pattern: PatternSyntax("s"), typeAnnotation: TypeAnnotationSyntax(type: TypeSyntax("String"))) + PatternBindingSyntax( + pattern: PatternSyntax("s"), + typeAnnotation: TypeAnnotationSyntax(type: TypeSyntax("String")) + ) } assertBuildResult(buildable, #"let a = [1, 2, 3], d = ["key1": 1, "key2": 2, "key3": 3], i: Int, s: String"#) } diff --git a/Tests/SwiftSyntaxMacroExpansionTest/DeclarationMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/DeclarationMacroTests.swift index a25710cd41a..20ac099d3c6 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/DeclarationMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/DeclarationMacroTests.swift @@ -91,8 +91,18 @@ final class DeclarationMacroTests: XCTestCase { } """, diagnostics: [ - DiagnosticSpec(message: "please don't do that", line: 1, column: 1, highlights: [#"#myError("please don't do that")"#]), - DiagnosticSpec(message: "#error macro requires a string literal", line: 4, column: 3, highlights: [#"#myError(bad)"#]), + DiagnosticSpec( + message: "please don't do that", + line: 1, + column: 1, + highlights: [#"#myError("please don't do that")"#] + ), + DiagnosticSpec( + message: "#error macro requires a string literal", + line: 4, + column: 3, + highlights: [#"#myError(bad)"#] + ), DiagnosticSpec(message: "worse", line: 6, column: 5, highlights: [#"#myError("worse")"#]), ], macros: ["myError": ErrorMacro.self], diff --git a/Tests/SwiftSyntaxMacroExpansionTest/ExtensionMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/ExtensionMacroTests.swift index f3364781e06..eb6dae3773f 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/ExtensionMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/ExtensionMacroTests.swift @@ -206,7 +206,9 @@ final class ExtensionMacroTests: XCTestCase { extension MyType: Encodable { } """, - macroSpecs: ["AddCodableExtensions": MacroSpec(type: CodableExtensionMacro.self, conformances: ["Decodable", "Encodable"])], + macroSpecs: [ + "AddCodableExtensions": MacroSpec(type: CodableExtensionMacro.self, conformances: ["Decodable", "Encodable"]) + ], indentationWidth: indentationWidth ) diff --git a/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift index 239cf789b33..042c7bf592e 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/MemberMacroTests.swift @@ -539,7 +539,9 @@ final class MemberMacroTests: XCTestCase { } } """, - macroSpecs: ["AddCodableExtensions": MacroSpec(type: CodableExtensionMacro.self, conformances: ["Decodable", "Encodable"])], + macroSpecs: [ + "AddCodableExtensions": MacroSpec(type: CodableExtensionMacro.self, conformances: ["Decodable", "Encodable"]) + ], indentationWidth: indentationWidth ) diff --git a/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift index 0843ed5302c..29e35353a63 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/MultiRoleMacroTests.swift @@ -208,15 +208,20 @@ final class MultiRoleMacroTests: XCTestCase { func testAttachedMacroOnFreestandingMacro() { struct DeclMacro: DeclarationMacro { - static func expansion(of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext) throws -> [DeclSyntax] { + static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { return ["var x: Int"] } } struct MyPeerMacro: PeerMacro { - static func expansion(of node: AttributeSyntax, providingPeersOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext) throws - -> [DeclSyntax] - { + static func expansion( + of node: AttributeSyntax, + providingPeersOf declaration: some DeclSyntaxProtocol, + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { return ["var peer: Int"] } } diff --git a/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift index 3e8634ce8d4..f5a5ad812cf 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/PeerMacroTests.swift @@ -90,7 +90,9 @@ final class PeerMacroTests: XCTestCase { var newParameterList = parameterList if !parameterList.isEmpty { // We need to add a trailing comma to the preceding list. - newParameterList[newParameterList.index(before: newParameterList.endIndex)].trailingComma = .commaToken(trailingTrivia: .space) + newParameterList[newParameterList.index(before: newParameterList.endIndex)].trailingComma = .commaToken( + trailingTrivia: .space + ) } newParameterList.append(completionHandlerParam) diff --git a/Tests/SwiftSyntaxMacroExpansionTest/StringInterpolationErrorTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/StringInterpolationErrorTests.swift index 2656cbf2a96..04ab30693ba 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/StringInterpolationErrorTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/StringInterpolationErrorTests.swift @@ -44,7 +44,10 @@ final class StringInterpolationErrorTests: XCTestCase { func testMacroExpansionContextAddDiagnosticsAddsSwiftSyntaxInterpolationErrorsWithWrappingMessage() throws { let context = BasicMacroExpansionContext(lexicalContext: []) - let error = SyntaxStringInterpolationInvalidNodeTypeError(expectedType: DeclSyntax.self, actualNode: ExprSyntax("test")) + let error = SyntaxStringInterpolationInvalidNodeTypeError( + expectedType: DeclSyntax.self, + actualNode: ExprSyntax("test") + ) // Since we only care about the error switch inside of addDagnostics, we don't care about the particular node we're passing in context.addDiagnostics(from: error, node: ExprSyntax("1")) @@ -66,7 +69,8 @@ final class StringInterpolationErrorTests: XCTestCase { func testMacroExpansionSyntaxInterpolationErrorGetsPrefixed() { let expectedDiagnostic = DiagnosticSpec( - message: "Internal macro error: Parsing the code snippet was expected to produce a ExtensionDeclSyntax but produced a DeclSyntax", + message: + "Internal macro error: Parsing the code snippet was expected to produce a ExtensionDeclSyntax but produced a DeclSyntax", line: 1, column: 1 ) diff --git a/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift b/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift index ed2a18161bc..9094f44e396 100644 --- a/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift +++ b/Tests/SwiftSyntaxTest/DebugDescriptionTests.swift @@ -171,6 +171,7 @@ class DebugDescriptionTests: XCTestCase { #if DEBUG // debugInitCall is only available in debug builds, so we can only test it in those. + // swift-format-ignore @available(*, deprecated, message: "Purposefully tests debugInitCall, which is marked deprecated for debugger use only") func testDebugInitCall() { let sourceFile: SourceFileSyntax = """ diff --git a/Tests/SwiftSyntaxTest/SyntaxCreationTests.swift b/Tests/SwiftSyntaxTest/SyntaxCreationTests.swift index f9e88fd2c9c..bde8943a31f 100644 --- a/Tests/SwiftSyntaxTest/SyntaxCreationTests.swift +++ b/Tests/SwiftSyntaxTest/SyntaxCreationTests.swift @@ -110,7 +110,9 @@ class SyntaxCreationTests: XCTestCase { public func testFunctionCallSyntaxBuilder() { let string = StringLiteralExprSyntax( openingQuote: .stringQuoteToken(), - segments: StringLiteralSegmentListSyntax([.stringSegment(StringSegmentSyntax(content: .stringSegment("Hello, world!")))]), + segments: StringLiteralSegmentListSyntax([ + .stringSegment(StringSegmentSyntax(content: .stringSegment("Hello, world!"))) + ]), closingQuote: .stringQuoteToken() ) let printID = DeclReferenceExprSyntax(baseName: .identifier("print")) @@ -154,7 +156,9 @@ class SyntaxCreationTests: XCTestCase { let string = StringLiteralExprSyntax( openingPounds: nil, openingQuote: .stringQuoteToken(), - segments: StringLiteralSegmentListSyntax([.stringSegment(StringSegmentSyntax(content: .stringSegment("Hello, world!")))]), + segments: StringLiteralSegmentListSyntax([ + .stringSegment(StringSegmentSyntax(content: .stringSegment("Hello, world!"))) + ]), closingQuote: .stringQuoteToken(), closingPounds: nil ) @@ -184,7 +188,9 @@ class SyntaxCreationTests: XCTestCase { public func testMakeStringLiteralExpr() { let expr = StringLiteralExprSyntax( openingQuote: .stringQuoteToken(leadingTrivia: [.lineComment("// hello"), .newlines(1)]), - segments: StringLiteralSegmentListSyntax([.stringSegment(StringSegmentSyntax(content: .stringSegment("Hello, world!")))]), + segments: StringLiteralSegmentListSyntax([ + .stringSegment(StringSegmentSyntax(content: .stringSegment("Hello, world!"))) + ]), closingQuote: .stringQuoteToken() ) let expected = """ diff --git a/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift b/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift index 322325e1bcb..0e2b3ff9ec1 100644 --- a/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift +++ b/Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift @@ -71,7 +71,9 @@ class SyntaxVisitorTests: XCTestCase { item: CodeBlockItemSyntax.Item( FunctionDeclSyntax( modifiers: DeclModifierListSyntax([ - DeclModifierSyntax(name: .keyword(.public, leadingTrivia: [.newlines(1), .spaces(2)], trailingTrivia: .space)) + DeclModifierSyntax( + name: .keyword(.public, leadingTrivia: [.newlines(1), .spaces(2)], trailingTrivia: .space) + ) ]), funcKeyword: .keyword(.func, trailingTrivia: .space), name: .identifier("foo"), @@ -88,7 +90,11 @@ class SyntaxVisitorTests: XCTestCase { CodeBlockItemSyntax( item: CodeBlockItemSyntax.Item( FunctionDeclSyntax( - funcKeyword: .keyword(.func, leadingTrivia: [.newlines(1), .spaces(4)], trailingTrivia: .space), + funcKeyword: .keyword( + .func, + leadingTrivia: [.newlines(1), .spaces(4)], + trailingTrivia: .space + ), name: .identifier("foo"), signature: FunctionSignatureSyntax( parameterClause: FunctionParameterClauseSyntax( diff --git a/Tests/SwiftSyntaxTest/VisitorTests.swift b/Tests/SwiftSyntaxTest/VisitorTests.swift index 1a83c26087a..d12618bd768 100644 --- a/Tests/SwiftSyntaxTest/VisitorTests.swift +++ b/Tests/SwiftSyntaxTest/VisitorTests.swift @@ -63,11 +63,16 @@ class VisitorTests: XCTestCase { public func testVisitUnexpected() { // This is just bunch of unexpected let unexpectedReturnStmt = ReturnStmtSyntax( - UnexpectedNodesSyntax([Syntax(TokenSyntax.identifier("starting")), Syntax(TokenSyntax.integerLiteral("unexpected"))]), + 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: [])) + NilLiteralExprSyntax( + UnexpectedNodesSyntax([Syntax(TokenSyntax.identifier("end"))]), + nilKeyword: TokenSyntax.keyword(.nil, trailingTrivia: []) + ) ) ) @@ -101,7 +106,10 @@ class VisitorTests: XCTestCase { } XCTAssertEqual(TreePrinter.print(unexpectedReturnStmt, viewMode: .fixedUp), "return nil") - XCTAssertEqual(TreePrinter.print(unexpectedReturnStmt, viewMode: .sourceAccurate), "startingunexpectedreturn middleendnil") + XCTAssertEqual( + TreePrinter.print(unexpectedReturnStmt, viewMode: .sourceAccurate), + "startingunexpectedreturn middleendnil" + ) XCTAssertEqual(TreePrinter.print(misspelledNil, viewMode: .fixedUp), "return nil") XCTAssertEqual(TreePrinter.print(misspelledNil, viewMode: .sourceAccurate), "return null") @@ -127,7 +135,10 @@ class VisitorTests: XCTestCase { } XCTAssertEqual(AnyTreePrinter.print(unexpectedReturnStmt, viewMode: .fixedUp), "return nil") - XCTAssertEqual(AnyTreePrinter.print(unexpectedReturnStmt, viewMode: .sourceAccurate), "startingunexpectedreturn middleendnil") + XCTAssertEqual( + AnyTreePrinter.print(unexpectedReturnStmt, viewMode: .sourceAccurate), + "startingunexpectedreturn middleendnil" + ) XCTAssertEqual(AnyTreePrinter.print(misspelledNil, viewMode: .fixedUp), "return nil") XCTAssertEqual(AnyTreePrinter.print(misspelledNil, viewMode: .sourceAccurate), "return null") @@ -151,7 +162,10 @@ class VisitorTests: XCTestCase { } XCTAssertEqual(RewritingTreePrinter.print(unexpectedReturnStmt, viewMode: .fixedUp), "return nil") - XCTAssertEqual(RewritingTreePrinter.print(unexpectedReturnStmt, viewMode: .sourceAccurate), "startingunexpectedreturn middleendnil") + XCTAssertEqual( + RewritingTreePrinter.print(unexpectedReturnStmt, viewMode: .sourceAccurate), + "startingunexpectedreturn middleendnil" + ) XCTAssertEqual(RewritingTreePrinter.print(misspelledNil, viewMode: .fixedUp), "return nil") XCTAssertEqual(RewritingTreePrinter.print(misspelledNil, viewMode: .sourceAccurate), "return null")