diff --git a/.bazelrc b/.bazelrc index aab718dde75..1398860584a 100644 --- a/.bazelrc +++ b/.bazelrc @@ -5,4 +5,12 @@ common --lockfile_mode=off build --features=swift.use_explicit_swift_module_map build --host_features=swift.use_explicit_swift_module_map +# Improved build performance +build --host_swiftcopt=-whole-module-optimization +build --swiftcopt=-whole-module-optimization + +# Keep in sync with Package.swift +build --host_macos_minimum_os=10.15 +build --macos_minimum_os=10.15 + test --test_output=errors diff --git a/.github/ISSUE_TEMPLATE/BASICFORMAT_BUG.yml b/.github/ISSUE_TEMPLATE/BASICFORMAT_BUG.yml index 6ceb4355bd8..a2c8f864f8e 100644 --- a/.github/ISSUE_TEMPLATE/BASICFORMAT_BUG.yml +++ b/.github/ISSUE_TEMPLATE/BASICFORMAT_BUG.yml @@ -4,7 +4,7 @@ labels: [bug, BasicFormat] body: - type: markdown attributes: - value: Thanks for taking the time to fill out this bug report! We would really appreciate if you could take the time to reduce the issue as described in [Filing BasicFormat Bug Reports](https://swiftpackageindex.com/apple/swift-syntax/main/documentation/swiftbasicformat/filingbugreports). + value: Thanks for taking the time to fill out this bug report! We would really appreciate if you could take the time to reduce the issue as described in [Filing BasicFormat Bug Reports](https://swiftpackageindex.com/swiftlang/swift-syntax/main/documentation/swiftbasicformat/filingbugreports). - type: textarea id: source attributes: diff --git a/.github/ISSUE_TEMPLATE/PARSER_BUG.yml b/.github/ISSUE_TEMPLATE/PARSER_BUG.yml index 9209d31340f..7cf33b92d27 100644 --- a/.github/ISSUE_TEMPLATE/PARSER_BUG.yml +++ b/.github/ISSUE_TEMPLATE/PARSER_BUG.yml @@ -4,12 +4,12 @@ labels: [bug, SwiftParser] body: - type: markdown attributes: - value: Thanks for taking the time to fill out this bug report! We would really appreciate if you could take the time to reduce the issue as described in [Filing Parser Bug Reports](https://swiftpackageindex.com/apple/swift-syntax/main/documentation/swiftparser/filingbugreports). + value: Thanks for taking the time to fill out this bug report! We would really appreciate if you could take the time to reduce the issue as described in [Filing Parser Bug Reports](https://swiftpackageindex.com/swiftlang/swift-syntax/main/documentation/swiftparser/filingbugreports). - type: dropdown id: issue-type attributes: label: Issue Kind - description: What kind of issue is this? See [Filing Parser Bug Reports](https://swiftpackageindex.com/apple/swift-syntax/main/documentation/swiftparser/filingbugreports) for more details. + description: What kind of issue is this? See [Filing Parser Bug Reports](https://swiftpackageindex.com/swiftlang/swift-syntax/main/documentation/swiftparser/filingbugreports) for more details. options: - Round-Trip Failure - Parser Crash diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index f764474c665..abe51dbfea7 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -11,5 +11,5 @@ url: https://forums.swift.org/tags/c/development/tooling/39/swift-syntax about: Ask and answer questions about SwiftSyntax - name: SwiftSyntax Documentation - url: https://swiftpackageindex.com/apple/swift-syntax/documentation/swiftsyntax + url: https://swiftpackageindex.com/swiftlang/swift-syntax/documentation/swiftsyntax about: Learn about how to use the SwiftSyntax in your projects diff --git a/.spi.yml b/.spi.yml index 5b8d735168a..7572213ba27 100644 --- a/.spi.yml +++ b/.spi.yml @@ -10,7 +10,6 @@ builder: - SwiftSyntax - SwiftBasicFormat - SwiftCompilerPlugin - - SwiftCompilerPluginMessageHandling - SwiftDiagnostics - SwiftIDEUtils - SwiftOperators @@ -20,5 +19,6 @@ builder: - SwiftSyntaxBuilder - SwiftSyntaxMacros - SwiftSyntaxMacroExpansion + - SwiftSyntaxMacrosGenericTestSupport - SwiftSyntaxMacrosTestSupport custom_documentation_parameters: [--experimental-skip-synthesized-symbols] 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/BUILD.bazel b/BUILD.bazel index 17ae67730be..cc2c901c880 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -1,34 +1,21 @@ -load("//utils/bazel:swift_syntax_library.bzl", "swift_syntax_library") +load("@build_bazel_rules_apple//apple/testing/default_runner:ios_xctestrun_runner.bzl", "ios_xctestrun_runner") +load("//utils/bazel:swift_syntax_library.bzl", "swift_syntax_library", "swift_syntax_test") package(default_visibility = ["//visibility:public"]) -cc_library( - name = "_AtomicBool", - srcs = glob(["Sources/_AtomicBool/src/*.c"]), - hdrs = glob(["Sources/_AtomicBool/include/*.h"]), - includes = ["Sources/_AtomicBool/include"], - tags = ["swift_module=_AtomicBool"], -) - swift_syntax_library( - name = "SwiftIDEUtils", + name = "SwiftBasicFormat", deps = [ - ":SwiftParser", ":SwiftSyntax", ], ) -swift_syntax_library( - name = "SwiftSyntax", +swift_syntax_test( + name = "SwiftBasicFormatTest", deps = [ - ":_AtomicBool", - ], -) - -swift_syntax_library( - name = "SwiftBasicFormat", - deps = [ - ":SwiftSyntax", + ":SwiftBasicFormat", + ":SwiftSyntaxBuilder", + ":_SwiftSyntaxTestSupport", ], ) @@ -46,42 +33,77 @@ swift_syntax_library( ":SwiftDiagnostics", ":SwiftOperators", ":SwiftParser", + ":SwiftSyntax", ":SwiftSyntaxMacroExpansion", ":SwiftSyntaxMacros", + ":_SwiftSyntaxCShims", + ], +) + +swift_syntax_test( + name = "SwiftCompilerPluginTest", + deps = [ + ":SwiftCompilerPlugin", ], ) swift_syntax_library( - name = "SwiftSyntaxMacroExpansion", + name = "SwiftDiagnostics", deps = [ - ":SwiftOperators", ":SwiftSyntax", - ":SwiftSyntaxMacros", + ], +) + +swift_syntax_test( + name = "SwiftDiagnosticsTest", + deps = [ + ":SwiftDiagnostics", + ":SwiftParser", + ":SwiftParserDiagnostics", + ":_SwiftSyntaxTestSupport", ], ) swift_syntax_library( - name = "SwiftDiagnostics", + name = "SwiftIDEUtils", deps = [ + ":SwiftDiagnostics", + ":SwiftParser", + ":SwiftSyntax", + ], +) + +swift_syntax_test( + name = "SwiftIDEUtilsTest", + deps = [ + ":SwiftIDEUtils", + ":SwiftParser", ":SwiftSyntax", + ":_SwiftSyntaxTestSupport", ], ) swift_syntax_library( - name = "SwiftSyntaxMacros", + name = "SwiftOperators", deps = [ ":SwiftDiagnostics", ":SwiftParser", ":SwiftSyntax", - ":SwiftSyntaxBuilder", + ], +) + +swift_syntax_test( + name = "SwiftOperatorsTest", + deps = [ + ":SwiftOperators", + ":SwiftParser", + ":_SwiftSyntaxTestSupport", ], ) swift_syntax_library( name = "SwiftParser", deps = [ - ":SwiftBasicFormat", - ":SwiftDiagnostics", ":SwiftSyntax", ], ) @@ -96,46 +118,208 @@ swift_syntax_library( ], ) +swift_syntax_test( + name = "SwiftParserDiagnosticsTest", + deps = [ + ":SwiftDiagnostics", + ":SwiftParserDiagnostics", + ], +) + +swift_syntax_test( + name = "SwiftParserTest", + deps = [ + ":SwiftDiagnostics", + ":SwiftIDEUtils", + ":SwiftOperators", + ":SwiftParser", + ":SwiftSyntaxBuilder", + ":_SwiftSyntaxTestSupport", + ], +) + +swift_syntax_library( + name = "SwiftRefactor", + deps = [ + ":SwiftBasicFormat", + ":SwiftParser", + ":SwiftSyntax", + ":SwiftSyntaxBuilder", + ], +) + +swift_syntax_test( + name = "SwiftRefactorTest", + deps = [ + ":SwiftRefactor", + ":_SwiftSyntaxTestSupport", + ], +) + +swift_syntax_library( + name = "SwiftSyntax", + deps = [ + ":SwiftSyntax509", + ":SwiftSyntax510", + ":SwiftSyntax600", + ":_SwiftSyntaxCShims", + ], +) + +swift_syntax_library( + name = "SwiftSyntax509", + srcs = glob(["Sources/VersionMarkerModules/SwiftSyntax509/**/*.swift"]), + deps = [ + ], +) + +swift_syntax_library( + name = "SwiftSyntax510", + srcs = glob(["Sources/VersionMarkerModules/SwiftSyntax510/**/*.swift"]), + deps = [ + ], +) + +swift_syntax_library( + name = "SwiftSyntax600", + srcs = glob(["Sources/VersionMarkerModules/SwiftSyntax600/**/*.swift"]), + deps = [ + ], +) + swift_syntax_library( name = "SwiftSyntaxBuilder", deps = [ ":SwiftBasicFormat", + ":SwiftDiagnostics", ":SwiftParser", ":SwiftParserDiagnostics", ":SwiftSyntax", ], ) +swift_syntax_test( + name = "SwiftSyntaxBuilderTest", + deps = [ + ":SwiftSyntaxBuilder", + ":_SwiftSyntaxTestSupport", + ], +) + swift_syntax_library( - name = "SwiftOperators", + name = "SwiftSyntaxMacroExpansion", + deps = [ + ":SwiftDiagnostics", + ":SwiftOperators", + ":SwiftSyntax", + ":SwiftSyntaxBuilder", + ":SwiftSyntaxMacros", + ], +) + +swift_syntax_test( + name = "SwiftSyntaxMacroExpansionTest", deps = [ ":SwiftDiagnostics", + ":SwiftOperators", ":SwiftParser", ":SwiftSyntax", + ":SwiftSyntaxBuilder", + ":SwiftSyntaxMacroExpansion", + ":SwiftSyntaxMacros", + ":SwiftSyntaxMacrosTestSupport", + ":_SwiftSyntaxTestSupport", ], ) swift_syntax_library( - name = "SwiftRefactor", + name = "SwiftSyntaxMacros", deps = [ + ":SwiftDiagnostics", ":SwiftParser", ":SwiftSyntax", ":SwiftSyntaxBuilder", ], ) +swift_syntax_library( + name = "SwiftSyntaxMacrosGenericTestSupport", + testonly = True, + deps = [ + ":SwiftDiagnostics", + ":SwiftIDEUtils", + ":SwiftParser", + ":SwiftSyntaxMacroExpansion", + ":SwiftSyntaxMacros", + ":_SwiftSyntaxGenericTestSupport", + ], +) + swift_syntax_library( name = "SwiftSyntaxMacrosTestSupport", testonly = True, deps = [ ":SwiftDiagnostics", + ":SwiftIDEUtils", ":SwiftParser", ":SwiftSyntaxMacroExpansion", ":SwiftSyntaxMacros", + ":SwiftSyntaxMacrosGenericTestSupport", + ":_SwiftSyntaxTestSupport", + ], +) + +swift_syntax_test( + name = "SwiftSyntaxMacrosTestSupportTests", + deps = [ + ":SwiftDiagnostics", + ":SwiftSyntax", + ":SwiftSyntaxMacros", + ":SwiftSyntaxMacrosTestSupport", + ], +) + +swift_syntax_test( + name = "SwiftSyntaxTest", + deps = [ + ":SwiftSyntax", + ":SwiftSyntaxBuilder", ":_SwiftSyntaxTestSupport", ], ) +swift_syntax_test( + name = "SwiftSyntaxTestSupportTest", + deps = [ + ":SwiftParser", + ":_SwiftSyntaxTestSupport", + ], +) + +cc_library( + name = "_InstructionCounter", + srcs = glob(["Sources/_InstructionCounter/src/*.c"]), + hdrs = glob(["Sources/_InstructionCounter/include/*.h"]), + includes = ["Sources/_InstructionCounter/include"], + tags = ["swift_module=_InstructionCounter"], + visibility = ["//visibility:private"], +) + +cc_library( + name = "_SwiftSyntaxCShims", + hdrs = glob(["Sources/_SwiftSyntaxCShims/include/*.h"]), + includes = ["Sources/_SwiftSyntaxCShims/include"], + tags = ["swift_module=_SwiftSyntaxCShims"], + visibility = ["//visibility:private"], +) + +swift_syntax_library( + name = "_SwiftSyntaxGenericTestSupport", + testonly = True, + deps = [ + ], +) + swift_syntax_library( name = "_SwiftSyntaxTestSupport", testonly = True, @@ -144,5 +328,13 @@ swift_syntax_library( ":SwiftSyntax", ":SwiftSyntaxBuilder", ":SwiftSyntaxMacroExpansion", + ":_SwiftSyntaxGenericTestSupport", ], ) + +ios_xctestrun_runner( + name = "ios_test_runner", + random = False, + reuse_simulator = True, + visibility = ["//visibility:private"], +) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2474bc12e4e..fd3facb64df 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,23 +42,24 @@ option(SWIFT_SYNTAX_ENABLE_WMO_PRE_3_26 $>,$>,YES,NO>) include(AddSwiftHostLibrary) +include(SwiftCompilerCapability) -# Ensure that we do not link the _StringProcessing module. But we can -# only pass this flag for new-enough compilers that support it. -file(WRITE "${CMAKE_BINARY_DIR}/tmp/empty-check-string-processing.swift" "") -execute_process( - COMMAND - "${CMAKE_Swift_COMPILER}" - -Xfrontend -disable-implicit-string-processing-module-import - -Xfrontend -parse-stdlib - -typecheck "${CMAKE_BINARY_DIR}/tmp/empty-check-string-processing.swift" - OUTPUT_QUIET ERROR_QUIET - RESULT_VARIABLE - SWIFT_SUPPORTS_DISABLE_IMPLICIT_STRING_PROCESSING_MODULE_IMPORT) -if (NOT SWIFT_SUPPORTS_DISABLE_IMPLICIT_STRING_PROCESSING_MODULE_IMPORT) - add_compile_options( - $<$:-Xfrontend> - $<$:-disable-implicit-string-processing-module-import>) +# Don't link with 'string-processing' and 'backtracing'. +swift_supports_implicit_module("string-processing" SWIFT_SUPPORTS_DISABLE_IMPLICIT_STRING_PROCESSING_MODULE_IMPORT) +swift_supports_implicit_module("backtracing" SWIFT_SUPPORTS_DISABLE_IMPLICIT_BACKTRACING_MODULE_IMPORT) +if(SWIFT_SUPPORTS_DISABLE_IMPLICIT_STRING_PROCESSING_MODULE_IMPORT) + add_compile_options("$<$:SHELL:-Xfrontend -disable-implicit-string-processing-module-import>") +endif() +if(SWIFT_SUPPORTS_DISABLE_IMPLICIT_BACKTRACING_MODULE_IMPORT) + add_compile_options("$<$:SHELL:-Xfrontend -disable-implicit-backtracing-module-import>") +endif() + +# SWIFTSYNTAX_EMIT_MODULE is TRUE by default +if(NOT DEFINED SWIFTSYNTAX_EMIT_MODULE) + set(SWIFTSYNTAX_EMIT_MODULE TRUE) +endif() +if(SWIFTSYNTAX_EMIT_MODULE) + swift_get_package_cmo_support(SWIFT_PACKAGE_CMO_SUPPORT) endif() # Determine the module triple. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6468ca3f23c..7df8bbb11c1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ swift-syntax is a SwiftPM package, so you can build and test it using anything t ## Formatting -swift-syntax is formatted using [swift-format](http://github.com/apple/swift-format) to ensure a consistent style. +swift-syntax is formatted using [swift-format](http://github.com/swiftlang/swift-format) to ensure a consistent style. To format your changes run the formatter using the following command ```bash diff --git a/CodeGeneration/Package.swift b/CodeGeneration/Package.swift index 293967ec963..8b2fd91d437 100644 --- a/CodeGeneration/Package.swift +++ b/CodeGeneration/Package.swift @@ -12,7 +12,7 @@ let package = Package( .executable(name: "generate-swift-syntax", targets: ["generate-swift-syntax"]) ], dependencies: [ - .package(url: "https://github.com/apple/swift-syntax", from: "510.0.0"), + .package(url: "https://github.com/swiftlang/swift-syntax", from: "510.0.0"), .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.2"), ], targets: [ diff --git a/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift b/CodeGeneration/Sources/SyntaxSupport/AttributeNodes.swift index 9cdec68b1f3..b7a9dbe5bea 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", @@ -199,7 +203,8 @@ public let ATTRIBUTE_NODES: [Node] = [ Child( name: "platformVersion", deprecatedName: "availabilityVersionRestriction", - kind: .node(kind: .platformVersion) + kind: .node(kind: .platformVersion), + documentation: "The platform/version pair, e.g. `iOS 10.1`" ), Child( name: "trailingComma", @@ -236,7 +241,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." ), ] @@ -284,15 +293,19 @@ public let ATTRIBUTE_NODES: [Node] = [ children: [ Child( name: "witnessMethodLabel", - kind: .token(choices: [.keyword(.witness_method)]) + kind: .token(choices: [.keyword(.witness_method)]), + documentation: #"The `witnessMethod` label."# ), Child( name: "colon", - kind: .token(choices: [.token(.colon)]) + kind: .token(choices: [.token(.colon)]), + documentation: #"The colon separating the `witnessMethod` label and the original protocol name."# + ), Child( name: "protocolName", - kind: .token(choices: [.token(.identifier)]) + kind: .token(choices: [.token(.identifier)]), + documentation: "The original protocol name." ), ] ), @@ -357,7 +370,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" ], @@ -445,6 +459,7 @@ public let ATTRIBUTE_NODES: [Node] = [ name: "kindSpecifier", deprecatedName: "diffKind", kind: .token(choices: [.keyword(._forward), .keyword(.reverse), .keyword(._linear)]), + documentation: "The differentiability kind, if it exists.", isOptional: true ), Child( @@ -458,6 +473,7 @@ public let ATTRIBUTE_NODES: [Node] = [ name: "arguments", deprecatedName: "diffParams", kind: .node(kind: .differentiabilityWithRespectToArgument), + documentation: "The differentiability arguments, if any exists.", isOptional: true ), Child( @@ -471,7 +487,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 +605,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", @@ -664,11 +682,13 @@ public let ATTRIBUTE_NODES: [Node] = [ name: "name", kind: .node(kind: .token), nameForDiagnostics: "name", + documentation: "The identifier name for a nullary selection, if it exists.", isOptional: true ), Child( name: "colon", kind: .token(choices: [.token(.colon)]), + documentation: "The colon separating the label and the value or a colon representing an unlabeled argument", isOptional: true ), ] @@ -738,14 +758,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 be317e400de..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,9 @@ 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( name: "major", @@ -167,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..c5d803f1b21 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. @@ -192,7 +197,7 @@ public class Child { The old string-based implementation returned "Token" to ensure that `tokenKind` is not nil and that `isToken` computed-property will return true, but the value "Token" had never been used in other cases. We should try to remove this computed property altogether in the issue: - https://github.com/apple/swift-syntax/issues/2010 + https://github.com/swiftlang/swift-syntax/issues/2010 */ return .unknown } @@ -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..b397156978d 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( @@ -467,9 +469,9 @@ public let DECL_NODES: [Node] = [ .keyword(._resultDependsOnSelf), .keyword(.required), .keyword(.static), - .keyword(.transferring), .keyword(.unowned), .keyword(.weak), + .keyword(.sending), ]) ), 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/ExperimentalFeatures.swift b/CodeGeneration/Sources/SyntaxSupport/ExperimentalFeatures.swift index c1ad5793fed..e28843cfb68 100644 --- a/CodeGeneration/Sources/SyntaxSupport/ExperimentalFeatures.swift +++ b/CodeGeneration/Sources/SyntaxSupport/ExperimentalFeatures.swift @@ -17,8 +17,8 @@ public enum ExperimentalFeature: String, CaseIterable { case thenStatements case doExpressions case nonescapableTypes - case transferringArgsAndResults case borrowingSwitch + case sendingArgsAndResults /// The name of the feature, which is used in the doc comment. public var featureName: String { @@ -31,10 +31,10 @@ public enum ExperimentalFeature: String, CaseIterable { return "'do' expressions" case .nonescapableTypes: return "NonEscableTypes" - case .transferringArgsAndResults: - return "TransferringArgsAndResults" case .borrowingSwitch: return "borrowing pattern matching" + case .sendingArgsAndResults: + return "SendingArgsAndResults" } } diff --git a/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift b/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift index 525687a2250..1d75123631e 100644 --- a/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/ExprNodes.swift @@ -214,7 +214,7 @@ public let EXPR_NODES: [Node] = [ ), Node( - kind: .canImportExpr, + kind: ._canImportExpr, base: .expr, nameForDiagnostics: "'canImport' expression", children: [ @@ -232,7 +232,7 @@ public let EXPR_NODES: [Node] = [ ), Child( name: "versionInfo", - kind: .node(kind: .canImportVersionInfo), + kind: .node(kind: ._canImportVersionInfo), isOptional: true ), Child( @@ -243,7 +243,7 @@ public let EXPR_NODES: [Node] = [ ), Node( - kind: .canImportVersionInfo, + kind: ._canImportVersionInfo, base: .expr, nameForDiagnostics: nil, children: [ @@ -913,7 +913,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" ), ] @@ -1082,7 +1086,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." ), ] ), @@ -1261,7 +1266,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 + ) ), ] ), @@ -1686,7 +1695,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/KeywordSpec.swift b/CodeGeneration/Sources/SyntaxSupport/KeywordSpec.swift index 895411bace0..b69cdb46d7e 100644 --- a/CodeGeneration/Sources/SyntaxSupport/KeywordSpec.swift +++ b/CodeGeneration/Sources/SyntaxSupport/KeywordSpec.swift @@ -19,7 +19,6 @@ public struct KeywordSpec { /// The experimental feature the keyword is part of, or `nil` if this isn't /// for an experimental feature. public let experimentalFeature: ExperimentalFeature? - public let experimentalFeature2: ExperimentalFeature? /// Indicates if the token kind is switched from being an identifier to a keyword in the lexer. public let isLexerClassified: Bool @@ -43,8 +42,17 @@ public struct KeywordSpec { /// /// This is typically used to mark APIs as SPI when the keyword is part of an experimental language feature. public var apiAttributes: AttributeListSyntax { - guard isExperimental else { return "" } - return AttributeListSyntax("@_spi(ExperimentalLanguageFeatures)").with(\.trailingTrivia, .newline) + let attrList = AttributeListSyntax { + if isExperimental { + let experimentalSPI: AttributeListSyntax = """ + #if compiler(>=5.8) + @_spi(ExperimentalLanguageFeatures) + #endif + """ + experimentalSPI.with(\.trailingTrivia, .newline) + } + } + return attrList.with(\.trailingTrivia, attrList.isEmpty ? [] : .newline) } /// Initializes a new `KeywordSpec` instance. @@ -60,26 +68,6 @@ public struct KeywordSpec { ) { self.name = name self.experimentalFeature = experimentalFeature - self.experimentalFeature2 = nil - self.isLexerClassified = isLexerClassified - } - - /// Initializes a new `KeywordSpec` instance. - /// - /// - Parameters: - /// - name: A name of the keyword. - /// - experimentalFeature: The experimental feature the keyword is part of, or `nil` if this isn't for an experimental feature. - /// - or: A second experimental feature the keyword is also part of, or `nil` if this isn't for an experimental feature. - /// - isLexerClassified: Indicates if the token kind is switched from being an identifier to a keyword in the lexer. - init( - _ name: String, - experimentalFeature: ExperimentalFeature, - or experimentalFeature2: ExperimentalFeature, - isLexerClassified: Bool = false - ) { - self.name = name - self.experimentalFeature = experimentalFeature - self.experimentalFeature2 = experimentalFeature2 self.isLexerClassified = isLexerClassified } } @@ -108,9 +96,7 @@ public enum Keyword: CaseIterable { case _Class case _compilerInitialized case _const - case _consume case _consuming - case _copy case _documentation case _dynamicReplacement case _effects @@ -121,7 +107,6 @@ public enum Keyword: CaseIterable { case _local case _modify case _move - case _mutate case _mutating case _NativeClass case _NativeRefCountedObject @@ -186,6 +171,7 @@ public enum Keyword: CaseIterable { case `default` case `defer` case `deinit` + case dependsOn case deprecated case derivative case didSet @@ -275,7 +261,9 @@ public enum Keyword: CaseIterable { case reverse case right case safe + case scoped case `self` + case sending case `Self` case Sendable case set @@ -293,7 +281,6 @@ public enum Keyword: CaseIterable { case then case `throw` case `throws` - case transferring case transpose case `true` case `try` @@ -332,7 +319,7 @@ public enum Keyword: CaseIterable { case ._borrow: return KeywordSpec("_borrow") case ._borrowing: - return KeywordSpec("_borrowing", experimentalFeature: .referenceBindings, or: .borrowingSwitch) + return KeywordSpec("_borrowing") case ._BridgeObject: return KeywordSpec("_BridgeObject") case ._cdecl: @@ -343,12 +330,8 @@ public enum Keyword: CaseIterable { return KeywordSpec("_compilerInitialized") case ._const: return KeywordSpec("_const") - case ._consume: - return KeywordSpec("_consume", experimentalFeature: .nonescapableTypes) case ._consuming: return KeywordSpec("_consuming", experimentalFeature: .referenceBindings) - case ._copy: - return KeywordSpec("_copy", experimentalFeature: .nonescapableTypes) case ._documentation: return KeywordSpec("_documentation") case ._dynamicReplacement: @@ -369,8 +352,6 @@ public enum Keyword: CaseIterable { return KeywordSpec("_modify") case ._move: return KeywordSpec("_move") - case ._mutate: - return KeywordSpec("_mutate", experimentalFeature: .nonescapableTypes) case ._mutating: return KeywordSpec("_mutating", experimentalFeature: .referenceBindings) case ._NativeClass: @@ -499,6 +480,8 @@ public enum Keyword: CaseIterable { return KeywordSpec("defer", isLexerClassified: true) case .deinit: return KeywordSpec("deinit", isLexerClassified: true) + case .dependsOn: + return KeywordSpec("dependsOn", experimentalFeature: .nonescapableTypes) case .deprecated: return KeywordSpec("deprecated") case .derivative: @@ -675,6 +658,8 @@ public enum Keyword: CaseIterable { return KeywordSpec("right") case .safe: return KeywordSpec("safe") + case .scoped: + return KeywordSpec("scoped", experimentalFeature: .nonescapableTypes) case .self: return KeywordSpec("self", isLexerClassified: true) case .Self: @@ -711,11 +696,8 @@ public enum Keyword: CaseIterable { return KeywordSpec("throw", isLexerClassified: true) case .throws: return KeywordSpec("throws", isLexerClassified: true) - case .transferring: - return KeywordSpec( - "transferring", - experimentalFeature: .transferringArgsAndResults - ) + case .sending: + return KeywordSpec("sending") case .transpose: return KeywordSpec("transpose") case .true: diff --git a/CodeGeneration/Sources/SyntaxSupport/Node.swift b/CodeGeneration/Sources/SyntaxSupport/Node.swift index 5fec1d979a0..9c6dd5aa47d 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Node.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Node.swift @@ -147,7 +147,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 @@ -165,9 +169,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 } @@ -183,7 +189,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 ) ] @@ -224,7 +233,11 @@ public class Node { // This will repeat the syntax type before and after the dot, which is // a little unfortunate, but it's the only way I found to get docc to // generate a fully-qualified type + member. - return " - \($0.node.doccLink).``\($0.node.syntaxType)/\(childName)``" + if $0.node.isAvailableInDocc { + return " - \($0.node.doccLink).``\($0.node.syntaxType)/\(childName)``" + } else { + return " - \($0.node.doccLink).`\($0.node.syntaxType)/\(childName)`" + } } else { return " - \($0.node.doccLink)" } @@ -248,7 +261,7 @@ public class Node { let list = SYNTAX_NODES - .filter { $0.base == self.kind && !$0.isExperimental } + .filter { $0.base == self.kind && !$0.isExperimental && !$0.kind.isDeprecated } .map { "- \($0.kind.doccLink)" } .joined(separator: "\n") diff --git a/CodeGeneration/Sources/SyntaxSupport/PatternNodes.swift b/CodeGeneration/Sources/SyntaxSupport/PatternNodes.swift index 9113acef734..83d45dd71ec 100644 --- a/CodeGeneration/Sources/SyntaxSupport/PatternNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/PatternNodes.swift @@ -201,6 +201,7 @@ public let PATTERN_NODES: [Node] = [ kind: .token(choices: [ .keyword(.let), .keyword(.var), .keyword(.inout), .keyword(._mutating), .keyword(._borrowing), .keyword(._consuming), + .keyword(.borrowing), ]) ), Child( diff --git a/CodeGeneration/Sources/SyntaxSupport/String+Extensions.swift b/CodeGeneration/Sources/SyntaxSupport/String+Extensions.swift index 93884aa0e35..3945a35ceb3 100644 --- a/CodeGeneration/Sources/SyntaxSupport/String+Extensions.swift +++ b/CodeGeneration/Sources/SyntaxSupport/String+Extensions.swift @@ -10,10 +10,20 @@ // //===----------------------------------------------------------------------===// -public extension StringProtocol { - var withFirstCharacterLowercased: String { prefix(1).lowercased() + dropFirst() } - var withFirstCharacterUppercased: String { prefix(1).uppercased() + dropFirst() } - var backtickedIfNeeded: String { +extension StringProtocol { + public var withFirstCharacterLowercased: String { + guard first?.isLetter ?? false else { + return String(first!) + dropFirst().withFirstCharacterLowercased + } + return prefix(1).lowercased() + dropFirst() + } + public var withFirstCharacterUppercased: String { + guard first?.isLetter ?? false else { + return String(first!) + dropFirst().withFirstCharacterUppercased + } + return prefix(1).uppercased() + dropFirst() + } + public var backtickedIfNeeded: String { if Keyword.allCases.map(\.spec).contains(where: { $0.name == self && ($0.isLexerClassified || $0.name == "Type" || $0.name == "Protocol") }) { @@ -23,3 +33,12 @@ public extension StringProtocol { } } } + +extension String { + public var droppingLeadingUnderscores: String { + if first == "_" { + return String(self.dropFirst()) + } + return self + } +} diff --git a/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift b/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift index 5ea26147675..3c460095a91 100644 --- a/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift +++ b/CodeGeneration/Sources/SyntaxSupport/SyntaxNodeKind.swift @@ -20,6 +20,8 @@ import SwiftSyntaxBuilder public enum SyntaxNodeKind: String, CaseIterable { // Please keep this list sorted alphabetically + case _canImportExpr + case _canImportVersionInfo case accessorBlock case accessorDecl case accessorDeclList @@ -47,8 +49,6 @@ public enum SyntaxNodeKind: String, CaseIterable { case booleanLiteralExpr case borrowExpr case breakStmt - case canImportExpr - case canImportVersionInfo case catchClause case catchClauseList case catchItem @@ -355,14 +355,25 @@ public enum SyntaxNodeKind: String, CaseIterable { } } + /// Whether the node is public API and not underscored/deprecated and can thus be referenced in docc links. + public var isAvailableInDocc: Bool { + if let node = SYNTAX_NODE_MAP[self], node.isExperimental { + return false + } else if isDeprecated { + return false + } else { + return true + } + } + /// If this node is non-experimental a docc link wrapped in two backticks. /// /// For experimental nodes, the node's type name in code font. public var doccLink: String { - if let node = SYNTAX_NODE_MAP[self], node.isExperimental { - return "`\(syntaxType)`" - } else { + if isAvailableInDocc { return "``\(syntaxType)``" + } else { + return "`\(syntaxType)`" } } @@ -405,6 +416,8 @@ public enum SyntaxNodeKind: String, CaseIterable { /// deprecated. public var deprecatedRawValue: String? { switch self { + case ._canImportExpr: return "canImportExpr" + case ._canImportVersionInfo: return "canImportVersionInfo" case .accessorDeclList: return "accessorList" case .accessorParameters: return "accessorParameter" case .associatedTypeDecl: return "associatedtypeDecl" @@ -475,4 +488,24 @@ public enum SyntaxNodeKind: String, CaseIterable { default: return nil } } + + public var deprecationMessage: String? { + switch self { + case ._canImportExpr: return "'canImport' directives are now represented as a `FunctionCallExpr`" + case ._canImportVersionInfo: return "'canImport' directives are now represented as a `FunctionCallExpr`" + default: return nil + } + } + + public var isDeprecated: Bool { + return rawValue.first == "_" + } + + var deprecationAttribute: AttributeSyntax? { + if let deprecationMessage = deprecationMessage { + AttributeSyntax("@available(*, deprecated, message: \(literal: deprecationMessage)") + } else { + AttributeSyntax(#"@available(*, deprecated, renamed: "\#(syntaxType)")"#) + } + } } diff --git a/CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift b/CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift index f06a97fa329..3987c07cbfc 100644 --- a/CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift +++ b/CodeGeneration/Sources/SyntaxSupport/SyntaxNodes.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -public let SYNTAX_NODES: [Node] = - (COMMON_NODES +private let unsortedSyntaxNodes: [Node] = + COMMON_NODES + EXPR_NODES + DECL_NODES + ATTRIBUTE_NODES @@ -19,7 +19,15 @@ public let SYNTAX_NODES: [Node] = + GENERIC_NODES + TYPE_NODES + PATTERN_NODES - + AVAILABILITY_NODES).sorted { $0.kind.syntaxType.description < $1.kind.syntaxType.description } + + AVAILABILITY_NODES + +public let SYNTAX_NODES: [Node] = + unsortedSyntaxNodes + .sorted { (lhs: Node, rhs: Node) -> Bool in + let lhsSortKey = lhs.kind.syntaxType.description.droppingLeadingUnderscores + let rhsSortKey = rhs.kind.syntaxType.description.droppingLeadingUnderscores + return lhsSortKey < rhsSortKey + } /// A lookup table of nodes indexed by their kind. public let SYNTAX_NODE_MAP: [SyntaxNodeKind: Node] = Dictionary( 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..1f729195d75 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", @@ -538,30 +543,30 @@ public let TYPE_NODES: [Node] = [ ), Node( - kind: .lifetimeSpecifierArguments, + kind: .lifetimeTypeSpecifier, base: .syntax, experimentalFeature: .nonescapableTypes, - nameForDiagnostics: nil, - documentation: """ - An optional argument passed to a type parameter. - - ### Example - `borrow(data)` in `func foo(data: Array) -> borrow(data) ComplexReferenceType` - """, - traits: [ - "Parenthesized" - ], + nameForDiagnostics: "lifetime specifier", + documentation: "A specifier that specifies function parameter on whose lifetime a type depends", children: [ + Child( + name: "dependsOnKeyword", + kind: .token(choices: [.keyword(.dependsOn)]), + documentation: "lifetime dependence specifier on the return type" + ), Child( name: "leftParen", kind: .token(choices: [.token(.leftParen)]) ), + Child( + name: "scopedKeyword", + kind: .token(choices: [.keyword(.scoped)]), + documentation: "lifetime of return value is scoped to the lifetime of the original value", + isOptional: true + ), Child( name: "arguments", - kind: .collection(kind: .lifetimeSpecifierArgumentList, collectionElementName: "Arguments"), - documentation: """ - The function parameters that the lifetime of the annotated type depends on. - """ + kind: .collection(kind: .lifetimeSpecifierArgumentList, collectionElementName: "Arguments") ), Child( name: "rightParen", @@ -570,30 +575,6 @@ public let TYPE_NODES: [Node] = [ ] ), - Node( - kind: .lifetimeTypeSpecifier, - base: .syntax, - experimentalFeature: .nonescapableTypes, - nameForDiagnostics: "lifetime specifier", - documentation: "A specifier that specifies function parameter on whose lifetime a type depends", - children: [ - Child( - name: "specifier", - kind: .token(choices: [ - .keyword(._copy), - .keyword(._consume), - .keyword(._borrow), - .keyword(._mutate), - ]), - documentation: "The specifier token that's attached to the type." - ), - Child( - name: "arguments", - kind: .node(kind: .lifetimeSpecifierArguments) - ), - ] - ), - Node( kind: .simpleTypeSpecifier, base: .syntax, @@ -610,8 +591,8 @@ public let TYPE_NODES: [Node] = [ .keyword(._const), .keyword(.borrowing), .keyword(.consuming), - .keyword(.transferring), .keyword(._resultDependsOn), + .keyword(.sending), ]), documentation: "The specifier token that's attached to the type." ) diff --git a/CodeGeneration/Sources/SyntaxSupport/Utils.swift b/CodeGeneration/Sources/SyntaxSupport/Utils.swift index ed2091ff7e3..009d0b6ca91 100644 --- a/CodeGeneration/Sources/SyntaxSupport/Utils.swift +++ b/CodeGeneration/Sources/SyntaxSupport/Utils.swift @@ -58,9 +58,9 @@ extension SwiftSyntax.Trivia { } } -public extension Collection { +extension Collection { /// If the collection contains a single element, return it, otherwise `nil`. - var only: Element? { + public var only: Element? { if !isEmpty && index(after: startIndex) == endIndex { return self.first! } else { @@ -69,8 +69,8 @@ public extension Collection { } } -public extension TokenSyntax { - var backtickedIfNeeded: TokenSyntax { +extension TokenSyntax { + public var backtickedIfNeeded: TokenSyntax { if Keyword.allCases.map(\.spec).contains(where: { $0.name == self.description && ($0.isLexerClassified || $0.name == "Type" || $0.name == "Protocol") }) { 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..fc6980c5cb2 100644 --- a/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift +++ b/CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift @@ -23,10 +23,10 @@ public enum SyntaxOrTokenNodeKind: Hashable { /// Extension to the ``Child`` type to provide functionality specific to /// SwiftSyntaxBuilder. -public extension Child { +extension Child { /// The type of this child, represented by a ``SyntaxBuildableType``, which can /// be used to create the corresponding `Buildable` and `ExpressibleAs` types. - var buildableType: SyntaxBuildableType { + public var buildableType: SyntaxBuildableType { let buildableKind: SyntaxOrTokenNodeKind switch kind { case .node(kind: let kind): @@ -44,7 +44,7 @@ public extension Child { ) } - var parameterBaseType: TypeSyntax { + public var parameterBaseType: TypeSyntax { switch kind { case .nodeChoices: return self.syntaxChoicesType @@ -53,11 +53,11 @@ public extension Child { } } - var parameterType: TypeSyntax { + public var parameterType: TypeSyntax { return self.buildableType.optionalWrapped(type: parameterBaseType) } - var defaultValue: ExprSyntax? { + public var defaultValue: ExprSyntax? { if isOptional || isUnexpectedNodes { if buildableType.isBaseType && kind.isNodeChoicesEmpty { return ExprSyntax("\(buildableType.buildable).none") @@ -85,9 +85,12 @@ public extension Child { /// If the child node has a default value, return an expression of the form /// ` = default_value` that can be used as the default value to for a /// function parameter. Otherwise, return `nil`. - var defaultInitialization: InitializerClauseSyntax? { + public 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 } @@ -96,7 +99,7 @@ public extension Child { /// If this node is a token that can't contain arbitrary text, generate a Swift /// `precondition` statement that verifies the variable with name var_name and of type /// ``TokenSyntax`` contains one of the supported text options. Otherwise return `nil`. - func generateAssertStmtTextChoices(varName: String) -> FunctionCallExprSyntax? { + public func generateAssertStmtTextChoices(varName: String) -> FunctionCallExprSyntax? { guard case .token(choices: let choices, requiresLeadingSpace: _, requiresTrailingSpace: _) = kind 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/Utils/SyntaxBuildableNode.swift b/CodeGeneration/Sources/Utils/SyntaxBuildableNode.swift index fdad0ae7bf1..e7467150baa 100644 --- a/CodeGeneration/Sources/Utils/SyntaxBuildableNode.swift +++ b/CodeGeneration/Sources/Utils/SyntaxBuildableNode.swift @@ -14,14 +14,14 @@ import SyntaxSupport /// Extension to the ``Node`` type to provide functionality specific to /// SwiftSyntaxBuilder. -public extension Node { +extension Node { /// The node's syntax kind as ``SyntaxBuildableType``. - var type: SyntaxBuildableType { + public var type: SyntaxBuildableType { SyntaxBuildableType(kind: .node(kind: kind)) } /// The node's syntax kind as ``SyntaxBuildableType``. - var baseType: SyntaxBuildableType { + public var baseType: SyntaxBuildableType { if base == .syntaxCollection { return SyntaxBuildableType(kind: .node(kind: .syntax)) } else { @@ -29,7 +29,7 @@ public extension Node { } } - static func from(type: SyntaxBuildableType) -> Node { + public static func from(type: SyntaxBuildableType) -> Node { guard case .node(kind: let kind) = type.kind, let node = SYNTAX_NODE_MAP[kind] else { fatalError("Base name \(type) does not have a syntax node") } @@ -37,18 +37,18 @@ public extension Node { } } -public extension LayoutNode { +extension LayoutNode { /// Assuming this node has a single child without a default value, that child. - var singleNonDefaultedChild: Child { + public var singleNonDefaultedChild: Child { let nonDefaultedParams = children.filter { $0.defaultInitialization == nil } precondition(nonDefaultedParams.count == 1) return nonDefaultedParams[0] } } -public extension CollectionNode { +extension CollectionNode { /// Assuming this node is a syntax collection, the type of its elements. - var collectionElementType: SyntaxBuildableType { + public var collectionElementType: SyntaxBuildableType { if elementChoices.count > 1 { return SyntaxBuildableType(kind: .node(kind: .syntax)) } else { 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..b73d7d7ddb6 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/ParserTokenSpecSetFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/ParserTokenSpecSetFile.swift @@ -15,13 +15,13 @@ import SwiftSyntaxBuilder import SyntaxSupport import Utils -func tokenCaseMatch(_ caseName: TokenSyntax, experimentalFeature: ExperimentalFeature?, experimentalFeature2: ExperimentalFeature?) -> SwitchCaseSyntax { +func tokenCaseMatch( + _ caseName: TokenSyntax, + experimentalFeature: ExperimentalFeature? +) -> SwitchCaseSyntax { var whereClause = "" if let feature = experimentalFeature { whereClause += "where experimentalFeatures.contains(.\(feature.token))" - if let feature2 = experimentalFeature2 { - whereClause += " || experimentalFeatures.contains(.\(feature2.token))" - } } return "case TokenSpec(.\(caseName))\(raw: whereClause): self = .\(caseName)" } @@ -61,21 +61,21 @@ 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 { case .keyword(let keyword): tokenCaseMatch( keyword.spec.varOrCaseName, - experimentalFeature: keyword.spec.experimentalFeature, - experimentalFeature2: keyword.spec.experimentalFeature2 + experimentalFeature: keyword.spec.experimentalFeature ) case .token(let token): tokenCaseMatch( token.spec.varOrCaseName, - experimentalFeature: token.spec.experimentalFeature, - experimentalFeature2: nil + experimentalFeature: token.spec.experimentalFeature ) } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/TokenSpecStaticMembersFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/TokenSpecStaticMembersFile.swift index 9d3272d4ee8..7f763e38ade 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/TokenSpecStaticMembersFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/TokenSpecStaticMembersFile.swift @@ -16,7 +16,15 @@ import SyntaxSupport import Utils let tokenSpecStaticMembersFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { - DeclSyntax("@_spi(RawSyntax) import SwiftSyntax") + DeclSyntax( + """ + #if swift(>=6) + @_spi(RawSyntax) internal import SwiftSyntax + #else + @_spi(RawSyntax) import SwiftSyntax + #endif + """ + ) try! ExtensionDeclSyntax("extension TokenSpec") { for tokenSpec in Token.allCases.map(\.spec) where tokenSpec.kind != .keyword { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/ChildNameForDiagnosticsFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/ChildNameForDiagnosticsFile.swift index a3732d1d3c9..2f51321e589 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/ChildNameForDiagnosticsFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/ChildNameForDiagnosticsFile.swift @@ -16,7 +16,15 @@ import SyntaxSupport import Utils let childNameForDiagnosticFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { - DeclSyntax("@_spi(ExperimentalLanguageFeatures) import SwiftSyntax") + DeclSyntax( + """ + #if swift(>=6) + @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax + #else + @_spi(ExperimentalLanguageFeatures) import SwiftSyntax + #endif + """ + ) try! FunctionDeclSyntax( "private func childNameForDiagnostics(_ keyPath: AnyKeyPath) -> String?" diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/SyntaxKindNameForDiagnosticsFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/SyntaxKindNameForDiagnosticsFile.swift index 53a6b67bdf1..34957cf11ab 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/SyntaxKindNameForDiagnosticsFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/SyntaxKindNameForDiagnosticsFile.swift @@ -16,7 +16,15 @@ import SyntaxSupport import Utils let syntaxKindNameForDiagnosticFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { - DeclSyntax("@_spi(ExperimentalLanguageFeatures) import SwiftSyntax") + DeclSyntax( + """ + #if swift(>=6) + @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax + #else + @_spi(ExperimentalLanguageFeatures) import SwiftSyntax + #endif + """ + ) try! ExtensionDeclSyntax("extension SyntaxKind") { try VariableDeclSyntax("var nameForDiagnostics: String?") { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/TokenNameForDiagnosticsFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/TokenNameForDiagnosticsFile.swift index 37ac41b8422..62c1c9e3973 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/TokenNameForDiagnosticsFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftparserdiagnostics/TokenNameForDiagnosticsFile.swift @@ -16,7 +16,15 @@ import SyntaxSupport import Utils let tokenNameForDiagnosticFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { - DeclSyntax("@_spi(RawSyntax) import SwiftSyntax") + DeclSyntax( + """ + #if swift(>=6) + @_spi(RawSyntax) internal import SwiftSyntax + #else + @_spi(RawSyntax) import SwiftSyntax + #endif + """ + ) try! ExtensionDeclSyntax("extension TokenKind") { try! VariableDeclSyntax("var nameForDiagnostics: String") { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RawSyntaxNodesFile.swift index c9dda02030f..60d9aeb0c52 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,11 @@ 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.droppingLeadingUnderscores.first!) + && !node.kind.isDeprecated + { DeclSyntax( """ \(node.apiAttributes(forRaw: true))\ @@ -49,7 +54,8 @@ func rawSyntaxNodesFile(nodesStartingWith: [Character]) -> SourceFileSyntax { ) } - for node in SYNTAX_NODES where nodesStartingWith.contains(node.kind.syntaxType.description.first!) { + for node in SYNTAX_NODES + where nodesStartingWith.contains(node.kind.syntaxType.description.droppingLeadingUnderscores.first!) { try! StructDeclSyntax( """ \(node.apiAttributes(forRaw: true))\ @@ -220,8 +226,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 +248,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..bc9babfedc4 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedSyntaxNodesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/RenamedSyntaxNodesFile.swift @@ -15,24 +15,33 @@ import SwiftSyntaxBuilder import SyntaxSupport import Utils +func deprecationAttribute(for syntaxKind: SyntaxNodeKind) -> AttributeSyntax { + if let deprecationMessage = syntaxKind.deprecationMessage { + return AttributeSyntax("@available(*, deprecated, message: \(literal: deprecationMessage))") + } + return AttributeSyntax(#"@available(*, deprecated, renamed: "\#(syntaxKind.syntaxType)")"#) +} + let renamedSyntaxNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { for syntaxKind in SyntaxNodeKind.allCases.sorted(by: { $0.deprecatedRawValue ?? "" < $1.deprecatedRawValue ?? "" }) { if let deprecatedName = syntaxKind.deprecatedRawValue { DeclSyntax( """ - @available(*, deprecated, renamed: "\(syntaxKind.syntaxType)") + \(deprecationAttribute(for: syntaxKind)) public typealias \(raw: deprecatedName.withFirstCharacterUppercased)Syntax = \(syntaxKind.syntaxType) """ ) } } - try! ExtensionDeclSyntax("public extension SyntaxKind") { - for syntaxKind in SyntaxNodeKind.allCases.sorted(by: { $0.deprecatedRawValue ?? "" < $1.deprecatedRawValue ?? "" }) { + try! ExtensionDeclSyntax("extension SyntaxKind") { + let syntaxKinds = SyntaxNodeKind.allCases.sorted(by: { $0.deprecatedRawValue ?? "" < $1.deprecatedRawValue ?? "" }) + for syntaxKind in syntaxKinds { if let deprecatedName = syntaxKind.deprecatedRawValue { DeclSyntax( """ - static var \(raw: deprecatedName): Self { + \(deprecationAttribute(for: syntaxKind)) + public static var \(raw: deprecatedName): Self { return .\(syntaxKind.varOrCaseName) } """ diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SwiftSyntaxDoccIndex.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SwiftSyntaxDoccIndex.swift index 65699262d7e..d81e1b11ca3 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 && !$0.kind.isDeprecated }) + .map(\.kind.syntaxType.description) addSection(heading: heading, types: baseTypes + leafTypes) } @@ -53,17 +56,24 @@ let nodesSections: String = { } return [node.kind.syntaxType.description] + node.elementChoices - .filter { SYNTAX_NODE_MAP[$0] != nil && !SYNTAX_NODE_MAP[$0]!.isExperimental } + .filter { SYNTAX_NODE_MAP[$0] != nil && !SYNTAX_NODE_MAP[$0]!.isExperimental && !$0.isDeprecated } .map(\.syntaxType.description) .filter { !handledSyntaxTypes.contains($0) } }) ) - addSection(heading: "Attributes", types: ATTRIBUTE_NODES.filter({ !$0.isExperimental }).map(\.kind.syntaxType.description).sorted()) + addSection( + heading: "Attributes", + types: ATTRIBUTE_NODES.filter({ !$0.isExperimental && !$0.kind.isDeprecated }).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 && !$0.kind.isDeprecated }).map(\.kind.syntaxType.description) + .filter({ + !handledSyntaxTypes.contains($0) + }) ) addSection(heading: "Traits", types: TRAITS.map { "\($0.protocolName)" }) @@ -84,7 +94,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/SyntaxBaseNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxBaseNodesFile.swift index 37a7f3f8beb..6125a3a9224 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxBaseNodesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxBaseNodesFile.swift @@ -145,14 +145,14 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { """# ) - try! ExtensionDeclSyntax("public extension Syntax") { + try! ExtensionDeclSyntax("extension Syntax") { DeclSyntax( """ /// Check whether the non-type erased version of this syntax node conforms to /// \(node.kind.protocolType). /// /// - Note: This will incur an existential conversion. - func isProtocol(_: \(node.kind.protocolType).Protocol) -> Bool { + public func isProtocol(_: \(node.kind.protocolType).Protocol) -> Bool { return self.asProtocol(\(node.kind.protocolType).self) != nil } """ @@ -164,7 +164,7 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// \(node.kind.protocolType). Otherwise return nil. /// /// - Note: This will incur an existential conversion. - func asProtocol(_: \(node.kind.protocolType).Protocol) -> \(node.kind.protocolType)? { + public func asProtocol(_: \(node.kind.protocolType).Protocol) -> \(node.kind.protocolType)? { return self.asProtocol(SyntaxProtocol.self) as? \(node.kind.protocolType) } """ @@ -183,7 +183,7 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ /// Create a \(raw: node.kind.doccLink) node from a specialized syntax node. - public init(_ syntax: some \(node.kind.protocolType)) { + public init(_ syntax: __shared some \(node.kind.protocolType)) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -195,7 +195,7 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ /// Create a \(raw: node.kind.doccLink) node from a specialized optional syntax node. - public init?(_ syntax: (some \(node.kind.protocolType))?) { + public init?(_ syntax: __shared (some \(node.kind.protocolType))?) { guard let syntax = syntax else { return nil } self.init(syntax) } @@ -204,7 +204,7 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - public init(fromProtocol syntax: \(node.kind.protocolType)) { + public init(fromProtocol syntax: __shared \(node.kind.protocolType)) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -216,14 +216,14 @@ let syntaxBaseNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ /// Create a \(raw: node.kind.doccLink) node from a specialized optional syntax node. - public init?(fromProtocol syntax: \(node.kind.protocolType)?) { + public init?(fromProtocol syntax: __shared \(node.kind.protocolType)?) { guard let syntax = syntax else { return nil } self.init(fromProtocol: syntax) } """ ) - try InitializerDeclSyntax("public init?(_ node: some SyntaxProtocol)") { + try InitializerDeclSyntax("public init?(_ node: __shared some SyntaxProtocol)") { try SwitchExprSyntax("switch node.raw.kind") { SwitchCaseListSyntax { SwitchCaseSyntax( @@ -337,7 +337,7 @@ private func leafProtocolDecl(type: TypeSyntax, inheritedType: TypeSyntax) -> De private func leafProtocolExtension(type: TypeSyntax, inheritedType: TypeSyntax) -> DeclSyntax { DeclSyntax( #""" - public extension \#(type) { + extension \#(type) { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -345,7 +345,7 @@ private func leafProtocolExtension(type: TypeSyntax, inheritedType: TypeSyntax) /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -356,7 +356,7 @@ private func leafProtocolExtension(type: TypeSyntax, inheritedType: TypeSyntax) /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -368,7 +368,7 @@ private func leafProtocolExtension(type: TypeSyntax, inheritedType: TypeSyntax) /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxEnumFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxEnumFile.swift index c97d1dd6519..fb212939b3c 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxEnumFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxEnumFile.swift @@ -35,13 +35,13 @@ let syntaxEnumFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { try! ExtensionDeclSyntax( """ - public extension Syntax + extension Syntax """ ) { try FunctionDeclSyntax( """ /// Get an enum that can be used to exhaustively switch over all syntax nodes. - func `as`(_: SyntaxEnum.Type) -> SyntaxEnum + public func `as`(_: SyntaxEnum.Type) -> SyntaxEnum """ ) { try SwitchExprSyntax("switch raw.kind") { @@ -81,13 +81,13 @@ let syntaxEnumFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { try! ExtensionDeclSyntax( """ - public extension \(baseKind.syntaxType) + extension \(baseKind.syntaxType) """ ) { try FunctionDeclSyntax( """ /// Get an enum that can be used to exhaustively switch over all \(raw: baseName) syntax nodes. - func `as`(_: \(enumType).Type) -> \(enumType) + public func `as`(_: \(enumType).Type) -> \(enumType) """ ) { try SwitchExprSyntax("switch raw.kind") { diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxNodesFile.swift index b9cb1c69a59..3753ae54a6e 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.droppingLeadingUnderscores.first!) { // We are actually handling this node now try! StructDeclSyntax( """ @@ -46,7 +47,7 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax { DeclSyntax( """ - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .\(node.varOrCaseName) else { return nil } self._syntaxNode = node._syntaxNode } @@ -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)") } @@ -194,17 +199,14 @@ func syntaxNode(nodesStartingWith: [Character]) -> SourceFileSyntax { } } - try! VariableDeclSyntax("public static var structure: SyntaxNodeStructure") { - let layout = ArrayExprSyntax { - for child in node.children { - ArrayElementSyntax( - expression: ExprSyntax(#"\Self.\#(child.varOrCaseName)"#) - ) - } + let layout = ArrayExprSyntax { + for child in node.children { + ArrayElementSyntax( + expression: ExprSyntax(#"\Self.\#(child.varOrCaseName)"#) + ) } - - StmtSyntax("return .layout(\(layout))") } + "public static let structure: SyntaxNodeStructure = .layout(\(layout))" } } } @@ -251,7 +253,7 @@ private func generateSyntaxChildChoices(for child: Child) throws -> EnumDeclSynt } } - try! InitializerDeclSyntax("public init?(_ node: some SyntaxProtocol)") { + try! InitializerDeclSyntax("public init?(_ node: __shared some SyntaxProtocol)") { for choice in choices { StmtSyntax( """ diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift index 3b6cada55c6..805b0b3efb1 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxRewriterFile.swift @@ -32,6 +32,13 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { ) { DeclSyntax("public let viewMode: SyntaxTreeViewMode") + DeclSyntax( + """ + /// 'Syntax' object factory recycling 'Syntax.Info' instances. + private let nodeFactory: SyntaxNodeFactory = SyntaxNodeFactory() + """ + ) + DeclSyntax( """ public init(viewMode: SyntaxTreeViewMode = .sourceAccurate) { @@ -44,7 +51,8 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { """ /// Rewrite `node`, keeping its parent unless `detach` is `true`. public func rewrite(_ node: some SyntaxProtocol, detach: Bool = false) -> Syntax { - let rewritten = self.dispatchVisit(Syntax(node)) + var rewritten = Syntax(node) + self.dispatchVisit(&rewritten) if detach { return rewritten } @@ -105,7 +113,9 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// - Returns: the rewritten node @available(*, deprecated, renamed: "rewrite(_:detach:)") public func visit(_ node: Syntax) -> Syntax { - return dispatchVisit(node) + var rewritten = node + dispatchVisit(&rewritten) + return rewritten } """ ) @@ -113,7 +123,9 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ public func visit(_ node: T) -> T { - return dispatchVisit(Syntax(node)).cast(T.self) + var rewritten = Syntax(node) + dispatchVisit(&rewritten) + return rewritten.cast(T.self) } """ ) @@ -127,7 +139,7 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// - Returns: the rewritten node \(node.apiAttributes())\ open func visit(_ node: \(node.kind.syntaxType)) -> \(node.kind.syntaxType) { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(\(node.kind.syntaxType).self) } """ ) @@ -139,14 +151,15 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// - Returns: the rewritten node \(node.apiAttributes())\ open func visit(_ node: \(node.kind.syntaxType)) -> \(node.baseType.syntaxBaseName) { - return \(node.baseType.syntaxBaseName)(visitChildren(node)) + return \(node.baseType.syntaxBaseName)(visitChildren(node._syntaxNode).cast(\(node.kind.syntaxType).self)) } """ ) } } - 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( """ @@ -155,7 +168,9 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// - Returns: the rewritten node \(baseNode.apiAttributes())\ public func visit(_ node: \(baseKind.syntaxType)) -> \(baseKind.syntaxType) { - return dispatchVisit(Syntax(node)).cast(\(baseKind.syntaxType).self) + var node: Syntax = Syntax(node) + dispatchVisit(&node) + return node.cast(\(baseKind.syntaxType).self) } """ ) @@ -165,21 +180,16 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { """ /// Interpret `node` as a node of type `nodeType`, visit it, calling /// the `visit` to transform the node. + @inline(__always) private func visitImpl( - _ node: Syntax, + _ node: inout Syntax, _ nodeType: NodeType.Type, _ visit: (NodeType) -> some SyntaxProtocol - ) -> Syntax { - let castedNode = node.cast(NodeType.self) - // Accessing _syntaxNode directly is faster than calling Syntax(node) - visitPre(node) - defer { - visitPost(node) - } - if let newNode = visitAny(node) { - return newNode - } - return Syntax(visit(castedNode)) + ) { + let origNode = node + visitPre(origNode) + node = visitAny(origNode) ?? Syntax(visit(origNode.cast(NodeType.self))) + visitPost(origNode) } """ ) @@ -220,17 +230,17 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// that determines the correct visitation function will be popped of the /// stack before the function is being called, making the switch's stack /// space transient instead of having it linger in the call stack. - private func visitationFunc(for node: Syntax) -> ((Syntax) -> Syntax) + private func visitationFunc(for node: Syntax) -> ((inout Syntax) -> Void) """ ) { try SwitchExprSyntax("switch node.raw.kind") { SwitchCaseSyntax("case .token:") { - StmtSyntax("return { self.visitImpl($0, TokenSyntax.self, self.visit) }") + StmtSyntax("return { self.visitImpl(&$0, TokenSyntax.self, self.visit) }") } for node in NON_BASE_SYNTAX_NODES { SwitchCaseSyntax("case .\(node.varOrCaseName):") { - StmtSyntax("return { self.visitImpl($0, \(node.kind.syntaxType).self, self.visit) }") + StmtSyntax("return { self.visitImpl(&$0, \(node.kind.syntaxType).self, self.visit) }") } } } @@ -238,8 +248,8 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - private func dispatchVisit(_ node: Syntax) -> Syntax { - return visitationFunc(for: node)(node) + private func dispatchVisit(_ node: inout Syntax) { + visitationFunc(for: node)(&node) } """ ) @@ -250,15 +260,15 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { poundKeyword: .poundElseToken(), elements: .statements( CodeBlockItemListSyntax { - try! FunctionDeclSyntax("private func dispatchVisit(_ node: Syntax) -> Syntax") { + try! FunctionDeclSyntax("private func dispatchVisit(_ node: inout Syntax)") { try SwitchExprSyntax("switch node.raw.kind") { SwitchCaseSyntax("case .token:") { - StmtSyntax("return visitImpl(node, TokenSyntax.self, visit)") + StmtSyntax("return visitImpl(&node, TokenSyntax.self, visit)") } for node in NON_BASE_SYNTAX_NODES { SwitchCaseSyntax("case .\(node.varOrCaseName):") { - StmtSyntax("return visitImpl(node, \(node.kind.syntaxType).self, visit)") + StmtSyntax("return visitImpl(&node, \(node.kind.syntaxType).self, visit)") } } } @@ -271,9 +281,7 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - private func visitChildren( - _ node: SyntaxType - ) -> SyntaxType { + private func visitChildren(_ node: Syntax) -> Syntax { // Walk over all children of this node and rewrite them. Don't store any // rewritten nodes until the first non-`nil` value is encountered. When this // happens, retrieve all previous syntax nodes from the parent node to @@ -283,73 +291,48 @@ let syntaxRewriterFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { // newLayout is nil until the first child node is rewritten and rewritten // nodes are being collected. - var newLayout: ContiguousArray? - - // Rewritten children just to keep their 'SyntaxArena' alive until they are - // wrapped with 'Syntax' - var rewrittens: ContiguousArray = [] + var newLayout: UnsafeMutableBufferPointer = .init(start: nil, count: 0) - let syntaxNode = node._syntaxNode + // Keep 'SyntaxArena' of rewritten nodes alive until they are wrapped + // with 'Syntax' + var rewrittens: ContiguousArray = [] - // Incrementing i manually is faster than using .enumerated() - var childIndex = 0 - for (raw, info) in RawSyntaxChildren(syntaxNode) { - defer { childIndex += 1 } - - guard let child = raw, viewMode.shouldTraverse(node: child) else { - // Node does not exist or should not be visited. If we are collecting - // rewritten nodes, we need to collect this one as well, otherwise we - // can ignore it. - if newLayout != nil { - newLayout!.append(raw) - } - continue - } + for case let (child?, info) in RawSyntaxChildren(node) where viewMode.shouldTraverse(node: child) { // Build the Syntax node to rewrite - let absoluteRaw = AbsoluteRawSyntax(raw: child, info: info) + var childNode = nodeFactory.create(parent: node, raw: child, absoluteInfo: info) - let rewritten = dispatchVisit(Syntax(absoluteRaw, parent: syntaxNode)) - if rewritten.id != info.nodeId { + dispatchVisit(&childNode) + if childNode.raw.id != child.id { // The node was rewritten, let's handle it - if newLayout == nil { + + if newLayout.baseAddress == nil { // We have not yet collected any previous rewritten nodes. Initialize - // the new layout with the previous nodes of the parent. This is - // possible, since we know they were not rewritten. - - // The below implementation is based on Collection.map but directly - // reserves enough capacity for the entire layout. - newLayout = ContiguousArray() - newLayout!.reserveCapacity(node.raw.layoutView!.children.count) - for j in 0..(_ keyPath: WritableKeyPath<\(trait.protocolName), T>, _ newChild: T) -> \(trait.protocolName) { + public func with(_ keyPath: WritableKeyPath<\(trait.protocolName), T>, _ newChild: T) -> \(trait.protocolName) { var copy: \(trait.protocolName) = self copy[keyPath: keyPath] = newChild return copy @@ -54,13 +54,13 @@ let syntaxTraitsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { ) } - try! ExtensionDeclSyntax("public extension SyntaxProtocol") { + try! ExtensionDeclSyntax("extension SyntaxProtocol") { DeclSyntax( """ /// Check whether the non-type erased version of this syntax node conforms to /// `\(trait.protocolName)`. /// Note that this will incur an existential conversion. - func isProtocol(_: \(trait.protocolName).Protocol) -> Bool { + public func isProtocol(_: \(trait.protocolName).Protocol) -> Bool { return self.asProtocol(\(trait.protocolName).self) != nil } """ @@ -71,7 +71,7 @@ let syntaxTraitsFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// Return the non-type erased version of this syntax node if it conforms to /// `\(trait.protocolName)`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: \(trait.protocolName).Protocol) -> \(trait.protocolName)? { + public func asProtocol(_: \(trait.protocolName).Protocol) -> \(trait.protocolName)? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? \(trait.protocolName) } """ @@ -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 06d0811fd5f..19794af22e2 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntax/SyntaxVisitorFile.swift @@ -32,6 +32,13 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { try! ClassDeclSyntax("open class SyntaxVisitor") { DeclSyntax("public let viewMode: SyntaxTreeViewMode") + DeclSyntax( + """ + /// 'Syntax' object factory recycling 'Syntax.Info' instances. + private let nodeFactory: SyntaxNodeFactory = SyntaxNodeFactory() + """ + ) + DeclSyntax( """ public init(viewMode: SyntaxTreeViewMode) { @@ -45,7 +52,8 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// Walk all nodes of the given syntax tree, calling the corresponding `visit` /// function for every node that is being visited. public func walk(_ node: some SyntaxProtocol) { - visit(Syntax(node)) + var syntaxNode = Syntax(node) + visit(&syntaxNode) } """ ) @@ -94,21 +102,30 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - /// Interpret `data` as a node of type `nodeType`, visit it, calling + /// Cast `node` to a node of type `nodeType`, visit it, calling /// the `visit` and `visitPost` functions during visitation. + /// + /// - Note: node is an `inout` parameter so that callers don't have to retain it before passing it to `visitImpl`. + /// With it being an `inout` parameter, the caller and `visitImpl` can work on the same reference of `node` without + /// any reference counting. + /// - Note: Inline so that the optimizer can look through the calles to `visit` and `visitPost`, which means it + /// doesn't need to retain `self` when forming closures to the unapplied function references on `self`. + @inline(__always) private func visitImpl( - _ node: Syntax, + _ node: inout Syntax, _ nodeType: NodeType.Type, _ visit: (NodeType) -> SyntaxVisitorContinueKind, _ visitPost: (NodeType) -> Void ) { - let node = node.cast(NodeType.self) - let needsChildren = (visit(node) == .visitChildren) + let castedNode = node.cast(NodeType.self) + // We retain castedNode.info here before passing it to visit. + // I don't think that's necessary because castedNode is already retained but don't know how to prevent it. + let needsChildren = (visit(castedNode) == .visitChildren) // Avoid calling into visitChildren if possible. if needsChildren && !node.raw.layoutView!.children.isEmpty { - visitChildren(node) + visitChildren(&node) } - visitPost(node) + visitPost(castedNode) } """ ) @@ -149,7 +166,7 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { /// that determines the correct visitation function will be popped of the /// stack before the function is being called, making the switch's stack /// space transient instead of having it linger in the call stack. - private func visitationFunc(for node: Syntax) -> ((Syntax) -> Void) + private func visitationFunc(for node: Syntax) -> ((inout Syntax) -> Void) """ ) { try SwitchExprSyntax("switch node.raw.kind") { @@ -168,7 +185,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) }" + ) } } } @@ -176,8 +195,8 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - private func visit(_ node: Syntax) { - return visitationFunc(for: node)(node) + private func visit(_ node: inout Syntax) { + return visitationFunc(for: node)(&node) } """ ) @@ -188,7 +207,12 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { poundKeyword: .poundElseToken(), elements: .statements( CodeBlockItemListSyntax { - try! FunctionDeclSyntax("private func visit(_ node: Syntax)") { + try! FunctionDeclSyntax( + """ + /// - Note: `node` is `inout` to avoid ref-counting. See comment in `visitImpl` + private func visit(_ node: inout Syntax) + """ + ) { try SwitchExprSyntax("switch node.raw.kind") { SwitchCaseSyntax("case .token:") { DeclSyntax("let node = node.cast(TokenSyntax.self)") @@ -203,7 +227,7 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { for node in NON_BASE_SYNTAX_NODES { SwitchCaseSyntax("case .\(node.varOrCaseName):") { - ExprSyntax("visitImpl(node, \(node.kind.syntaxType).self, visit, visitPost)") + ExprSyntax("visitImpl(&node, \(node.kind.syntaxType).self, visit, visitPost)") } } } @@ -217,10 +241,12 @@ let syntaxVisitorFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - private func visitChildren(_ node: some SyntaxProtocol) { - let syntaxNode = Syntax(node) - for childRaw in NonNilRawSyntaxChildren(syntaxNode, viewMode: viewMode) { - visit(Syntax(childRaw, parent: syntaxNode)) + /// - Note: `node` is `inout` to avoid reference counting. See comment in `visitImpl`. + private func visitChildren(_ node: inout Syntax) { + for case let (child?, info) in RawSyntaxChildren(node) where viewMode.shouldTraverse(node: child) { + var childNode = nodeFactory.create(parent: node, raw: child, absoluteInfo: info) + visit(&childNode) + nodeFactory.dispose(&childNode) } } """ 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/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/ResultBuildersFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/ResultBuildersFile.swift index 1b02de4dc5f..1cbc33b9e1e 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/ResultBuildersFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/ResultBuildersFile.swift @@ -33,8 +33,8 @@ let resultBuildersFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { """ // MARK: - \(type.resultBuilderType) - @resultBuilder \(node.node.apiAttributes())\ + @resultBuilder public struct \(type.resultBuilderType): ListBuilder """ ) { @@ -60,8 +60,8 @@ let resultBuildersFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { DeclSyntax( """ - public extension \(type.syntaxBaseName) { - init(@\(type.resultBuilderType) itemsBuilder: () throws -> \(type.syntaxBaseName)) rethrows { + extension \(type.syntaxBaseName) { + public init(@\(type.resultBuilderType) itemsBuilder: () throws -> \(type.syntaxBaseName)) rethrows { self = try itemsBuilder() } } diff --git a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/SyntaxExpressibleByStringInterpolationConformancesFile.swift b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/SyntaxExpressibleByStringInterpolationConformancesFile.swift index b7a63319ad6..d6c237bbca9 100644 --- a/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/SyntaxExpressibleByStringInterpolationConformancesFile.swift +++ b/CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/SyntaxExpressibleByStringInterpolationConformancesFile.swift @@ -16,7 +16,15 @@ import SyntaxSupport import Utils let syntaxExpressibleByStringInterpolationConformancesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { - DeclSyntax("import SwiftSyntax") + DeclSyntax( + """ + #if swift(>=6) + internal import SwiftSyntax + #else + import SwiftSyntax + #endif + """ + ) let typesExpressibleByStringInterpolation = SYNTAX_NODES diff --git a/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift b/CodeGeneration/Tests/ValidateSyntaxNodes/ValidateSyntaxNodes.swift index 5a590359b90..93046782bf3 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')" ), ] ) @@ -501,15 +535,22 @@ class ValidateSyntaxNodes: XCTestCase { expectedFailures: [ 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: ._canImportExpr, 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" + ), + ValidationFailure(node: .lifetimeTypeSpecifier, message: "could conform to trait 'Parenthesized' but does not"), ] ) } @@ -581,7 +622,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 +636,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 +653,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 +688,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 +719,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 +820,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/README.md b/Examples/README.md index c8a8fb1657a..42805c57cc4 100644 --- a/Examples/README.md +++ b/Examples/README.md @@ -23,8 +23,8 @@ Furthermore, SwiftSyntax uses [`SwiftSyntaxBuilder`](../Sources/SwiftSyntaxBuild [**Swift AST Explorer**](https://swift-ast-explorer.com/): A Swift AST visualizer. -[**Swift Stress Tester**](https://github.com/apple/swift-stress-tester): A test driver for `sourcekitd` and Swift evolution. +[**Swift Stress Tester**](https://github.com/swiftlang/swift-stress-tester): A test driver for `sourcekitd` and Swift evolution. -[**swift-format**](https://github.com/apple/swift-format): Formatting technology for Swift source code. +[**swift-format**](https://github.com/swiftlang/swift-format): Formatting technology for Swift source code. [**SwiftLint**](https://github.com/realm/SwiftLint): A tool to enforce Swift style and conventions. 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/Expression/SourceLocationMacro.swift b/Examples/Sources/MacroExamples/Implementation/Expression/SourceLocationMacro.swift new file mode 100644 index 00000000000..822913fc9eb --- /dev/null +++ b/Examples/Sources/MacroExamples/Implementation/Expression/SourceLocationMacro.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import SwiftSyntax +import SwiftSyntaxMacros + +public struct NativeFileIDMacro: ExpressionMacro { + public static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) -> ExprSyntax { + return context.location( + of: node, + at: .afterLeadingTrivia, + filePathMode: .fileID + )!.file + } +} + +public struct NativeFilePathMacro: ExpressionMacro { + public static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) -> ExprSyntax { + return context.location( + of: node, + at: .afterLeadingTrivia, + filePathMode: .filePath + )!.file + } +} + +public struct NativeLineMacro: ExpressionMacro { + public static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) -> ExprSyntax { + return context.location(of: node)!.line + } +} + +public struct NativeColumnMacro: ExpressionMacro { + public static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) -> ExprSyntax { + return context.location(of: node)!.column + } +} 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/Implementation/Plugin.swift b/Examples/Sources/MacroExamples/Implementation/Plugin.swift index e5960e80712..66375649b10 100644 --- a/Examples/Sources/MacroExamples/Implementation/Plugin.swift +++ b/Examples/Sources/MacroExamples/Implementation/Plugin.swift @@ -31,6 +31,10 @@ struct MyPlugin: CompilerPlugin { FuncUniqueMacro.self, MemberDeprecatedMacro.self, MetaEnumMacro.self, + NativeColumnMacro.self, + NativeFileIDMacro.self, + NativeFilePathMacro.self, + NativeLineMacro.self, NewTypeMacro.self, ObservableMacro.self, ObservablePropertyMacro.self, 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/Sources/MacroExamples/Interface/SourceLocationMacros.swift b/Examples/Sources/MacroExamples/Interface/SourceLocationMacros.swift new file mode 100644 index 00000000000..baa78caa4be --- /dev/null +++ b/Examples/Sources/MacroExamples/Interface/SourceLocationMacros.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +@freestanding(expression) +public macro FileID() -> T = + #externalMacro( + module: "MacroExamplesImplementation", + type: "NativeFileIDMacro" + ) + +@freestanding(expression) +public macro FilePath() -> T = + #externalMacro( + module: "MacroExamplesImplementation", + type: "NativeFilePathMacro" + ) + +@freestanding(expression) +public macro Line() -> T = + #externalMacro( + module: "MacroExamplesImplementation", + type: "NativeLineMacro" + ) + +@freestanding(expression) +public macro Column() -> T = + #externalMacro( + module: "MacroExamplesImplementation", + type: "NativeColumnMacro" + ) diff --git a/Examples/Sources/MacroExamples/Playground/ExpressionMacrosPlayground.swift b/Examples/Sources/MacroExamples/Playground/ExpressionMacrosPlayground.swift index 17d9fcf897a..d71f086677e 100644 --- a/Examples/Sources/MacroExamples/Playground/ExpressionMacrosPlayground.swift +++ b/Examples/Sources/MacroExamples/Playground/ExpressionMacrosPlayground.swift @@ -47,7 +47,7 @@ func runExpressionMacrosPlayground() { // let domain = "domain.com" //print(#URL("https://\(domain)/api/path")) // error: #URL requires a static string literal - //print(#URL("https://not a url.com")) // error: Malformed url + //print(#URL("https://not a url.com:invalid-port/")) // error: Malformed url // MARK: - Warning diff --git a/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift b/Examples/Sources/MacroExamples/Playground/SourceLocationMacrosPlayground.swift similarity index 55% rename from Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift rename to Examples/Sources/MacroExamples/Playground/SourceLocationMacrosPlayground.swift index e48bf6dc367..ba07df19118 100644 --- a/Sources/_SwiftSyntaxTestSupport/String+TrimmingTrailingWhitespace.swift +++ b/Examples/Sources/MacroExamples/Playground/SourceLocationMacrosPlayground.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Copyright (c) 2024 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -10,9 +10,11 @@ // //===----------------------------------------------------------------------===// -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: [" "]) - } +import MacroExamplesInterface + +func runSourceLoctionMacrosPlayground() { + print("FileID: \(#FileID as String)") + print("FilePath: \(#FilePath as String)") + print("Line: \(#Line as Int)") + print("Column: \(#Column as Int)") } diff --git a/Examples/Sources/MacroExamples/Playground/main.swift b/Examples/Sources/MacroExamples/Playground/main.swift index d9af26d3e0e..19ac102630d 100644 --- a/Examples/Sources/MacroExamples/Playground/main.swift +++ b/Examples/Sources/MacroExamples/Playground/main.swift @@ -47,3 +47,7 @@ runMemberMacrosPlayground() // MARK: - Peer Macros runPeerMacrosPlayground() + +// MARK: - SourceLocationMacros + +runSourceLoctionMacrosPlayground() diff --git a/Examples/Tests/MacroExamples/Implementation/Expression/URLMacroTests.swift b/Examples/Tests/MacroExamples/Implementation/Expression/URLMacroTests.swift index b49a4133a1f..2bb79779208 100644 --- a/Examples/Tests/MacroExamples/Implementation/Expression/URLMacroTests.swift +++ b/Examples/Tests/MacroExamples/Implementation/Expression/URLMacroTests.swift @@ -21,13 +21,18 @@ final class URLMacroTests: XCTestCase { func testExpansionWithMalformedURLEmitsError() { assertMacroExpansion( """ - let invalid = #URL("https://not a url.com") + let invalid = #URL("https://not a url.com:invalid-port/") """, expandedSource: """ - let invalid = #URL("https://not a url.com") + let invalid = #URL("https://not a url.com:invalid-port/") """, diagnostics: [ - DiagnosticSpec(message: #"malformed url: "https://not a url.com""#, line: 1, column: 15, severity: .error) + DiagnosticSpec( + message: #"malformed url: "https://not a url.com:invalid-port/""#, + line: 1, + column: 15, + severity: .error + ) ], macros: macros, indentationWidth: .spaces(2) 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/MODULE.bazel b/MODULE.bazel index 07d4758742c..e711d17ce99 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -4,5 +4,6 @@ module( compatibility_level = 1, ) -bazel_dep(name = "rules_swift", version = "1.16.0", repo_name = "build_bazel_rules_swift") -bazel_dep(name = "apple_support", version = "1.11.1", repo_name = "build_bazel_apple_support") +bazel_dep(name = "apple_support", version = "1.13.0", repo_name = "build_bazel_apple_support") +bazel_dep(name = "rules_apple", version = "3.3.0", repo_name = "build_bazel_rules_apple") +bazel_dep(name = "rules_swift", version = "1.18.0", max_compatibility_level = 2, repo_name = "build_bazel_rules_swift") diff --git a/Package.swift b/Package.swift index 62d7a020d8d..59e62e1f515 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.7 +// swift-tools-version:5.8 import Foundation import PackageDescription @@ -15,7 +15,6 @@ let package = Package( products: [ .library(name: "SwiftBasicFormat", targets: ["SwiftBasicFormat"]), .library(name: "SwiftCompilerPlugin", targets: ["SwiftCompilerPlugin"]), - .library(name: "SwiftCompilerPluginMessageHandling", targets: ["SwiftCompilerPluginMessageHandling"]), .library(name: "SwiftDiagnostics", targets: ["SwiftDiagnostics"]), .library(name: "SwiftIDEUtils", targets: ["SwiftIDEUtils"]), .library(name: "SwiftOperators", targets: ["SwiftOperators"]), @@ -27,12 +26,14 @@ let package = Package( .library(name: "SwiftSyntaxMacros", targets: ["SwiftSyntaxMacros"]), .library(name: "SwiftSyntaxMacroExpansion", targets: ["SwiftSyntaxMacroExpansion"]), .library(name: "SwiftSyntaxMacrosTestSupport", targets: ["SwiftSyntaxMacrosTestSupport"]), + .library(name: "SwiftSyntaxMacrosGenericTestSupport", targets: ["SwiftSyntaxMacrosGenericTestSupport"]), + .library(name: "_SwiftCompilerPluginMessageHandling", targets: ["SwiftCompilerPluginMessageHandling"]), + .library(name: "_SwiftLibraryPluginProvider", targets: ["SwiftLibraryPluginProvider"]), ], targets: [ // MARK: - Internal helper targets - .target( - name: "_AtomicBool" + name: "_SwiftSyntaxCShims" ), .target( @@ -41,7 +42,18 @@ let package = Package( .target( name: "_SwiftSyntaxTestSupport", - dependencies: ["SwiftBasicFormat", "SwiftSyntax", "SwiftSyntaxBuilder", "SwiftSyntaxMacroExpansion"] + dependencies: [ + "_SwiftSyntaxGenericTestSupport", + "SwiftBasicFormat", + "SwiftSyntax", + "SwiftSyntaxBuilder", + "SwiftSyntaxMacroExpansion", + ] + ), + + .target( + name: "_SwiftSyntaxGenericTestSupport", + dependencies: [] ), .testTarget( @@ -87,7 +99,15 @@ let package = Package( .target( name: "SwiftCompilerPluginMessageHandling", - dependencies: ["SwiftDiagnostics", "SwiftOperators", "SwiftParser", "SwiftSyntax", "SwiftSyntaxMacros", "SwiftSyntaxMacroExpansion"], + dependencies: [ + "_SwiftSyntaxCShims", + "SwiftDiagnostics", + "SwiftOperators", + "SwiftParser", + "SwiftSyntax", + "SwiftSyntaxMacros", + "SwiftSyntaxMacroExpansion", + ], exclude: ["CMakeLists.txt"] ), @@ -117,11 +137,24 @@ let package = Package( dependencies: ["_SwiftSyntaxTestSupport", "SwiftIDEUtils", "SwiftParser", "SwiftSyntax"] ), + // MARK: SwiftLibraryPluginProvider + + .target( + name: "SwiftLibraryPluginProvider", + dependencies: ["SwiftSyntaxMacros", "SwiftCompilerPluginMessageHandling", "_SwiftLibraryPluginProviderCShims"], + exclude: ["CMakeLists.txt"] + ), + + .target( + name: "_SwiftLibraryPluginProviderCShims", + exclude: ["CMakeLists.txt"] + ), + // MARK: SwiftSyntax .target( name: "SwiftSyntax", - dependencies: ["_AtomicBool", "SwiftSyntax509", "SwiftSyntax510", "SwiftSyntax600"], + dependencies: ["_SwiftSyntaxCShims", "SwiftSyntax509", "SwiftSyntax510", "SwiftSyntax600"], exclude: ["CMakeLists.txt"], swiftSettings: swiftSyntaxSwiftSettings ), @@ -183,8 +216,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 +232,26 @@ let package = Package( .target( name: "SwiftSyntaxMacrosTestSupport", - dependencies: ["_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftIDEUtils", "SwiftParser", "SwiftSyntaxMacros", "SwiftSyntaxMacroExpansion"] + dependencies: [ + "SwiftSyntax", + "SwiftSyntaxMacroExpansion", + "SwiftSyntaxMacros", + "SwiftSyntaxMacrosGenericTestSupport", + ] + ), + + // MARK: SwiftSyntaxMacrosGenericTestSupport + + .target( + name: "SwiftSyntaxMacrosGenericTestSupport", + dependencies: [ + "_SwiftSyntaxGenericTestSupport", + "SwiftDiagnostics", + "SwiftIDEUtils", + "SwiftParser", + "SwiftSyntaxMacros", + "SwiftSyntaxMacroExpansion", + ] ), .testTarget( @@ -211,7 +270,14 @@ let package = Package( .testTarget( name: "SwiftParserTest", - dependencies: ["_SwiftSyntaxTestSupport", "SwiftDiagnostics", "SwiftIDEUtils", "SwiftOperators", "SwiftParser", "SwiftSyntaxBuilder"], + dependencies: [ + "_SwiftSyntaxTestSupport", + "SwiftDiagnostics", + "SwiftIDEUtils", + "SwiftOperators", + "SwiftParser", + "SwiftSyntaxBuilder", + ], swiftSettings: swiftParserSwiftSettings ), @@ -266,7 +332,8 @@ let package = Package( dependencies: ["_InstructionCounter", "_SwiftSyntaxTestSupport", "SwiftIDEUtils", "SwiftParser", "SwiftSyntax"], exclude: ["Inputs"] ), - ] + ], + swiftLanguageVersions: [.v5, .version("6")] ) // This is a fake target that depends on all targets in the package. diff --git a/README.md b/README.md index 18d211b4005..c477c3ac70c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ The swift-syntax package is a set of libraries that work on a source-accurate tr ## Documentation -You can read SwiftSyntax’s documentation on [swiftpackageindex.com](https://swiftpackageindex.com/apple/swift-syntax/documentation). +You can read SwiftSyntax’s documentation on [swiftpackageindex.com](https://swiftpackageindex.com/swiftlang/swift-syntax/documentation). A great way to interactively explore the SwiftSyntax tree of a source file is https://swift-ast-explorer.com, developed by [@kishikawakatsumi](https://github.com/kishikawakatsumi). @@ -19,15 +19,15 @@ To depend on swift-syntax in a SwiftPM package, add the following to your `Packa ```swift dependencies: [ - .package(url: "https://github.com/apple/swift-syntax.git", from: "<#latest swift-syntax tag#>"), + .package(url: "https://github.com/swiftlang/swift-syntax.git", from: "<#latest swift-syntax tag#>"), ], ``` -To add swift-syntax as a dependency of your Xcode project, go to the *Package Dependencies* tab of your Xcode project, click the plus button and search for https://github.com/apple/swift-syntax.git. +To add swift-syntax as a dependency of your Xcode project, go to the *Package Dependencies* tab of your Xcode project, click the plus button and search for https://github.com/swiftlang/swift-syntax.git. ## Reporting Issues -If you should hit any issues while using SwiftSyntax, we appreciate bug reports on [GitHub Issue](https://github.com/apple/swift-syntax/issues). +If you should hit any issues while using SwiftSyntax, we appreciate bug reports on [GitHub Issue](https://github.com/swiftlang/swift-syntax/issues). ## Contributing @@ -42,7 +42,7 @@ into your `WORKSPACE` and depend on the libraries you need from the `Library_opt` target (such as `SwiftSyntax_opt`) which forces SwiftSyntax to always build with optimizations enabled. This may help local runtime performance at the cost of debuggability, and initial -build time. Please tag any [issues](https://github.com/apple/swift-syntax/issues) related to the Bazel configuration with the label "Bazel". +build time. Please tag any [issues](https://github.com/swiftlang/swift-syntax/issues) related to the Bazel configuration with the label "Bazel". ## License diff --git a/Release Notes/600.md b/Release Notes/600.md index e9e318e5c00..32d15208343 100644 --- a/Release Notes/600.md +++ b/Release Notes/600.md @@ -3,73 +3,101 @@ ## New APIs - FixIt now has a new computed property named `edits` - Description: the `edits` represent the non-overlapping textual `edits` that need to be performed when the Fix-It is applied. - - Issue: https://github.com/apple/sourcekit-lsp/issues/909 - - Pull Request: https://github.com/apple/swift-syntax/pull/2314 + - Issue: https://github.com/swiftlang/sourcekit-lsp/issues/909 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2314 - `SourceEdit` - Description: `SourceEdit` has been moved from SwiftRefactor to SwiftSyntax - - Issue: https://github.com/apple/sourcekit-lsp/issues/909 - - Pull Request: https://github.com/apple/swift-syntax/pull/2314 + - Issue: https://github.com/swiftlang/sourcekit-lsp/issues/909 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2314 - `assertMacroExpansion` now have new parameters named `applyFixIts` and `fixedSource` - Description: `applyFixIts` and `fixedSource` are used to assert so ensure that the source code after applying Fix-Its matches this string. - - Issue: https://github.com/apple/swift-syntax/issues/2015 - - Pull Request: https://github.com/apple/swift-syntax/pull/2021 + - Issue: https://github.com/swiftlang/swift-syntax/issues/2015 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2021 - `DeclSyntaxEnum`, `StmtSyntaxEnum`, `ExprSyntaxEnum`, `TypeSyntaxEnum`, and `PatternSyntaxEnum` - Description: Enum to exhaustively switch over all different syntax nodes of each base type. - - Pull Request: https://github.com/apple/swift-syntax/pull/2351 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2351 - `WithOptionalCodeBlock` - Description: A trait for syntax nodes that have an optional code block, such as `FunctionDeclSyntax` and `InitializerDeclSyntax`. - - Pull Request: https://github.com/apple/swift-syntax/pull/2359 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2359 - `CodeBlockSyntax` - Description: `CodeBlockSyntax` is now `SyntaxParseable`, so it can be used with string interpolations. - - Pull Request: https://github.com/apple/swift-syntax/pull/2361 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2361 - `ThrowsClause` - Description: The `throwsSpecifier` for the effects nodes (`AccessorEffectSpecifiers`, `FunctionEffectSpecifiers`, `TypeEffectSpecifiers`, `EffectSpecifiers`) has been replaced with `throwsClause`, which captures both the throws specifier and the (optional) thrown error type, as introduced by SE-0413. - - Pull Request: https://github.com/apple/swift-syntax/pull/2379 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2379 -- `String.isValidIdentifier(for:)` +- `String.isValidSwiftIdentifier(for:)` - Description: `SwiftParser` adds an extension on `String` to check if it can be used as an identifier in a given context. - - Pull Request: https://github.com/apple/swift-syntax/pull/2434 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2434 - `MacroDeclSyntax.expand` - the `expand(argumentList:definition:replacements:)` method gains a new parameter 'genericReplacements:' that is defaulted to an empty array. - The method's signature is now `expand(argumentList:definition:replacements:genericReplacements:)` - - Pull Request: https://github.com/apple/swift-syntax/pull/2450 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2450 - `SyntaxProtocol.asMacroLexicalContext()` and `allMacroLexicalContexts(enclosingSyntax:)` - Description: Produce the lexical context for a given syntax node (if it has one), or the entire stack of lexical contexts enclosing a syntax node, for use in macro expansion. - - Pull request: https://github.com/apple/swift-syntax/pull/1554 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/1554 - `TriviaPiece.isComment` - Description: `TriviaPiece` now has a computed property `isComment` that returns `true` if the trivia piece is a comment. - - Pull Request: https://github.com/apple/swift-syntax/pull/2469 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2469 - New `assertMacroExpansion` API with option to specify macro specifications with `macroSpecs` argument - Description: `macroSpecs` can have additional specifications like conformances provided by member or extension macro that can be used for macro expansion. - - Issue: https://github.com/apple/swift-syntax/issues/2031 - - Pull Request: https://github.com/apple/swift-syntax/pull/2327 + - Issue: https://github.com/swiftlang/swift-syntax/issues/2031 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2327 - `BasicFormat.inferIndentation(of:)` - Description: Uses heuristics to infer the indentation width used in a syntax tree. - - Pull Request: https://github.com/apple/swift-syntax/pull/2514 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2514 - `IncrementalEdit` stores replacement text - Description: `IncrementalEdit` used to store the range that was replaced and the length of the replacement but not the replacement bytes by itself. `IncrementalEdit` now has a `replacement` property that contains the replacement bytes. - - Pull Request: https://github.com/apple/swift-syntax/pull/2527 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2527 - Type specifiers - Description: `AttributedTypeSyntax` can now contain multiple specifiers and these types are used to model the list of specifiers. Additionally, type specifiers can now contain arguments, like `borrow(data)`. To facilitate this, the following new types were introduces: `LifetimeSpecifierArgumentListSyntax`, `LifetimeSpecifierArgumentSyntax`, `LifetimeSpecifierArgumentsSyntax`, `LifetimeTypeSpecifierSyntax`, `SimpleTypeSpecifierSyntax`, `TypeSpecifierListSyntax` - - Pull request: https://github.com/apple/swift-syntax/pull/2433 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2433 - `DeclGroupSyntax.introducer` - Description: The `DeclGroupSyntax` trait has an extra `introducer` property, ie. the keyword that introduces the declaration. - - Issue: https://github.com/apple/sourcekit-lsp/issues/2535 - - Pull Request: https://github.com/apple/swift-syntax/pull/2539 + - Issue: https://github.com/swiftlang/sourcekit-lsp/issues/2535 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2539 + +- `ExprSyntax.interpretedAsVersionTuple` + - Description: With the change to parse `#if canImport(MyModule, _version: 1.2.3)` as a function call instead of a dedicated syntax node, `1.2.3` natively gets parsed as a member access `3` to the `1.2` float literal. This property allows the reinterpretation of such an expression as a version tuple. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2025 + +- `SyntaxProtocol.node(at:)` + - Description: Given a `SyntaxIdentifier`, returns the `Syntax` node with that identifier + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2594 + +- `SyntaxIdentifier.IndexInTree` + - Description: Uniquely identifies a syntax node within a tree. This is similar to ``SyntaxIdentifier`` but does not store the root ID of the tree. It can thus be transferred across trees that are structurally equivalent, for example two copies of the same tree that live in different processes. The only public functions on this type are `toOpaque` and `init(fromOpaque:)`, which allow serialization of the `IndexInTree`. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2594 + +- `SyntaxIdentifier` conformance to `Comparable`: + - Description: A `SyntaxIdentifier` compares less than another `SyntaxIdentifier` if the node at that identifier occurs first during a depth-first traversal of the tree. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2594 + +- `SyntaxIdentifier.indexInTree` and `SyntaxIdentifier.fromIndexInTree` + - Description: `SyntaxIdentifier.indexInTree` allows the retrieval of a `SyntaxIdentifier` that identifies the syntax node independent of the syntax tree. `SyntaxIdentifier.fromIndexInTree` allows the creation for a `SyntaxIdentifier` from a tree-agnostic `SyntaxIdentifier.IndexInTree` and the tree's root node. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2594 + +- `SwiftSyntaxMacrosGenericTestSupport` + - Description: A version of the `SwiftSyntaxMacrosTestSupport` module that doesn't depend on `Foundation` or `XCTest` and can thus be used to write macro tests using `swift-testing`. Since swift-syntax can't depend on swift-testing (which would incur a circular dependency since swift-testing depends on swift-syntax), users need to manually specify a failure handler like the following, that fails the swift-testing test: `Issue.record("\($0.message)", fileID: $0.location.fileID, filePath: $0.location.filePath, line: $0.location.line, column: $0.location.column)` + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2647 + +- `TokenSyntax.identifier` + - Description: Adds an `identifier` property to `TokenSyntax` which returns a canonicalized representation of an identifier that strips away backticks. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2576 ## API Behavior Changes @@ -77,77 +105,86 @@ - Child Choice Node Casts - Description: `is`, `as`, and `cast` methods for types not contained in the choice node are marked as deprecated. The deprecated methods will emit a warning, indicating that the cast will always fail. - - Issue: https://github.com/apple/swift-syntax/issues/2092 - - Pull Request: https://github.com/apple/swift-syntax/pull/2184 + - Issue: https://github.com/swiftlang/swift-syntax/issues/2092 + - Pull Request: https://github.com/swiftlang/swift-syntax/pull/2184 - Migration steps: Remove the `is`, `as` or `cast` methods because they will always fail. - `IncrementalParseTransition`: - Description: The initializer `IncrementalParseTransition.init(previousTree:edits:lookaheadRanges:reusedNodeCallback:)` is marked as deprecated. Use `IncrementalParseTransition.init(previousIncrementalParseResult:edits:reusedNodeCallback:)` instead. - - Issue: https://github.com/apple/swift-syntax/issues/2267 - - Pull request: https://github.com/apple/swift-syntax/pull/2272 + - Issue: https://github.com/swiftlang/swift-syntax/issues/2267 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2272 - Migration steps: Call `IncrementalParseTransition.init(previousIncrementalParseResult:edits:reusedNodeCallback:)` instead. - `MacroExpansion{Error|Warning|FixIt}Message` moved to the `SwiftSyntaxMacros` module - Description: Move the `MacroExpansion{Error|Warning|FixIt}Message` types from the `SwiftSyntaxMacroExpansion` module to `SwiftSyntaxMacros`. Deprecated typealiases in `SwiftSyntaxMacroExpansion` forward to `SwiftSyntaxMacros`. - - Pull request: https://github.com/apple/swift-syntax/pull/2338 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2338 - Notes: The expansion diagnostic messages were defined in `SwiftSyntaxMacroExpansion`, which is intended as an implementation detail of the plugin server and should not need to be imported by macros. - `EditorPlaceholderDeclSyntax` and `EditorPlaceholderExprSyntax`: - Description: `EditorPlaceholderDeclSyntax` and `EditorPlaceholderExprSyntax` are now deprecated and placeholders are instead parsed as identifiers within a `MissingDeclSyntax` or `DeclReferenceExprSyntax`. - - Pull request: https://github.com/apple/swift-syntax/pull/2237 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2237 - `AttributedTypeSyntax.specifier` has renamed to `specifiers` and changed to be a collection - Description: Types can have multiple specifiers now and the syntax tree has been modified to reflect that. - - Pull request: https://github.com/apple/swift-syntax/pull/2433 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2433 + +- ` CanImportExprSyntax` and `CanImportVersionInfoSyntax` + - Description: Instead of parsing `canImport` inside `#if` directives as a special expression node, parse it as a functionc call expression. This is in-line with how the `swift(>=6.0)` and `compiler(>=6.0)` directives are parsed. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2025 ## API-Incompatible Changes - `MacroDefinition` used for expanding macros: - Description: The `MacroDefinition/expansion` enum case used to have two values (`(MacroExpansionExprSyntax, replacements: [Replacement])`), has now gained another value in order to support generic argument replacements in macro expansions: `(MacroExpansionExprSyntax, replacements: [Replacement], genericReplacements: [GenericArgumentReplacement])` - - Pull request: https://github.com/apple/swift-syntax/pull/2450 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2450 - Migration steps: Code which exhaustively checked over the enum should be changed to `case .expansion(let node, let replacements, let genericReplacements):`. Creating the `.extension` gained a compatibility shim, retaining the previous syntax source compatible (`return .expansion(node, replacements: [])`). - Effect specifiers: - Description: The `unexpectedAfterThrowsSpecifier` node of the various effect specifiers has been removed. - - Pull request: https://github.com/apple/swift-syntax/pull/2219 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2219 - Migration steps: Check `unexpectedBetweenThrowsSpecifierAndThrownError` and `unexpectedAfterThrownError` instead. - `SyntaxKind` removed conformance to `CaseIterable` - Description: `SyntaxKind` no longer conforms to `CaseIterable` since there is no good use case to iterate over all syntax kinds. - - Pull request: https://github.com/apple/swift-syntax/pull/2292 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2292 - Migration steps: Exhaustively check all the syntax nodes that your program supports. There should be no use case to iterate over all cases in `SyntaxKind`. - `IntegerLiteralExprSyntax.Radix` removed conformance to `CaseIterable` - Description: `IntegerLiteralExprSyntax.Radix` no longer conforms to `CaseIterable` since there is no good use case to iterate over all radix kinds. - - Pull request: https://github.com/apple/swift-syntax/pull/2292 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2292 - Migration steps: There should be no use case to iterate over all cases in `IntegerLiteralExprSyntax.Radix`. - `Parser.parseIncrementally(source:parseTransition:)` and `Parser.parseIncrementally(source:maximumNestingLevel:parseTransition:)`: - Description: The default versions of `Parser.parseIncrementally` return a `IncrementalParseResult` instead of a tuple. Access to the struct should be compatible with the tuple in almost all cases unless the tuple is stored into a variable and then destructed or passed to a function that expects a tuple. - - Issue: https://github.com/apple/swift-syntax/issues/2267 - - Pull request: https://github.com/apple/swift-syntax/pull/2272 + - Issue: https://github.com/swiftlang/swift-syntax/issues/2267 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2272 - Migration steps: If necessary, change type annotations from the tuple to the `IncrementalParseResult` type. - `SyntaxClassification` gained a new case: `argumentLabel` - The new classification case covers the first names of parameters in function-like declarations and the label of arguments in function-like calls. - - Pull request: https://github.com/apple/swift-syntax/pull/2375 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2375 - Migration steps: In exhaustive switches over `SyntaxClassification`, cover the new case. - `SyntaxEnum` and `SyntaxKind` gained new cases: `throwsClause` - The new cases cover the newly introduced `ThrowsClauseSyntax` - - Pull request: https://github.com/apple/swift-syntax/pull/2379 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2379 - Migration steps: In exhaustive switches over `SyntaxEnum` and `SyntaxKind`, cover the new case. - `MacroExpansionContext` now requires a property `lexicalContext`: - Description: The new property provides the lexical context in which the macro is expanded, and has several paired API changes. Types that conform to `MacroExpansionContext` will need to implement this property. Additionally, the `HostToPluginMessage` cases `expandFreestandingMacro` and `expandAttachedMacro` now include an optional `lexicalContext`. Finally, the `SyntaxProtocol.expand(macros:in:indentationWidth:)` syntactic expansion operation has been deprecated in favor of a new version `expand(macros:contextGenerator:indentationWidth:)` that takes a function produces a new macro expansion context for each expansion. - - Pull request: https://github.com/apple/swift-syntax/pull/1554 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/1554 - Migration steps: Add the new property `lexicalContext` to any `MacroExpansionContext`-conforming types. If implementing the host-to-plugin message protocol, add support for `lexicalContext`. For macro expansion operations going through `SyntaxProtocol.expand`, provide a context generator that creates a fresh context including the lexical context. - `TriviaPiece.isBackslash` in `SwiftParserDiagnostics` removed - Description: `TriviaPiece.isBackslash` was not intended to be public API. - - Pull request: https://github.com/apple/swift-syntax/pull/2531 + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2531 - Migration steps: Use `if case .backslash = triviaPiece` instead +- All symbols in `SwiftCompilerPluginMessageHandling` are now SPI + - Description: This module is only intended to be used from some internal components. Any other modules should not use them directly. + - Pull request: https://github.com/swiftlang/swift-syntax/pull/2489 + - Migration steps: Stop using this module. + ## Template - *Affected API or two word description* diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index f5df62c776e..cd75c1080ef 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -6,9 +6,12 @@ # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for Swift project authors +add_subdirectory(_SwiftLibraryPluginProviderCShims) +add_subdirectory(_SwiftSyntaxCShims) add_subdirectory(SwiftBasicFormat) add_subdirectory(SwiftSyntax) add_subdirectory(SwiftDiagnostics) +add_subdirectory(SwiftLibraryPluginProvider) add_subdirectory(SwiftParser) add_subdirectory(SwiftParserDiagnostics) add_subdirectory(SwiftRefactor) diff --git a/Sources/SwiftBasicFormat/BasicFormat.swift b/Sources/SwiftBasicFormat/BasicFormat.swift index ee63614091a..2e50a4e9c82 100644 --- a/Sources/SwiftBasicFormat/BasicFormat.swift +++ b/Sources/SwiftBasicFormat/BasicFormat.swift @@ -148,7 +148,7 @@ open class BasicFormat: SyntaxRewriter { return true case .ifConfigClauseList: return true - case .memberDeclList: + case .memberBlockItemList: return true case .switchCaseList: return true @@ -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), @@ -308,41 +310,32 @@ open class BasicFormat: SyntaxRewriter { (.backtick, _), (.dollarIdentifier, .period), // a.b (.endOfFile, _), - (.exclamationMark, .leftParen), // myOptionalClosure!() (.exclamationMark, .period), // myOptionalBar!.foo() - (.regexPoundDelimiter, .leftParen), // opening extended regex delimiter should never be separate by a space (.regexPoundDelimiter, .regexSlash), // opening extended regex delimiter should never be separate by a space (.identifier, .leftAngle), // MyType - (.identifier, .leftParen), // foo() (.identifier, .leftSquare), // myArray[1] (.identifier, .period), // a.b (.integerLiteral, .period), // macOS 11.2.1 (.keyword(.Any), .period), // Any.Type (.keyword(.`init`), .leftAngle), // init() - (.keyword(.`init`), .leftParen), // init() (.keyword(.self), .period), // self.someProperty - (.keyword(.self), .leftParen), // self() (.keyword(.self), .leftSquare), // self[] (.keyword(.Self), .period), // Self.someProperty - (.keyword(.Self), .leftParen), // Self() (.keyword(.Self), .leftSquare), // Self[] - (.keyword(.set), .leftParen), // var mVar: Int { set(value) {} } - (.keyword(.subscript), .leftParen), // subscript(x: Int) (.keyword(.super), .period), // super.someProperty (.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?() (.postfixQuestionMark, .period), // someOptional?.someProperty (.pound, _), - (.poundUnavailable, .leftParen), // #unavailable(...) (.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 @@ -350,10 +343,7 @@ open class BasicFormat: SyntaxRewriter { (.regexPoundDelimiter, .period), // #/myRegex/#.someMember (.regexSlash, .regexPoundDelimiter), // closing extended regex delimiter should never be separate by a space (.regexSlash, .period), // /myRegex/.someMember - (.rightAngle, .leftParen), // func foo(x: T) (.rightAngle, .period), // Foo.bar - (.rightBrace, .leftParen), // { return 1 }() - (.rightParen, .leftParen), // returnsClosure()() (.rightParen, .period), // foo().bar (.rightSquare, .period), // myArray[1].someProperty (.singleQuote, .rawStringPoundDelimiter), // closing raw string delimiter should never be separate by a space @@ -373,15 +363,31 @@ open class BasicFormat: SyntaxRewriter { (nil, _): return false case (_, .colon): - if second?.keyPathInParent != \TernaryExprSyntax.colon - && second?.keyPathInParent != \UnresolvedTernaryExprSyntax.colon - { + switch second?.keyPathInParent { + case \TernaryExprSyntax.colon, + \UnresolvedTernaryExprSyntax.colon: + break + default: 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 + case (_, .leftParen): + switch second?.keyPathInParent { + case \ClosureParameterClauseSyntax.leftParen, + \FunctionTypeSyntax.leftParen, + \TupleExprSyntax.leftParen, + \TuplePatternSyntax.leftParen, + \TupleTypeSyntax.leftParen: + break + default: + 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/SwiftBasicFormat/SwiftBasicFormat.docc/FilingBugReports.md b/Sources/SwiftBasicFormat/SwiftBasicFormat.docc/FilingBugReports.md index 3c6179ab246..a79eccaaa66 100644 --- a/Sources/SwiftBasicFormat/SwiftBasicFormat.docc/FilingBugReports.md +++ b/Sources/SwiftBasicFormat/SwiftBasicFormat.docc/FilingBugReports.md @@ -15,4 +15,4 @@ or openning `SwiftParserCLI` package and building the `swift-parser-cli` target swift-parser-cli basic-format /path/to/file/that/formats/incorrectly.swift ``` 2. Remove as much code from your source file while still experiencing the formatting issue. -3. File a bug report on with the reduced source code. +3. File a bug report on with the reduced source code. diff --git a/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift b/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift index 981e1370e24..5a0e5d6a5dc 100644 --- a/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift +++ b/Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift @@ -16,9 +16,9 @@ public import SwiftSyntax import SwiftSyntax #endif -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Build a syntax node from this `Buildable` and format it with the given format. - func formatted(using format: BasicFormat = BasicFormat()) -> Syntax { + public func formatted(using format: BasicFormat = BasicFormat()) -> Syntax { format.reset() return format.rewrite(self) } diff --git a/Sources/SwiftCompilerPlugin/CMakeLists.txt b/Sources/SwiftCompilerPlugin/CMakeLists.txt index 1e69e0b690c..20c7d9a7872 100644 --- a/Sources/SwiftCompilerPlugin/CMakeLists.txt +++ b/Sources/SwiftCompilerPlugin/CMakeLists.txt @@ -13,4 +13,5 @@ add_swift_syntax_library(SwiftCompilerPlugin target_link_swift_syntax_libraries(SwiftCompilerPlugin PUBLIC SwiftSyntaxMacros - SwiftCompilerPluginMessageHandling) + SwiftCompilerPluginMessageHandling +) diff --git a/Sources/SwiftCompilerPlugin/CompilerPlugin.swift b/Sources/SwiftCompilerPlugin/CompilerPlugin.swift index 8787de36aab..3ced3a43de1 100644 --- a/Sources/SwiftCompilerPlugin/CompilerPlugin.swift +++ b/Sources/SwiftCompilerPlugin/CompilerPlugin.swift @@ -9,25 +9,13 @@ // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// -// NOTE: This basic plugin mechanism is mostly copied from -// https://github.com/apple/swift-package-manager/blob/main/Sources/PackagePlugin/Plugin.swift #if swift(>=6.0) public import SwiftSyntaxMacros -private import Foundation -private import SwiftCompilerPluginMessageHandling +@_spi(PluginMessage) private import SwiftCompilerPluginMessageHandling #else import SwiftSyntaxMacros -import Foundation -import SwiftCompilerPluginMessageHandling -#endif - -#if os(Windows) -#if swift(>=6.0) -private import ucrt -#else -import ucrt -#endif +@_spi(PluginMessage) import SwiftCompilerPluginMessageHandling #endif // @@ -86,8 +74,23 @@ 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)'") + let pluginPath: String + if CommandLine.argc > 0, let cPluginPath = CommandLine.unsafeArgv[0] { + pluginPath = String(cString: cPluginPath) + } else { + pluginPath = "" + } + throw CompilerPluginError( + message: + "macro implementation type '\(moduleName).\(typeName)' could not be found in executable plugin '\(pluginPath)'" + ) + } +} + +struct CompilerPluginError: Error, CustomStringConvertible { + var description: String + init(message: String) { + self.description = message } } @@ -103,157 +106,12 @@ struct MacroProviderAdapter: PluginProvider { extension CompilerPlugin { - /// Main entry point of the plugin — sets up a communication channel with - /// the plugin host and runs the main message loop. + /// Main entry point of the plugin — sets up a standard I/O communication + /// channel with the plugin host and runs the main message loop. public static func main() throws { - // Duplicate the `stdin` file descriptor, which we will then use for - // receiving messages from the plugin host. - let inputFD = dup(fileno(stdin)) - guard inputFD >= 0 else { - internalError("Could not duplicate `stdin`: \(describe(errno: errno)).") - } - - // Having duplicated the original standard-input descriptor, we close - // `stdin` so that attempts by the plugin to read console input (which - // are usually a mistake) return errors instead of blocking. - guard close(fileno(stdin)) >= 0 else { - internalError("Could not close `stdin`: \(describe(errno: errno)).") - } - - // Duplicate the `stdout` file descriptor, which we will then use for - // sending messages to the plugin host. - let outputFD = dup(fileno(stdout)) - guard outputFD >= 0 else { - internalError("Could not dup `stdout`: \(describe(errno: errno)).") - } - - // Having duplicated the original standard-output descriptor, redirect - // `stdout` to `stderr` so that all free-form text output goes there. - guard dup2(fileno(stderr), fileno(stdout)) >= 0 else { - internalError("Could not dup2 `stdout` to `stderr`: \(describe(errno: errno)).") - } - - // Turn off full buffering so printed text appears as soon as possible. - // Windows is much less forgiving than other platforms. If line - // buffering is enabled, we must provide a buffer and the size of the - // buffer. As a result, on Windows, we completely disable all - // buffering, which means that partial writes are possible. - #if os(Windows) - setvbuf(stdout, nil, _IONBF, 0) - #else - setvbuf(stdout, nil, _IOLBF, 0) - #endif - - // Open a message channel for communicating with the plugin host. - let connection = PluginHostConnection( - inputStream: FileHandle(fileDescriptor: inputFD), - outputStream: FileHandle(fileDescriptor: outputFD) - ) - - // Handle messages from the host until the input stream is closed, - // indicating that we're done. + let connection = try StandardIOMessageConnection() let provider = MacroProviderAdapter(plugin: Self()) - let impl = CompilerPluginMessageHandler(connection: connection, provider: provider) - do { - try impl.main() - } catch { - // Emit a diagnostic and indicate failure to the plugin host, - // and exit with an error code. - internalError(String(describing: error)) - } - } - - // Private function to report internal errors and then exit. - fileprivate static func internalError(_ message: String) -> Never { - fputs("Internal Error: \(message)\n", stderr) - exit(1) - } - - // Private function to construct an error message from an `errno` code. - fileprivate static func describe(errno: Int32) -> String { - if let cStr = strerror(errno) { return String(cString: cStr) } - return String(describing: errno) - } -} - -internal struct PluginHostConnection: MessageConnection { - fileprivate let inputStream: FileHandle - fileprivate let outputStream: FileHandle - - func sendMessage(_ message: TX) throws { - // Encode the message as JSON. - let payload = try JSONEncoder().encode(message) - - // Write the header (a 64-bit length field in little endian byte order). - var count = UInt64(payload.count).littleEndian - let header = Swift.withUnsafeBytes(of: &count) { Data($0) } - precondition(header.count == 8) - - // Write the header and payload. - try outputStream._write(contentsOf: header) - try outputStream._write(contentsOf: payload) - } - - func waitForNextMessage(_ ty: RX.Type) throws -> RX? { - // Read the header (a 64-bit length field in little endian byte order). - guard - let header = try inputStream._read(upToCount: 8), - header.count != 0 - else { - return nil - } - guard header.count == 8 else { - throw PluginMessageError.truncatedHeader - } - - // Decode the count. - let count = header.withUnsafeBytes { - UInt64(littleEndian: $0.loadUnaligned(as: UInt64.self)) - } - guard count >= 2 else { - throw PluginMessageError.invalidPayloadSize - } - - // Read the JSON payload. - guard - let payload = try inputStream._read(upToCount: Int(count)), - payload.count == count - else { - throw PluginMessageError.truncatedPayload - } - - // Decode and return the message. - return try JSONDecoder().decode(RX.self, from: payload) - } - - enum PluginMessageError: Swift.Error { - case truncatedHeader - case invalidPayloadSize - case truncatedPayload - } -} - -private extension FileHandle { - func _write(contentsOf data: Data) throws { - if #available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) { - return try self.write(contentsOf: data) - } else { - return self.write(data) - } - } - - func _read(upToCount count: Int) throws -> Data? { - if #available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) { - return try self.read(upToCount: count) - } else { - return self.readData(ofLength: 8) - } - } -} - -struct CompilerPluginError: Error, CustomStringConvertible { - var description: String - init(message: String) { - self.description = message + let impl = CompilerPluginMessageListener(connection: connection, provider: provider) + impl.main() } } diff --git a/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt b/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt index f01fc1f2f15..e0323a7abfc 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt +++ b/Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt @@ -9,10 +9,16 @@ add_swift_syntax_library(SwiftCompilerPluginMessageHandling CompilerPluginMessageHandler.swift Diagnostics.swift + LRUCache.swift Macros.swift PluginMacroExpansionContext.swift PluginMessageCompatibility.swift PluginMessages.swift + JSON/CodingUtilities.swift + JSON/JSON.swift + JSON/JSONDecoding.swift + JSON/JSONEncoding.swift + StandardIOMessageConnection.swift ) target_link_swift_syntax_libraries(SwiftCompilerPluginMessageHandling PUBLIC @@ -22,4 +28,9 @@ target_link_swift_syntax_libraries(SwiftCompilerPluginMessageHandling PUBLIC SwiftParser SwiftSyntaxMacros SwiftSyntaxMacroExpansion - SwiftOperators) + SwiftOperators +) + +target_link_swift_syntax_libraries(SwiftCompilerPluginMessageHandling PRIVATE + _SwiftSyntaxCShims +) diff --git a/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift b/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift index c978f949774..0d680ff69ad 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/CompilerPluginMessageHandler.swift @@ -11,17 +11,23 @@ //===----------------------------------------------------------------------===// #if swift(>=6) +private import _SwiftSyntaxCShims public import SwiftSyntaxMacros #else +@_implementationOnly import _SwiftSyntaxCShims import SwiftSyntaxMacros #endif /// Optional features. +@_spi(PluginMessage) public enum PluginFeature: String { case loadPluginLibrary = "load-plugin-library" } /// A type that provides the actual plugin functions. +/// +/// Note that it's an implementation's responsibility to cache the API results as needed. +@_spi(PluginMessage) public protocol PluginProvider { /// Resolve macro type by the module name and the type name. func resolveMacro(moduleName: String, typeName: String) throws -> Macro.Type @@ -37,6 +43,7 @@ public protocol PluginProvider { /// Low level message connection to the plugin host. /// This encapsulates the connection and the message serialization. +@_spi(PluginMessage) public protocol MessageConnection { /// Send a message to the peer. func sendMessage(_ message: TX) throws @@ -61,49 +68,64 @@ struct HostCapability { var hasExpandMacroResult: Bool { protocolVersion >= 5 } } -/// 'CompilerPluginMessageHandler' is a type that listens to the message -/// connection and dispatches them to the actual plugin provider, then send back +/// 'CompilerPluginMessageListener' is a type that listens to the message +/// connection, delegate them to the message handler, then send back /// the response. /// /// The low level connection and the provider is injected by the client. -public class CompilerPluginMessageHandler { +@_spi(PluginMessage) +public class CompilerPluginMessageListener { /// Message channel for bidirectional communication with the plugin host. let connection: Connection - /// Object to provide actual plugin functions. - let provider: Provider - - /// Plugin host capability - var hostCapability: HostCapability + let handler: CompilerPluginMessageHandler public init(connection: Connection, provider: Provider) { self.connection = connection - self.provider = provider - self.hostCapability = HostCapability() - } -} - -extension CompilerPluginMessageHandler { - func sendMessage(_ message: PluginToHostMessage) throws { - try connection.sendMessage(message) - } - - func waitForNextMessage() throws -> HostToPluginMessage? { - try connection.waitForNextMessage(HostToPluginMessage.self) + self.handler = CompilerPluginMessageHandler(provider: provider) } /// Run the main message listener loop. /// Returns when the message connection was closed. - /// Throws an error when it failed to send/receive the message, or failed - /// to serialize/deserialize the message. - public func main() throws { - while let message = try self.waitForNextMessage() { - try handleMessage(message) + /// + /// On internal errors, such as I/O errors or JSON serialization errors, print + /// an error message and `exit(1)` + public func main() { + do { + while let message = try connection.waitForNextMessage(HostToPluginMessage.self) { + let result = handler.handleMessage(message) + try connection.sendMessage(result) + } + } catch { + // Emit a diagnostic and indicate failure to the plugin host, + // and exit with an error code. + fputs("Internal Error: \(error)\n", _stderr) + exit(1) } } +} + +/// 'CompilerPluginMessageHandler' is a type that handle a message and do the +/// corresponding operation. +@_spi(PluginMessage) +public class CompilerPluginMessageHandler { + /// Object to provide actual plugin functions. + let provider: Provider + + /// Syntax registry shared between multiple requests. + let syntaxRegistry: ParsedSyntaxRegistry + + /// Plugin host capability + var hostCapability: HostCapability + + public init(provider: Provider) { + self.provider = provider + self.syntaxRegistry = ParsedSyntaxRegistry(cacheCapacity: 16) + self.hostCapability = HostCapability() + } /// Handles a single message received from the plugin host. - fileprivate func handleMessage(_ message: HostToPluginMessage) throws { + public func handleMessage(_ message: HostToPluginMessage) -> PluginToHostMessage { switch message { case .getCapability(let hostCapability): // Remember the peer capability if provided. @@ -116,7 +138,7 @@ extension CompilerPluginMessageHandler { protocolVersion: PluginMessage.PROTOCOL_VERSION_NUMBER, features: provider.features.map({ $0.rawValue }) ) - try self.sendMessage(.getCapabilityResult(capability: capability)) + return .getCapabilityResult(capability: capability) case .expandFreestandingMacro( let macro, @@ -125,7 +147,7 @@ extension CompilerPluginMessageHandler { let expandingSyntax, let lexicalContext ): - try expandFreestandingMacro( + return expandFreestandingMacro( macro: macro, macroRole: macroRole, discriminator: discriminator, @@ -144,7 +166,7 @@ extension CompilerPluginMessageHandler { let conformanceListSyntax, let lexicalContext ): - try expandAttachedMacro( + return expandAttachedMacro( macro: macro, macroRole: macroRole, discriminator: discriminator, @@ -172,7 +194,7 @@ extension CompilerPluginMessageHandler { ) ) } - try self.sendMessage(.loadPluginLibraryResult(loaded: diags.isEmpty, diagnostics: diags)); + return .loadPluginLibraryResult(loaded: diags.isEmpty, diagnostics: diags) } } } @@ -182,13 +204,13 @@ struct UnimplementedError: Error, CustomStringConvertible { } /// Default implementation of 'PluginProvider' requirements. -public extension PluginProvider { - var features: [PluginFeature] { +extension PluginProvider { + public var features: [PluginFeature] { // No optional features by default. return [] } - func loadPluginLibrary(libraryPath: String, moduleName: String) throws { + public func loadPluginLibrary(libraryPath: String, moduleName: String) throws { // This should be unreachable. The host should not call 'loadPluginLibrary' // unless the feature is not declared. throw UnimplementedError() diff --git a/Sources/SwiftCompilerPluginMessageHandling/Diagnostics.swift b/Sources/SwiftCompilerPluginMessageHandling/Diagnostics.swift index 2b0ab4874d2..027ec68838b 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/Diagnostics.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/Diagnostics.swift @@ -10,8 +10,13 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftDiagnostics +internal import SwiftSyntax +#else import SwiftDiagnostics import SwiftSyntax +#endif /// Errors in macro handing. enum MacroExpansionError { diff --git a/Sources/SwiftCompilerPluginMessageHandling/JSON/CodingUtilities.swift b/Sources/SwiftCompilerPluginMessageHandling/JSON/CodingUtilities.swift new file mode 100644 index 00000000000..b423f7caea4 --- /dev/null +++ b/Sources/SwiftCompilerPluginMessageHandling/JSON/CodingUtilities.swift @@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +// Copied from swift-foundation + +//===----------------------------------------------------------------------===// +// Coding Path Node +//===----------------------------------------------------------------------===// + +// This construction allows overall fewer and smaller allocations as the coding path is modified. +internal enum _CodingPathNode { + case root + indirect case node(CodingKey, _CodingPathNode) + indirect case indexNode(Int, _CodingPathNode) + + var path: [any CodingKey] { + switch self { + case .root: + return [] + case let .node(key, parent): + return parent.path + [key] + case let .indexNode(index, parent): + return parent.path + [_CodingKey(index: index)] + } + } + + @inline(__always) + func appending(_ key: __owned (some CodingKey)?) -> _CodingPathNode { + if let key { + return .node(key, self) + } else { + return self + } + } + + @inline(__always) + func path(byAppending key: __owned (some CodingKey)?) -> [CodingKey] { + if let key { + return self.path + [key] + } + return self.path + } + + // Specializations for indexes, commonly used by unkeyed containers. + @inline(__always) + func appending(index: __owned Int) -> _CodingPathNode { + .indexNode(index, self) + } + + func path(byAppendingIndex index: __owned Int) -> [CodingKey] { + self.path + [_CodingKey(index: index)] + } +} + +//===----------------------------------------------------------------------===// +// Shared Key Type +//===----------------------------------------------------------------------===// + +internal enum _CodingKey: CodingKey { + case string(String) + case int(Int) + case index(Int) + + @inline(__always) + public init?(stringValue: String) { + self = .string(stringValue) + } + + @inline(__always) + public init?(intValue: Int) { + self = .int(intValue) + } + + @inline(__always) + internal init(index: Int) { + self = .index(index) + } + + var stringValue: String { + switch self { + case let .string(str): return str + case let .int(int): return "\(int)" + case let .index(index): return "Index \(index)" + } + } + + var intValue: Int? { + switch self { + case .string: return nil + case let .int(int): return int + case let .index(index): return index + } + } +} diff --git a/Sources/SwiftCompilerPluginMessageHandling/JSON/JSON.swift b/Sources/SwiftCompilerPluginMessageHandling/JSON/JSON.swift new file mode 100644 index 00000000000..a0eb47a0925 --- /dev/null +++ b/Sources/SwiftCompilerPluginMessageHandling/JSON/JSON.swift @@ -0,0 +1,24 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +@_spi(PluginMessage) +public enum JSON { + /// Encode Swift value to an UInt8 array. + public static func encode(_ value: T) throws -> [UInt8] { + try encodeToJSON(value: value) + } + + /// Decode a JSON data to a Swift value. + public static func decode(_ type: T.Type, from json: UnsafeBufferPointer) throws -> T { + try decodeFromJSON(json: json) + } +} diff --git a/Sources/SwiftCompilerPluginMessageHandling/JSON/JSONDecoding.swift b/Sources/SwiftCompilerPluginMessageHandling/JSON/JSONDecoding.swift new file mode 100644 index 00000000000..2a88935a347 --- /dev/null +++ b/Sources/SwiftCompilerPluginMessageHandling/JSON/JSONDecoding.swift @@ -0,0 +1,1353 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if swift(>=6.0) +private import _SwiftSyntaxCShims +#else +@_implementationOnly import _SwiftSyntaxCShims +#endif + +func decodeFromJSON(json: UnsafeBufferPointer) throws -> T { + let map: JSONMap + do { + map = try JSONScanner.scan(buffer: json) + } catch let err as JSONError { + throw DecodingError.dataCorrupted( + DecodingError.Context( + codingPath: [], + debugDescription: "Corrupted JSON", + underlyingError: err + ) + ) + } + return try map.withValue { value in + let decoder = JSONDecoding(value: value, codingPathNode: .root) + return try T.init(from: decoder) + } +} + +/* + JSONMap is inspired by swift-foundation's JSONMap. + + For JSON payload such as: + + ``` + {"foo": [-1.3, true], "barz": 42} + ``` + + will be scanned by 'JSONScanner' into a map like: + + ``` + == Object Marker + == Array Marker + == Simple String (a variant of String that can has no escapes and can be passed directly to a UTF-8 parser) + == Number Marker + == NULL Marker + map: [ + 0: , -- object marker + 1: 17, | `- number of *map* elements this object occupies + 2: , | --- key 1: 'foo' + 3: , | | |- pointer in the payload + 4: 3, | | `- length + 5: , | --- value 1: array + 6: 6, | | `- number of *map* elements this array occupies + 7: , | | -- arr elm 1: '-1.3' + 8: , | | | + 9: 4, | | | + 10: , | | -- arr elm 2: 'true' + 11: , | --- key 2: 'barz' + 12: , | | + 13: 4, | | + 14: | --- value 2: '42' + 15: , | | + 16: 2, | | + ] + ``` + To decode '.barz' value: + 1. Index 0 indicates it's a object. + 2. Parse a key string at index 2, which is "foo", not a match for "barz" + 3. Skip the key and the value by advancing the index by 'mapSize' of them, 3 and 6. + 4. Parse a key string at index 11, matching "barz" + 5. Parse a value number at the pointer of index 15, length at index 16 +*/ + +private struct JSONMap { + enum Descriptor: Int { + + // MARK: - Keywords; mapSize:1 [desc] + // desc: Descriptor.rawValue + + /// 'null' + case nullKeyword + /// 'true' size:1 + case trueKeyword + /// 'false' size:1 + case falseKeyword + + // MARK: - Scalar values; mapSize:3 [desc, pointer, length] + // desc: Descriptor.rawValue + // pointer: pointer to the start of the value in the source UTF-8 JSON buffer. + // length: the length of the value in the source UTF-8 JSON buffer. + + /// Integer and floating number. + case number + /// ASCII non-escaped string. + case asciiSimpleString + /// Non escaped string. + case simpleString + /// String with escape sequences. + case string + + // MARK: - Collections; mapSize: 2 + variable [desc, size, element...] + // desc: Descriptor.rawValue + // size: the map size this collection occupies. + // element * n: JSON values in this collection. For collections, sequence of key/value pairs. + + /// Object '{ ... }'. Elements are (key, value)... + case object + /// Array '[ ... ]'. + case array + } + let data: [Int] + + /// Top-level value. + func withValue(_ body: (JSONMapValue) throws -> T) rethrows -> T { + try data.withUnsafeBufferPointer { buf in + try body(JSONMapValue(data: buf.baseAddress!)) + } + } +} + +private struct JSONMapBuilder { + var mapData: [Int] + + init() { + mapData = [] + mapData.reserveCapacity(128) // 128 is good enough for most PluginMessage. + } + + /// Record .nullKeyword, .trueKeyword, or .falseKeyword. + @inline(__always) + mutating func record(_ descriptor: JSONMap.Descriptor) { + mapData.append(descriptor.rawValue) + } + + /// Record literal values i.e. numbers and strings, with a range in the source buffer. + @inline(__always) + mutating func record(_ descriptor: JSONMap.Descriptor, range: Range>) { + mapData.append(descriptor.rawValue) + mapData.append(Int(bitPattern: range.lowerBound)) + mapData.append(range.count) + } + + /// Record starting of a collection i.e. .array or .object. Must be paired with + /// closeCollection(handle:) call using the returned handle. + @inline(__always) + mutating func startCollection(_ descriptor: JSONMap.Descriptor) -> Int { + let handle = mapData.count + mapData.append(descriptor.rawValue) + mapData.append(0) // Count, this will be updated in closeCollection() + return handle + } + + /// Close the collection. Accepts a "handle" returned from startCollection(_:). + @inline(__always) + mutating func closeCollection(handle: Int) { + // 'handle': descriptor index. + // 'handle+1': counter index. + mapData[handle + 1] = mapData.count - handle + } + + func finalize() -> JSONMap { + JSONMap(data: mapData) + } +} + +private enum JSONError: Error, CustomStringConvertible { + case unexpectedEndOfFile + case unexpectedCharacter(UInt8, context: String) + + var description: String { + switch self { + case .unexpectedEndOfFile: + return "unexpected end of file" + case .unexpectedCharacter(let c, let ctxt): + let char = c < 0x80 ? String(UnicodeScalar(c)) : "0x" + String(c, radix: 16, uppercase: true) + return "unexpected character '\(char)'; \(ctxt)" + } + } +} + +private struct JSONScanner { + typealias Cursor = UnsafePointer + + let endPtr: Cursor + var ptr: Cursor + var map: JSONMapBuilder + + init(buffer: UnsafeBufferPointer) { + self.ptr = buffer.baseAddress! + self.endPtr = buffer.baseAddress! + buffer.count + self.map = JSONMapBuilder() + } + + var hasData: Bool { + ptr != endPtr + } + + @inline(__always) + mutating func skipWhitespace() { + while hasData { + switch ptr.pointee { + case UInt8(ascii: " "), UInt8(ascii: "\t"), UInt8(ascii: "\n"), UInt8(ascii: "\r"): + ptr += 1 + default: + return + } + } + } + + @inline(__always) + mutating func advance() throws -> UInt8 { + guard hasData else { + throw JSONError.unexpectedEndOfFile + } + let value = ptr.pointee + ptr += 1 + return value + } + + @inline(__always) + mutating func advance(if char: UnicodeScalar) -> Bool { + guard hasData, ptr.pointee == UInt8(ascii: char) else { + return false + } + ptr += 1 + return true + } + + @inline(__always) + mutating func advance(if range: ClosedRange) -> Bool { + guard hasData, range.contains(UnicodeScalar(ptr.pointee)) else { + return false + } + ptr += 1 + return true + } + + @inline(__always) + mutating func expect(ascii char: UnicodeScalar) throws { + guard hasData else { + throw JSONError.unexpectedEndOfFile + } + guard ptr.pointee == UInt8(ascii: char) else { + throw JSONError.unexpectedCharacter(ptr.pointee, context: "expected '\(char)'") + } + ptr += 1 + } + + mutating func scanNull() throws { + try expect(ascii: "u") + try expect(ascii: "l") + try expect(ascii: "l") + map.record(.nullKeyword) + } + + mutating func scanTrue() throws { + try expect(ascii: "r") + try expect(ascii: "u") + try expect(ascii: "e") + map.record(.trueKeyword) + } + + mutating func scanFalse() throws { + try expect(ascii: "a") + try expect(ascii: "l") + try expect(ascii: "s") + try expect(ascii: "e") + map.record(.falseKeyword) + } + + mutating func scanString(start: Cursor) throws { + ptr = start + try expect(ascii: "\"") + + var hasEscape = false + var hasNonASCII = false + while hasData && ptr.pointee != UInt8(ascii: "\"") { + // FIXME: Error for non-escaped control characters. + // FIXME: Error for invalid UTF8 sequences. + if ptr.pointee == UInt8(ascii: "\\") { + hasEscape = true + // eat '\'. Rest of the escape sequence are all ASCII. We just skip them + // ignoring how many bytes are actually for the escape sequence. For + // decoding, they are revisited in _JSONStingDecoder.decodeStringWithEscapes() + _ = try advance() + } else if ptr.pointee >= 0x80 { + hasNonASCII = true + } + _ = try advance() + } + try expect(ascii: "\"") + + let kind: JSONMap.Descriptor + if hasEscape { + kind = .string + } else if hasNonASCII { + kind = .simpleString + } else { + kind = .asciiSimpleString + } + map.record(kind, range: (start + 1)..<(ptr - 1)) + } + + mutating func scanNumber(start: Cursor) throws { + // FIXME: Error for invalid literal e.g. 'e-', '.e+' + ptr = start + _ = advance(if: "-") + while advance(if: "0"..."9") {} + if advance(if: ".") { + while advance(if: "0"..."9") {} + } + if advance(if: "e") || advance(if: "E") { + _ = advance(if: "-") || advance(if: "+") + while advance(if: "0"..."9") {} + } + map.record(.number, range: start..) throws -> JSONMap { + var scanner = JSONScanner(buffer: buffer) + try scanner.scanValue() + if scanner.hasData { + throw JSONError.unexpectedCharacter(scanner.ptr.pointee, context: "after top-level value") + } + + return scanner.map.finalize() + } +} + +/// Represents a single value in a JSONMap. +private struct JSONMapValue { + typealias Pointer = UnsafePointer + /// Pointer to an element descriptor in the map. + let data: Pointer + + @inline(__always) + var endPtr: Pointer { + data.advanced(by: mapSize) + } + + /// The size of this value data in the map. + @inline(__always) + var mapSize: Int { + switch JSONMap.Descriptor(rawValue: data[0]) { + case .nullKeyword, .trueKeyword, .falseKeyword: + return 1 + case .number, .asciiSimpleString, .simpleString, .string: + return 3 + case .array, .object: + return data[1] + case nil: + fatalError("invalid value descriptor") + } + } + + @inline(__always) + func `is`(_ kind: JSONMap.Descriptor) -> Bool { + return data[0] == kind.rawValue + } +} + +// MARK: Keyword primitives +extension JSONMapValue { + @inline(__always) + var isNull: Bool { + return self.is(.nullKeyword) + } + + @inline(__always) + func asBool() -> Bool? { + if self.is(.trueKeyword) { + return true + } + if self.is(.falseKeyword) { + return false + } + return nil + } +} + +// MARK: Scalar values +private enum _JSONStringParser { + /// Decode a non-escaped string value from the buffer. + @inline(__always) + static func decodeSimpleString(source: UnsafeBufferPointer) -> String { + if source.count <= 0 { + return "" + } + return _makeString(unsafeUninitializedCapacity: source.count) { buffer in + buffer.initialize(fromContentsOf: source) + } + } + + /// Decode a string value that includes escape sequences. + static func decodeStringWithEscapes(source: UnsafeBufferPointer) -> String? { + // JSON string with escape sequences must be== 0 2 bytes or longer. + assert(!source.isEmpty) + + // Decode 'source' UTF-8 JSON string literal into the uninitialized + // UTF-8 buffer. Upon error, return 0 and make an empty string. + let decoded = _makeString(unsafeUninitializedCapacity: source.count) { buffer in + + var cursor = source.baseAddress! + let end = cursor + source.count + var mark = cursor + + var dest = buffer.baseAddress! + + @inline(__always) func flush() { + let count = mark.distance(to: cursor) + dest.initialize(from: mark, count: count) + dest += count + } + + while cursor != end { + if cursor.pointee != UInt8(ascii: "\\") { + cursor += 1 + continue + } + + // Found an escape sequence. Flush the skipped source into the buffer. + flush() + + let hadError = decodeEscapeSequence(cursor: &cursor, end: end) { + dest.initialize(to: $0) + dest += 1 + } + guard !hadError else { return 0 } + + // Mark the position of the end of the escape sequence. + mark = cursor + } + + // Flush the remaining non-escaped characters. + flush() + + return buffer.baseAddress!.distance(to: dest) + } + + // If any error is detected, empty string is created. + return decoded.isEmpty ? nil : decoded + } + + /// Decode a JSON escape sequence, advance 'cursor' to end of the escape + /// sequence, and call 'processCodeUnit' with the decoded value. + /// Returns 'true' on error. + /// + /// - Note: We don't report detailed errors for now because we only care + /// well-formed payloads from the compiler. + private static func decodeEscapeSequence( + cursor: inout UnsafePointer, + end: UnsafePointer, + into processCodeUnit: (UInt8) -> Void + ) -> Bool { + assert(cursor.pointee == UInt8(ascii: "\\")) + guard cursor.distance(to: end) >= 2 else { return true } + + // Eat backslash and the next character. + cursor += 2 + switch cursor[-1] { + case UInt8(ascii: "\""): processCodeUnit(UInt8(ascii: "\"")) + case UInt8(ascii: "'"): processCodeUnit(UInt8(ascii: "'")) + case UInt8(ascii: "\\"): processCodeUnit(UInt8(ascii: "\\")) + case UInt8(ascii: "/"): processCodeUnit(UInt8(ascii: "/")) + case UInt8(ascii: "b"): processCodeUnit(0x08) + case UInt8(ascii: "f"): processCodeUnit(0x0C) + case UInt8(ascii: "n"): processCodeUnit(0x0A) + case UInt8(ascii: "r"): processCodeUnit(0x0D) + case UInt8(ascii: "t"): processCodeUnit(0x09) + case UInt8(ascii: "u"): + guard cursor.distance(to: end) >= 4 else { return true } + + // Parse 4 hex digits into a UTF-16 code unit. + let result: UInt16? = _JSONNumberParser.parseHexIntegerDigits( + source: UnsafeBufferPointer(start: cursor, count: 4) + ) + guard let result else { return true } + + // Transcode UTF-16 code unit to UTF-8. + // FIXME: Support surrogate pairs. + let hadError = transcode( + CollectionOfOne(result).makeIterator(), + from: UTF16.self, + to: UTF8.self, + stoppingOnError: true, + into: processCodeUnit + ) + guard !hadError else { return true } + cursor += 4 + default: + // invalid escape sequence. + return true + } + return false + } + + /// SwiftStdlib 5.3 compatibility shim for + /// 'String.init(unsafeUninitializedCapacity:initializingUTF8With:)' + private static func _makeString( + unsafeUninitializedCapacity capacity: Int, + initializingUTF8With initializer: (UnsafeMutableBufferPointer) throws -> Int + ) rethrows -> String { + if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { + return try String(unsafeUninitializedCapacity: capacity, initializingUTF8With: initializer) + } else { + let buffer = UnsafeMutableBufferPointer.allocate(capacity: capacity) + let count = try initializer(buffer) + return String(decoding: buffer[..(source: UnsafeBufferPointer) -> Integer? { + var source = source[...] + let isNegative = source.first == UInt8(ascii: "-") + if isNegative { + source = source.dropFirst() + } + var value: Integer = 0 + var overflowed: Bool = false + while let digit = source.popFirst() { + let digitValue = Integer(truncatingIfNeeded: digit &- UInt8(ascii: "0")) + guard (0...9).contains(digitValue) else { + return nil + } + (value, overflowed) = value.multipliedReportingOverflow(by: 10) + guard !overflowed else { + return nil + } + (value, overflowed) = + isNegative + ? value.subtractingReportingOverflow(digitValue) + : value.addingReportingOverflow(digitValue) + guard !overflowed else { + return nil + } + } + return value + } + + static func parseFloatingPoint(source: UnsafeBufferPointer) -> Floating? { + // Since source is not NUL terminated, we need to make a temporary storage. + // Depending on the length of the source, prepare the buffer on stack or heap, + // then call 'impl(_:)' (defined below) for the actual operation. + if source.count + 1 <= MemoryLayout.size { + var stash: UInt64 = 0 + return withUnsafeMutableBytes(of: &stash) { + $0.withMemoryRebound(to: UInt8.self, impl) + } + } else { + let stash = UnsafeMutableBufferPointer.allocate(capacity: source.count + 1) + defer { stash.deallocate() } + return impl(stash) + } + + func impl(_ stash: UnsafeMutableBufferPointer) -> Floating? { + // Create a NUL terminated string in the stash. + assert(stash.count >= source.count + 1) + let end = stash.initialize(fromContentsOf: source) + stash.initializeElement(at: end, to: 0) + + var endPtr: UnsafeMutablePointer? = nil + let value: Floating? + if Floating.self == Double.self { + value = Floating(exactly: strtod(stash.baseAddress!, &endPtr)) + } else if Floating.self == Float.self { + value = Floating(exactly: strtof(stash.baseAddress!, &endPtr)) + } else { + preconditionFailure("unsupported floating point type") + } + guard let endPtr, endPtr == stash.baseAddress! + source.count else { + return nil + } + return value + } + } + + static func parseHexIntegerDigits(source: UnsafeBufferPointer) -> Integer? { + var source = source[...] + var value: Integer = 0 + var overflowed: Bool = false + while let digit = source.popFirst() { + let digitValue: Integer + switch digit { + case UInt8(ascii: "0")...UInt8(ascii: "9"): + digitValue = Integer(truncatingIfNeeded: digit &- UInt8(ascii: "0")) + case UInt8(ascii: "a")...UInt8(ascii: "f"): + digitValue = Integer(truncatingIfNeeded: digit &- UInt8(ascii: "a") &+ 10) + case UInt8(ascii: "A")...UInt8(ascii: "F"): + digitValue = Integer(truncatingIfNeeded: digit &- UInt8(ascii: "A") &+ 10) + default: + return nil + } + (value, overflowed) = value.multipliedReportingOverflow(by: 16) + guard !overflowed else { + return nil + } + (value, overflowed) = value.addingReportingOverflow(digitValue) + guard !overflowed else { + return nil + } + } + return value + } +} + +extension JSONMapValue { + /// Get value buffer for .number, .string, and .simpleString. + @inline(__always) + func valueBuffer() -> UnsafeBufferPointer { + UnsafeBufferPointer( + start: UnsafePointer(bitPattern: data[1]), + count: data[2] + ) + } + + @inline(__always) + func asString() -> String? { + if self.is(.asciiSimpleString) || self.is(.simpleString) { + return _JSONStringParser.decodeSimpleString(source: valueBuffer()) + } + if self.is(.string) { + return _JSONStringParser.decodeStringWithEscapes(source: valueBuffer()) + } + return nil + } + + /// Returns true if this value represents a string and equals to 'str'. + /// + /// This is faster than 'value.asString() == str' because this doesn't + /// instantiate 'Swift.String' unless there are escaped characters or + /// non-ASCII characters. + func equals(to str: String) -> Bool { + if self.is(.asciiSimpleString) { + let lhs = valueBuffer() + var str = str + return str.withUTF8 { rhs in + if lhs.count != rhs.count { + return false + } + guard let lBase = lhs.baseAddress, let rBase = rhs.baseAddress else { + // If either `baseAddress` is `nil`, both are empty so returns `true`. + return true + } + return memcmp(lBase, rBase, lhs.count) == 0 + } + } + return self.asString() == str + } + + @inline(__always) + func asFloatingPoint(_: Floating.Type) -> Floating? { + return _JSONNumberParser.parseFloatingPoint(source: self.valueBuffer()) + } + + @inline(__always) + func asInteger(_: Integer.Type) -> Integer? { + // FIXME: Support 42.0 as an integer. + return _JSONNumberParser.parseInteger(source: self.valueBuffer()) + } +} + +// MARK: Collection values +extension JSONMapValue { + struct JSONArray: Collection { + let map: JSONMapValue + + var startIndex: Pointer { map.data.advanced(by: 2) } + var endIndex: Pointer { map.endPtr } + func index(after pointer: Pointer) -> Pointer { + self[pointer].endPtr + } + subscript(pointer: Pointer) -> JSONMapValue { + JSONMapValue(data: pointer) + } + } + + @inline(__always) + func asArray() -> JSONArray? { + guard self.is(.array) else { + return nil + } + return JSONArray(map: self) + } + + struct JSONObject { + let map: JSONMapValue + + struct Iterator: IteratorProtocol { + var currPtr: Pointer + let endPtr: Pointer + + @inline(__always) + init(map: JSONMapValue) { + self.currPtr = map.data.advanced(by: 2) + self.endPtr = map.endPtr + } + + mutating func next() -> (key: JSONMapValue, value: JSONMapValue)? { + guard currPtr != endPtr else { + return nil + } + let key = JSONMapValue(data: currPtr) + let val = JSONMapValue(data: key.endPtr) + currPtr = val.endPtr + return (key, val) + } + } + + @inline(__always) + func makeIterator() -> Iterator { + return Iterator(map: map) + } + + @inline(__always) + func find(_ key: String) -> JSONMapValue? { + // Linear search because, unless there are many keys, creating dictionary + // costs more for preparation. I.e. key string allocation and dictionary + // construction. + var iter = makeIterator() + while let elem = iter.next() { + if elem.key.equals(to: key) { + return elem.value + } + } + return nil + } + + @inline(__always) + func contains(key: String) -> Bool { + return find(key) != nil + } + } + + @inline(__always) + func asObject() -> JSONObject? { + guard self.is(.object) else { + return nil + } + return JSONObject(map: self) + } +} + +private struct JSONDecoding { + var value: JSONMapValue + var codingPathNode: _CodingPathNode +} + +// MARK: Pure decoding functions. +extension JSONDecoding { + @inline(__always) + private static func _checkNotNull( + _ value: JSONMapValue, + expectedType: T.Type, + for codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws { + guard !value.isNull else { + throw DecodingError.valueNotFound( + expectedType, + DecodingError.Context( + codingPath: codingPathNode.path(byAppending: additionalKey), + debugDescription: "Cannot get value of type \(expectedType) -- found null value instead" + ) + ) + } + } + + @inline(__always) + static func _unwrapOrThrow( + _ result: T?, + decoding value: JSONMapValue, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> T { + if let result = result { + return result + } + try _checkNotNull(value, expectedType: T.self, for: codingPathNode, additionalKey) + throw DecodingError.typeMismatch( + T.self, + .init( + codingPath: codingPathNode.path(byAppending: additionalKey), + debugDescription: "type mismatch" + ) + ) + } + + @inline(__always) + static func _decode( + _ value: JSONMapValue, + as _: Bool.Type, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> Bool { + try _unwrapOrThrow(value.asBool(), decoding: value, codingPathNode: codingPathNode, additionalKey) + } + + @inline(__always) + static func _decode( + _ value: JSONMapValue, + as _: String.Type, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> String { + try _unwrapOrThrow(value.asString(), decoding: value, codingPathNode: codingPathNode, additionalKey) + } + + @inline(__always) + static func _decode( + _ value: JSONMapValue, + as type: Integer.Type, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> Integer { + try _unwrapOrThrow(value.asInteger(type), decoding: value, codingPathNode: codingPathNode, additionalKey) + } + + @inline(__always) + static func _decode( + _ value: JSONMapValue, + as type: Floating.Type, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> Floating { + try _unwrapOrThrow(value.asFloatingPoint(type), decoding: value, codingPathNode: codingPathNode, additionalKey) + } + + static func _decodeGeneric( + _ value: JSONMapValue, + as type: T.Type, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> T { + let decoder = Self(value: value, codingPathNode: codingPathNode.appending(additionalKey)) + return try T.init(from: decoder) + } +} + +extension JSONDecoding: Decoder { + var codingPath: [any CodingKey] { + codingPathNode.path + } + var userInfo: [CodingUserInfoKey: Any] { [:] } + + fileprivate struct KeyedContainer { + var codingPathNode: _CodingPathNode + var mapping: JSONMapValue.JSONObject + } + + fileprivate struct UnkeyedContainer { + var codingPathNode: _CodingPathNode + var currentIndex: Int + var array: JSONMapValue.JSONArray + var _currMapIdx: JSONMapValue.JSONArray.Index + } + + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { + return try KeyedDecodingContainer( + KeyedContainer( + value: value, + codingPathNode: codingPathNode + ) + ) + } + + func unkeyedContainer() throws -> any UnkeyedDecodingContainer { + return try UnkeyedContainer( + value: value, + codingPathNode: codingPathNode + ) + } + + func singleValueContainer() throws -> any SingleValueDecodingContainer { + return self + } +} + +extension JSONDecoding: SingleValueDecodingContainer { + func decodeNil() -> Bool { + value.isNull + } + + func decode(_ type: Bool.Type) throws -> Bool { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: String.Type) throws -> String { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Double.Type) throws -> Double { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Float.Type) throws -> Float { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Int.Type) throws -> Int { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Int8.Type) throws -> Int8 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Int16.Type) throws -> Int16 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Int32.Type) throws -> Int32 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: Int64.Type) throws -> Int64 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: UInt.Type) throws -> UInt { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: UInt8.Type) throws -> UInt8 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: UInt16.Type) throws -> UInt16 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: UInt32.Type) throws -> UInt32 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: UInt64.Type) throws -> UInt64 { + try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } + + func decode(_ type: T.Type) throws -> T where T: Decodable { + try JSONDecoding._decodeGeneric(value, as: type, codingPathNode: codingPathNode, _CodingKey?.none) + } +} + +extension JSONDecoding.KeyedContainer: KeyedDecodingContainerProtocol { + var codingPath: [any CodingKey] { + codingPathNode.path + } + + var allKeys: [Key] { + var iter = mapping.makeIterator() + var keys: [Key] = [] + while let elem = iter.next() { + if let key = Key(stringValue: elem.key.asString()!) { + keys.append(key) + } + } + return keys + } + + func contains(_ key: Key) -> Bool { + return mapping.contains(key: key.stringValue) + } + + @inline(__always) + func _getOrThrow(forKey key: Key) throws -> JSONMapValue { + if let value = mapping.find(key.stringValue) { + return value + } + throw DecodingError.keyNotFound( + key, + .init( + codingPath: codingPathNode.path, + debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")." + ) + ) + } + + func decodeNil(forKey key: Key) throws -> Bool { + try _getOrThrow(forKey: key).isNull + } + + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: String.Type, forKey key: Key) throws -> String { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { + try JSONDecoding._decode(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func decode(_ type: T.Type, forKey key: Key) throws -> T { + try JSONDecoding._decodeGeneric(_getOrThrow(forKey: key), as: type, codingPathNode: codingPathNode, key) + } + + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: Key + ) throws -> KeyedDecodingContainer { + return try KeyedDecodingContainer( + JSONDecoding.KeyedContainer( + value: try _getOrThrow(forKey: key), + codingPathNode: codingPathNode.appending(key) + ) + ) + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> any UnkeyedDecodingContainer { + return try JSONDecoding.UnkeyedContainer( + value: _getOrThrow(forKey: key), + codingPathNode: codingPathNode.appending(key) + ) + } + + func superDecoder() throws -> any Decoder { + fatalError("unimplemented") + } + + func superDecoder(forKey key: Key) throws -> any Decoder { + fatalError("unimplemented") + } + + init(value: JSONMapValue, codingPathNode: _CodingPathNode) throws { + guard let mapping = value.asObject() else { + throw DecodingError.typeMismatch( + [String: Any].self, + .init( + codingPath: codingPathNode.path, + debugDescription: "not an object" + ) + ) + } + self.codingPathNode = codingPathNode + self.mapping = mapping + } +} + +extension JSONDecoding.UnkeyedContainer: UnkeyedDecodingContainer { + var codingPath: [any CodingKey] { + codingPathNode.path + } + + var count: Int? { + array.count + } + + var isAtEnd: Bool { + _currMapIdx == array.endIndex + } + + @inline(__always) + mutating func advanceToNextValue() { + _currMapIdx = array.index(after: _currMapIdx) + currentIndex += 1 + } + + @inline(__always) + mutating func _getOrThrow() throws -> (index: _CodingKey, value: JSONMapValue) { + let idx = currentIndex + guard !isAtEnd else { + throw DecodingError.valueNotFound( + Any.self, + .init( + codingPath: codingPathNode.path(byAppendingIndex: idx), + debugDescription: "Unkeyed container is at end" + ) + ) + } + let value = array[_currMapIdx] + advanceToNextValue() + return (_CodingKey(index: idx), value) + } + + @inline(__always) + mutating func _decodeInteger(_ type: Integer.Type) throws -> Integer { + let (idx, value) = try _getOrThrow() + return try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, idx) + } + + @inline(__always) + mutating func _decodeFloating(_ type: Floating.Type) throws -> Floating { + let (idx, value) = try _getOrThrow() + return try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, idx) + } + + mutating func decodeNil() throws -> Bool { + if !isAtEnd && array[_currMapIdx].isNull { + advanceToNextValue() + return true + } + // The protocol states: + // If the value is not null, does not increment currentIndex. + return false + } + + mutating func decode(_ type: Bool.Type) throws -> Bool { + let (idx, value) = try _getOrThrow() + return try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, idx) + } + + mutating func decode(_ type: String.Type) throws -> String { + let (idx, value) = try _getOrThrow() + return try JSONDecoding._decode(value, as: type, codingPathNode: codingPathNode, idx) + } + + mutating func decode(_ type: Double.Type) throws -> Double { + try _decodeFloating(type) + } + + mutating func decode(_ type: Float.Type) throws -> Float { + try _decodeFloating(type) + } + + mutating func decode(_ type: Int.Type) throws -> Int { + try _decodeInteger(type) + } + + mutating func decode(_ type: Int8.Type) throws -> Int8 { + try _decodeInteger(type) + } + + mutating func decode(_ type: Int16.Type) throws -> Int16 { + try _decodeInteger(type) + } + + mutating func decode(_ type: Int32.Type) throws -> Int32 { + try _decodeInteger(type) + } + + mutating func decode(_ type: Int64.Type) throws -> Int64 { + try _decodeInteger(type) + } + + mutating func decode(_ type: UInt.Type) throws -> UInt { + try _decodeInteger(type) + } + + mutating func decode(_ type: UInt8.Type) throws -> UInt8 { + try _decodeInteger(type) + } + + mutating func decode(_ type: UInt16.Type) throws -> UInt16 { + try _decodeInteger(type) + } + + mutating func decode(_ type: UInt32.Type) throws -> UInt32 { + try _decodeInteger(type) + } + + mutating func decode(_ type: UInt64.Type) throws -> UInt64 { + try _decodeInteger(type) + } + + mutating func decode(_ type: T.Type) throws -> T where T: Decodable { + let (idx, value) = try _getOrThrow() + return try JSONDecoding._decodeGeneric(value, as: type, codingPathNode: codingPathNode, idx) + } + + mutating func nestedContainer( + keyedBy keyType: NestedKey.Type + ) throws -> KeyedDecodingContainer { + let (idx, value) = try _getOrThrow() + return try KeyedDecodingContainer( + JSONDecoding.KeyedContainer( + value: value, + codingPathNode: codingPathNode.appending(idx) + ) + ) + } + + mutating func nestedUnkeyedContainer() throws -> any UnkeyedDecodingContainer { + let (idx, value) = try _getOrThrow() + return try JSONDecoding.UnkeyedContainer( + value: value, + codingPathNode: codingPathNode.appending(idx) + ) + } + + mutating func superDecoder() throws -> any Decoder { + fatalError("unimplemented") + } + + init(value: JSONMapValue, codingPathNode: _CodingPathNode) throws { + guard let array = value.asArray() else { + throw DecodingError.typeMismatch( + [Any].self, + .init( + codingPath: codingPathNode.path, + debugDescription: "not an array" + ) + ) + } + self.codingPathNode = codingPathNode + self.currentIndex = 0 + self.array = array + self._currMapIdx = array.startIndex + } +} + +// Compatibility shim for SE-0370 +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + fileprivate func initialize( + fromContentsOf source: some Collection + ) -> Index { + let count = source.withContiguousStorageIfAvailable { + guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { + return 0 + } + precondition( + $0.count <= self.count, + "buffer cannot contain every element from source." + ) + baseAddress?.initialize(from: sourceAddress, count: $0.count) + return $0.count + } + if let count { + return startIndex.advanced(by: count) + } + + var (iterator, copied) = self.initialize(from: source) + precondition( + iterator.next() == nil, + "buffer cannot contain every element from source." + ) + return startIndex.advanced(by: copied) + } + + fileprivate func initializeElement(at index: Index, to value: Element) { + precondition(startIndex <= index && index < endIndex) + let p = baseAddress!.advanced(by: index) + p.initialize(to: value) + } +} +#endif diff --git a/Sources/SwiftCompilerPluginMessageHandling/JSON/JSONEncoding.swift b/Sources/SwiftCompilerPluginMessageHandling/JSON/JSONEncoding.swift new file mode 100644 index 00000000000..319f9384b45 --- /dev/null +++ b/Sources/SwiftCompilerPluginMessageHandling/JSON/JSONEncoding.swift @@ -0,0 +1,622 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +func encodeToJSON(value: some Encodable) throws -> [UInt8] { + let encoder = JSONEncoding() + try value.encode(to: encoder) + return JSONWriter.serialize(encoder.reference ?? .null) +} + +/// Intermediate representation for serializing JSON structure. +private final class JSONReference { + enum Backing { + case null + case trueKeyword + case falseKeyword + case string(String) + case number(String) + case array([JSONReference]) + case object([String: JSONReference]) + } + + var backing: Backing + + init(backing: Backing) { + self.backing = backing + } + + var count: Int { + switch backing { + case .array(let array): return array.count + case .object(let dict): return dict.count + default: preconditionFailure("Count does not apply to scalar") + } + } + + func set(key: String, value: JSONReference) { + guard case .object(var dict) = backing else { + preconditionFailure() + } + backing = .null // Ensure 'dict' uniquely referenced. + dict[key] = value + backing = .object(dict) + } + + func append(_ value: JSONReference) { + guard case .array(var arr) = backing else { + preconditionFailure() + } + backing = .null // Ensure 'arr' uniquely referenced. + arr.append(value) + backing = .array(arr) + } + + #if swift(>=6) + // nonisolated(unsafe) is fine for these properties because they represent primitives + // that are never modified. + nonisolated(unsafe) static let null: JSONReference = .init(backing: .null) + nonisolated(unsafe) static let trueKeyword: JSONReference = .init(backing: .trueKeyword) + nonisolated(unsafe) static let falseKeyword: JSONReference = .init(backing: .falseKeyword) + #else + static let null: JSONReference = .init(backing: .null) + static let trueKeyword: JSONReference = .init(backing: .trueKeyword) + static let falseKeyword: JSONReference = .init(backing: .falseKeyword) + #endif + + @inline(__always) + static func newArray() -> JSONReference { + .init(backing: .array([])) + } + + @inline(__always) + static func newObject() -> JSONReference { + .init(backing: .object([:])) + } + + @inline(__always) + static func string(_ str: String) -> JSONReference { + .init(backing: .string(str)) + } + + @inline(__always) + static func number(_ integer: some BinaryInteger & LosslessStringConvertible) -> JSONReference { + .init(backing: .number(String(integer))) + } + + @inline(__always) + static func number(_ floating: some BinaryFloatingPoint & LosslessStringConvertible) -> JSONReference { + // FIXME: Error for NaN, Inf. + .init(backing: .number(String(floating))) + } +} + +/// Serialize JSONReference to [UInt8] data. +private struct JSONWriter { + var data: [UInt8] + init() { + data = [] + } + + mutating func write(_ ascii: UInt8) { + data.append(ascii) + } + + mutating func write(ascii: UnicodeScalar) { + data.append(UInt8(ascii: ascii)) + } + + mutating func write(string: StaticString) { + string.withUTF8Buffer { buffer in + data.append(contentsOf: buffer) + } + } + + mutating func write(utf8: some Collection) { + data.append(contentsOf: utf8) + } + + mutating func serialize(value: JSONReference) { + switch value.backing { + case .null: + write(string: "null") + case .trueKeyword: + write(string: "true") + case .falseKeyword: + write(string: "false") + case .string(let string): + serialize(string: string) + case .number(var string): + string.withUTF8 { + write(utf8: $0) + } + case .array(let array): + serialize(array: array) + case .object(let dictionary): + serialize(object: dictionary) + } + } + + mutating func serialize(string: String) { + var string = string + write(ascii: "\"") + string.withUTF8 { utf8 in + let start = utf8.baseAddress! + let end = start + utf8.count + var mark = start + + for cursor in start..> shift) & 0xF + write(d < 10 ? (_0 + d) : (_A + d - 10)) + } + default: + // Accumulate this byte. + break + } + } + + // Append accumulated bytes. + if end > mark { + write(utf8: UnsafeBufferPointer(start: mark, count: end - mark)) + } + } + write(ascii: "\"") + } + + mutating func serialize(array: [JSONReference]) { + write(ascii: "[") + var first = true + for elem in array { + if first { + first = false + } else { + write(ascii: ",") + } + serialize(value: elem) + } + write(ascii: "]") + } + + mutating func serialize(object: [String: JSONReference]) { + write(ascii: "{") + var first = true + for key in object.keys.sorted() { + if first { + first = false + } else { + write(ascii: ",") + } + serialize(string: key) + write(ascii: ":") + serialize(value: object[key]!) + } + write(ascii: "}") + } + + static func serialize(_ value: JSONReference) -> [UInt8] { + var writer = JSONWriter() + writer.serialize(value: value) + return writer.data + } +} + +private class JSONEncoding { + /// Storage of the encoded data. + var reference: JSONReference? + + var codingPathNode: _CodingPathNode + + init(codingPathNode: _CodingPathNode = .root) { + self.reference = nil + self.codingPathNode = codingPathNode + } +} + +// MARK: Pure encoding functions. +extension JSONEncoding { + func _encode(_ value: Bool) -> JSONReference { + value ? .trueKeyword : .falseKeyword + } + + func _encode(_ value: some BinaryFloatingPoint & LosslessStringConvertible) -> JSONReference { + .number(value) + } + + func _encode(_ value: some BinaryInteger & LosslessStringConvertible) -> JSONReference { + .number(value) + } + + func _encode(_ value: String) -> JSONReference { + .string(value) + } + + func _encodeGeneric( + _ value: T, + codingPathNode: _CodingPathNode, + _ additionalKey: (some CodingKey)? + ) throws -> JSONReference { + // Temporarily reset the state and perform the encoding. + let old = (self.reference, self.codingPathNode) + defer { (self.reference, self.codingPathNode) = old } + + self.reference = nil + self.codingPathNode = codingPathNode.appending(additionalKey) + + try value.encode(to: self) + guard let result = self.reference else { + throw EncodingError.invalidValue( + T.self, + .init( + codingPath: self.codingPathNode.path, + debugDescription: "nothing was encoded" + ) + ) + } + return result + } +} + +// MARK: Encoder conformance. +extension JSONEncoding: Encoder { + var codingPath: [any CodingKey] { + codingPathNode.path + } + + var userInfo: [CodingUserInfoKey: Any] { [:] } + + fileprivate struct KeyedContainer { + var encoder: JSONEncoding + var reference: JSONReference + var codingPathNode: _CodingPathNode + } + + fileprivate struct UnkeyedContainer { + var encoder: JSONEncoding + var reference: JSONReference + var codingPathNode: _CodingPathNode + } + + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { + reference = .newObject() + return KeyedEncodingContainer( + KeyedContainer( + encoder: self, + reference: reference!, + codingPathNode: codingPathNode + ) + ) + } + + func unkeyedContainer() -> any UnkeyedEncodingContainer { + reference = .newArray() + return UnkeyedContainer( + encoder: self, + reference: reference!, + codingPathNode: codingPathNode + ) + } + + func singleValueContainer() -> any SingleValueEncodingContainer { + return self + } +} + +extension JSONEncoding: SingleValueEncodingContainer { + func encodeNil() throws { + reference = .null + } + + func encode(_ value: Bool) throws { + reference = _encode(value) + } + + func encode(_ value: String) throws { + reference = _encode(value) + } + + func encode(_ value: Double) throws { + reference = _encode(value) + } + + func encode(_ value: Float) throws { + reference = _encode(value) + } + + func encode(_ value: Int) throws { + reference = _encode(value) + } + + func encode(_ value: Int8) throws { + reference = _encode(value) + } + + func encode(_ value: Int16) throws { + reference = _encode(value) + } + + func encode(_ value: Int32) throws { + reference = _encode(value) + } + + func encode(_ value: Int64) throws { + reference = _encode(value) + } + + func encode(_ value: UInt) throws { + reference = _encode(value) + } + + func encode(_ value: UInt8) throws { + reference = _encode(value) + } + + func encode(_ value: UInt16) throws { + reference = _encode(value) + } + + func encode(_ value: UInt32) throws { + reference = _encode(value) + } + + func encode(_ value: UInt64) throws { + reference = _encode(value) + } + + func encode(_ value: T) throws { + reference = try _encodeGeneric(value, codingPathNode: codingPathNode, (_CodingKey)?.none) + } +} + +extension JSONEncoding.KeyedContainer: KeyedEncodingContainerProtocol { + var codingPath: [any CodingKey] { + codingPathNode.path + } + + func _set(key: Key, value: JSONReference) { + reference.set(key: key.stringValue, value: value) + } + + mutating func encodeNil(forKey key: Key) throws { + _set(key: key, value: .null) + } + + mutating func encode(_ value: Bool, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: String, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Double, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Float, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Int, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Int8, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Int16, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Int32, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: Int64, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: UInt, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: UInt8, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: UInt16, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: UInt32, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: UInt64, forKey key: Key) throws { + _set(key: key, value: encoder._encode(value)) + } + + mutating func encode(_ value: T, forKey key: Key) throws { + _set(key: key, value: try encoder._encodeGeneric(value, codingPathNode: codingPathNode, key)) + } + + mutating func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: Key + ) -> KeyedEncodingContainer { + let ref: JSONReference = .newObject() + _set(key: key, value: ref) + return KeyedEncodingContainer( + JSONEncoding.KeyedContainer( + encoder: encoder, + reference: ref, + codingPathNode: codingPathNode.appending(key) + ) + ) + } + + mutating func nestedUnkeyedContainer(forKey key: Key) -> any UnkeyedEncodingContainer { + let ref: JSONReference = .newArray() + _set(key: key, value: ref) + return JSONEncoding.UnkeyedContainer( + encoder: encoder, + reference: ref, + codingPathNode: codingPathNode.appending(key) + ) + } + + mutating func superEncoder() -> any Encoder { + fatalError("unimplemented") + } + + mutating func superEncoder(forKey key: Key) -> any Encoder { + fatalError("unimplemented") + } +} + +extension JSONEncoding.UnkeyedContainer: UnkeyedEncodingContainer { + var codingPath: [any CodingKey] { + codingPathNode.path + } + + var count: Int { + reference.count + } + + func encodeNil() throws { + reference.append(.null) + } + + func encode(_ value: Bool) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: String) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Double) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Float) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Int) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Int8) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Int16) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Int32) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: Int64) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: UInt) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: UInt8) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: UInt16) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: UInt32) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: UInt64) throws { + reference.append(encoder._encode(value)) + } + + func encode(_ value: T) throws where T: Encodable { + let idx = reference.count + let ref = try encoder._encodeGeneric(value, codingPathNode: codingPathNode, _CodingKey.index(idx)) + reference.append(ref) + } + + func nestedContainer( + keyedBy keyType: NestedKey.Type + ) -> KeyedEncodingContainer { + let ref: JSONReference = .newObject() + let idx = count + reference.append(ref) + return KeyedEncodingContainer( + JSONEncoding.KeyedContainer( + encoder: encoder, + reference: ref, + codingPathNode: codingPathNode.appending(index: idx) + ) + ) + } + + func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer { + let ref: JSONReference = .newObject() + let idx = count + reference.append(ref) + return JSONEncoding.UnkeyedContainer( + encoder: encoder, + reference: ref, + codingPathNode: codingPathNode.appending(index: idx) + ) + } + + func superEncoder() -> any Encoder { + fatalError("unimplmented") + } +} diff --git a/Sources/SwiftCompilerPluginMessageHandling/LRUCache.swift b/Sources/SwiftCompilerPluginMessageHandling/LRUCache.swift new file mode 100644 index 00000000000..aa67204fd5a --- /dev/null +++ b/Sources/SwiftCompilerPluginMessageHandling/LRUCache.swift @@ -0,0 +1,116 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +/// Simple LRU cache. +@_spi(Testing) +public class LRUCache { + private class _Node { + unowned var prev: _Node? = nil + unowned var next: _Node? = nil + + let key: Key + var value: Value + + init(key: Key, value: Value) { + self.key = key + self.value = value + } + } + + private var table: [Key: _Node] + + // Double linked list + private unowned var head: _Node? + private unowned var tail: _Node? + + public let capacity: Int + + public init(capacity: Int) { + self.table = [:] + self.head = nil + self.tail = nil + self.capacity = capacity + } + + public var count: Int { + return table.count + } + + public subscript(key: Key) -> Value? { + get { + guard let node = table[key] else { + return nil + } + moveToHead(node: node) + return node.value + } + + set { + switch (table[key], newValue) { + case let (nil, newValue?): // create. + self.ensureCapacityForNewValue() + let node = _Node(key: key, value: newValue) + addToHead(node: node) + table[key] = node + + case let (node?, newValue?): // update. + moveToHead(node: node) + node.value = newValue + + case let (node?, nil): // delete. + remove(node: node) + table[key] = nil + + case (nil, nil): // no-op. + break + } + } + } + + private func ensureCapacityForNewValue() { + while self.table.count >= self.capacity, let tail = self.tail { + remove(node: tail) + table[tail.key] = nil + } + } + + private func moveToHead(node: _Node) { + if node === self.head { + return + } + remove(node: node) + addToHead(node: node) + } + + private func addToHead(node: _Node) { + node.next = self.head + node.next?.prev = node + node.prev = nil + self.head = node + if self.tail == nil { + self.tail = node + } + } + + private func remove(node: _Node) { + node.next?.prev = node.prev + node.prev?.next = node.next + if node === self.head { + self.head = node.next + } + if node === self.tail { + self.tail = node.prev + } + node.prev = nil + node.next = nil + } +} diff --git a/Sources/SwiftCompilerPluginMessageHandling/Macros.swift b/Sources/SwiftCompilerPluginMessageHandling/Macros.swift index 4687cbb00ed..c92a36fde5f 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/Macros.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/Macros.swift @@ -10,12 +10,21 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftBasicFormat +internal import SwiftDiagnostics +internal import SwiftOperators +internal import SwiftSyntax +@_spi(MacroExpansion) @_spi(ExperimentalLanguageFeature) internal import SwiftSyntaxMacroExpansion +@_spi(ExperimentalLanguageFeature) internal import SwiftSyntaxMacros +#else import SwiftBasicFormat import SwiftDiagnostics import SwiftOperators import SwiftSyntax -@_spi(ExperimentalLanguageFeature) import SwiftSyntaxMacroExpansion +@_spi(MacroExpansion) @_spi(ExperimentalLanguageFeature) import SwiftSyntaxMacroExpansion @_spi(ExperimentalLanguageFeature) import SwiftSyntaxMacros +#endif extension CompilerPluginMessageHandler { /// Get concrete macro type from a pair of module name and type name. @@ -46,8 +55,8 @@ extension CompilerPluginMessageHandler { discriminator: String, expandingSyntax: PluginMessage.Syntax, lexicalContext: [PluginMessage.Syntax]? - ) throws { - let sourceManager = SourceManager() + ) -> PluginToHostMessage { + let sourceManager = SourceManager(syntaxRegistry: syntaxRegistry) let syntax = sourceManager.add(expandingSyntax, foldingWith: .standardOperators) let context = PluginMacroExpansionContext( @@ -96,7 +105,7 @@ extension CompilerPluginMessageHandler { // TODO: Remove this when all compilers have 'hasExpandMacroResult'. response = .expandFreestandingMacroResult(expandedSource: expandedSource, diagnostics: diagnostics) } - try self.sendMessage(response) + return response } /// Expand `@attached(XXX)` macros. @@ -110,8 +119,8 @@ extension CompilerPluginMessageHandler { extendedTypeSyntax: PluginMessage.Syntax?, conformanceListSyntax: PluginMessage.Syntax?, lexicalContext: [PluginMessage.Syntax]? - ) throws { - let sourceManager = SourceManager() + ) -> PluginToHostMessage { + let sourceManager = SourceManager(syntaxRegistry: syntaxRegistry) let attributeNode = sourceManager.add( attributeSyntax, foldingWith: .standardOperators @@ -180,7 +189,7 @@ extension CompilerPluginMessageHandler { } else { response = .expandAttachedMacroResult(expandedSources: expandedSources, diagnostics: diagnostics) } - try self.sendMessage(response) + return response } } diff --git a/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift b/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift index 469bcc56ddb..8914d159823 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/PluginMacroExpansionContext.swift @@ -10,11 +10,62 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftDiagnostics +internal import SwiftOperators +internal import SwiftParser +internal import SwiftSyntax +internal import SwiftSyntaxMacros +#else import SwiftDiagnostics import SwiftOperators import SwiftParser import SwiftSyntax import SwiftSyntaxMacros +#endif + +/// Caching parser for PluginMessage.Syntax +class ParsedSyntaxRegistry { + struct Key: Hashable { + let source: String + let kind: PluginMessage.Syntax.Kind + } + + private var storage: LRUCache + + init(cacheCapacity: Int) { + self.storage = LRUCache(capacity: cacheCapacity) + } + + private func parse(source: String, kind: PluginMessage.Syntax.Kind) -> Syntax { + var parser = Parser(source) + switch kind { + case .declaration: + return Syntax(DeclSyntax.parse(from: &parser)) + case .statement: + return Syntax(StmtSyntax.parse(from: &parser)) + case .expression: + return Syntax(ExprSyntax.parse(from: &parser)) + case .type: + return Syntax(TypeSyntax.parse(from: &parser)) + case .pattern: + return Syntax(PatternSyntax.parse(from: &parser)) + case .attribute: + return Syntax(AttributeSyntax.parse(from: &parser)) + } + } + + func get(source: String, kind: PluginMessage.Syntax.Kind) -> Syntax { + let key = Key(source: source, kind: kind) + if let cached = storage[key] { + return cached + } + + let node = parse(source: source, kind: kind) + storage[key] = node + return node + } +} /// Manages known source code combined with their filename/fileID. This can be /// used to get line/column from a syntax node in the managed source code. @@ -59,9 +110,16 @@ class SourceManager { var endUTF8Offset: Int } + /// Caching syntax parser. + private let syntaxRegistry: ParsedSyntaxRegistry + /// Syntax added by `add(_:)` method. Keyed by the `id` of the node. private var knownSourceSyntax: [Syntax.ID: KnownSourceSyntax] = [:] + init(syntaxRegistry: ParsedSyntaxRegistry) { + self.syntaxRegistry = syntaxRegistry + } + /// Convert syntax information to a ``Syntax`` node. The location informations /// are cached in the source manager to provide `location(of:)` et al. func add( @@ -69,22 +127,7 @@ class SourceManager { foldingWith operatorTable: OperatorTable? = nil ) -> Syntax { - var node: Syntax - var parser = Parser(syntaxInfo.source) - switch syntaxInfo.kind { - case .declaration: - node = Syntax(DeclSyntax.parse(from: &parser)) - case .statement: - node = Syntax(StmtSyntax.parse(from: &parser)) - case .expression: - node = Syntax(ExprSyntax.parse(from: &parser)) - case .type: - node = Syntax(TypeSyntax.parse(from: &parser)) - case .pattern: - node = Syntax(PatternSyntax.parse(from: &parser)) - case .attribute: - node = Syntax(AttributeSyntax.parse(from: &parser)) - } + var node = syntaxRegistry.get(source: syntaxInfo.source, kind: syntaxInfo.kind) if let operatorTable { node = operatorTable.foldAll(node, errorHandler: { _ in /*ignore*/ }) } @@ -145,7 +188,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 } @@ -162,8 +209,9 @@ class SourceManager { let localLocation = base.locationConverter.location(for: localPosition) let positionOffset = base.location.offset + // NOTE '- 1' because base.location.{line|column} are 1-based. let lineOffset = base.location.line - 1 - let columnOffset = localLocation.line == 1 ? base.location.column : 0 + let columnOffset = localLocation.line == 1 ? (base.location.column - 1) : 0 return SourceLocation( // NOTE: IUO because 'localLocation' is created by a location converter diff --git a/Sources/SwiftCompilerPluginMessageHandling/PluginMessageCompatibility.swift b/Sources/SwiftCompilerPluginMessageHandling/PluginMessageCompatibility.swift index f3a264e2647..6658bf57dd4 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/PluginMessageCompatibility.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/PluginMessageCompatibility.swift @@ -11,8 +11,8 @@ //===----------------------------------------------------------------------===// /// Old compiler might send '.declaration' as "freeStandingDeclaration". -@_spi(PluginMessage) public extension PluginMessage.MacroRole { - init(from decoder: Decoder) throws { +extension PluginMessage.MacroRole { + @_spi(PluginMessage) public init(from decoder: Decoder) throws { let stringValue = try decoder.singleValueContainer().decode(String.self) if let role = Self(rawValue: stringValue) { self = role diff --git a/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift b/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift index be7d34fc421..aeb8e9bd9ae 100644 --- a/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift +++ b/Sources/SwiftCompilerPluginMessageHandling/PluginMessages.swift @@ -12,6 +12,7 @@ // NOTE: Types in this file should be self-contained and should not depend on any non-stdlib types. +@_spi(PluginMessage) public enum HostToPluginMessage: Codable { /// Send capability of the host, and get capability of the plugin. case getCapability( @@ -49,6 +50,7 @@ public enum HostToPluginMessage: Codable { ) } +@_spi(PluginMessage) public enum PluginToHostMessage: Codable { case getCapabilityResult( capability: PluginMessage.PluginCapability @@ -78,6 +80,7 @@ public enum PluginToHostMessage: Codable { ) } +@_spi(PluginMessage) public enum PluginMessage { public static var PROTOCOL_VERSION_NUMBER: Int { 7 } // Pass extension protocol list @@ -226,7 +229,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/SwiftCompilerPluginMessageHandling/StandardIOMessageConnection.swift b/Sources/SwiftCompilerPluginMessageHandling/StandardIOMessageConnection.swift new file mode 100644 index 00000000000..df5a10ecdd7 --- /dev/null +++ b/Sources/SwiftCompilerPluginMessageHandling/StandardIOMessageConnection.swift @@ -0,0 +1,167 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if swift(>=6.0) +private import _SwiftSyntaxCShims +#else +@_implementationOnly import _SwiftSyntaxCShims +#endif + +#if canImport(ucrt) +private let dup = _dup(_:) +private let fileno = _fileno(_:) +private let dup2 = _dup2(_:_:) +private let close = _close(_:) +private let read = _read(_:_:_:) +private let write = _write(_:_:_:) +#endif + +/// Concrete 'MessageConnection' type using Standard I/O. +/// +/// Each message is serialized to UTF-8 encoded JSON text, prefixed with a +/// 8 byte header which is the byte size of the JSON payload serialized to a +/// little-endian 64bit unsigned integer. +@_spi(PluginMessage) +public struct StandardIOMessageConnection: MessageConnection { + private let inputFileDescriptor: CInt + private let outputFileDescriptor: CInt + + public init(inputFileDescriptor: CInt, outputFileDescriptor: CInt) { + self.inputFileDescriptor = inputFileDescriptor + self.outputFileDescriptor = outputFileDescriptor + } + + /// Convenience initializer for normal executable plugins. Upon creation: + /// - Redirect `stdout` to `stderr` so that print statements from the plugin + /// are treated as plain-text output + /// - Close `stdin` so that any attempts by the plugin logic to read from + /// console result in errors instead of blocking the process + /// - Duplicate the original `stdin` and `stdout` for use as messaging + /// pipes, and are not directly used by the plugin logic + public init() throws { + // Duplicate the `stdin` file descriptor, which we will then use for + // receiving messages from the plugin host. + let inputFD = dup(fileno(_stdin)) + guard inputFD >= 0 else { + throw IOError.systemError(function: "dup(fileno(stdin))", errno: _errno) + } + + // Having duplicated the original standard-input descriptor, we close + // `stdin` so that attempts by the plugin to read console input (which + // are usually a mistake) return errors instead of blocking. + guard close(fileno(_stdin)) >= 0 else { + throw IOError.systemError(function: "close(fileno(stdin))", errno: _errno) + } + + // Duplicate the `stdout` file descriptor, which we will then use for + // sending messages to the plugin host. + let outputFD = dup(fileno(_stdout)) + guard outputFD >= 0 else { + throw IOError.systemError(function: "dup(fileno(stdout))", errno: _errno) + } + + // Having duplicated the original standard-output descriptor, redirect + // `stdout` to `stderr` so that all free-form text output goes there. + guard dup2(fileno(_stderr), fileno(_stdout)) >= 0 else { + throw IOError.systemError(function: "dup2(fileno(stderr), fileno(stdout))", errno: _errno) + } + + #if canImport(ucrt) + // Set I/O to binary mode. Avoid CRLF translation, and Ctrl+Z (0x1A) as EOF. + _ = _setmode(inputFD, _O_BINARY) + _ = _setmode(outputFD, _O_BINARY) + #endif + + self.init(inputFileDescriptor: inputFD, outputFileDescriptor: outputFD) + } + + /// Write the buffer to the file descriptor. Throws an error on failure. + private func _write(contentsOf buffer: UnsafeRawBufferPointer) throws { + guard var ptr = buffer.baseAddress else { return } + let endPtr = ptr.advanced(by: buffer.count) + while ptr != endPtr { + switch write(outputFileDescriptor, ptr, numericCast(endPtr - ptr)) { + case -1: throw IOError.systemError(function: "write(_:_:_:)", errno: _errno) + case 0: throw IOError.systemError(function: "write", errno: 0) /* unreachable */ + case let n: ptr += Int(n) + } + } + } + + /// Fill the buffer from the file descriptor. Throws an error on failure. + /// If the file descriptor reached the end-of-file before filling up the entire + /// buffer, throws IOError.readReachedEndOfInput + private func _read(into buffer: UnsafeMutableRawBufferPointer) throws { + guard var ptr = buffer.baseAddress else { return } + let endPtr = ptr.advanced(by: buffer.count) + while ptr != endPtr { + switch read(inputFileDescriptor, ptr, numericCast(endPtr - ptr)) { + case -1: throw IOError.systemError(function: "read(_:_:_:)", errno: _errno) + case 0: throw IOError.readReachedEndOfInput + case let n: ptr += Int(n) + } + } + } + + public func sendMessage(_ message: TX) throws { + // Encode the message as JSON. + let payload = try JSON.encode(message) + + // Write the header (a 64-bit length field in little endian byte order). + let count = payload.count + var header = UInt64(count).littleEndian + try withUnsafeBytes(of: &header) { try _write(contentsOf: $0) } + + // Write the JSON payload. + try payload.withUnsafeBytes { try _write(contentsOf: $0) } + } + + public func waitForNextMessage(_ type: RX.Type) throws -> RX? { + // Read the header (a 64-bit length field in little endian byte order). + var header: UInt64 = 0 + do { + try withUnsafeMutableBytes(of: &header) { try _read(into: $0) } + } catch IOError.readReachedEndOfInput { + // Connection closed. + return nil + } + + // Read the JSON payload. + let count = Int(UInt64(littleEndian: header)) + let data = UnsafeMutableRawBufferPointer.allocate(byteCount: count, alignment: 1) + defer { data.deallocate() } + try _read(into: data) + + // Decode and return the message. + return try JSON.decode(type, from: UnsafeBufferPointer(data.bindMemory(to: UInt8.self))) + } +} + +private enum IOError: Error, CustomStringConvertible { + case readReachedEndOfInput + case systemError(function: String, errno: CInt) + + var description: String { + switch self { + case .readReachedEndOfInput: + return "read(2) reached end-of-file" + case .systemError(let function, let errno): + return "\(function) failed: \(describe(errno: errno))" + } + } +} + +// Private function to construct an error message from an `errno` code. +private func describe(errno: CInt) -> String { + if let cStr = strerror(errno) { return String(cString: cStr) } + return String(describing: errno) +} 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..4acfcf7527c 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 @@ -266,11 +268,13 @@ public struct DiagnosticsFormatter { // line numbers should be right aligned let lineNumberString = String(lineNumber) let leadingSpaces = String(repeating: " ", count: maxNumberOfDigits - lineNumberString.count) - let linePrefix = "\(leadingSpaces)\(diagnosticDecorator.decorateBufferOutline("\(lineNumberString) │")) " + let linePrefix = "\(leadingSpaces)\(diagnosticDecorator.decorateBufferOutline("\(lineNumberString) |")) " // 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,19 +311,23 @@ 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.. 0 { - boxSuffix = diagnosticDecorator.decorateBufferOutline(String(repeating: "─", count: extraLengthNeeded)) + boxSuffix = diagnosticDecorator.decorateBufferOutline(String(repeating: "-", count: extraLengthNeeded)) } else { boxSuffix = "" } - prefixString = diagnosticDecorator.decorateBufferOutline(padding + "╭─── ") + sourceFile.displayName + " " + boxSuffix + "\n" + prefixString = + diagnosticDecorator.decorateBufferOutline(padding + "+--- ") + sourceFile.displayName + " " + boxSuffix + "\n" suffixString = - diagnosticDecorator.decorateBufferOutline(padding + "╰───" + String(repeating: "─", count: sourceFile.displayName.count + 2)) + boxSuffix + "\n" + diagnosticDecorator.decorateBufferOutline( + padding + "+---" + String(repeating: "-", count: sourceFile.displayName.count + 2) + ) + boxSuffix + "\n" } // Render the buffer. diff --git a/Sources/SwiftIDEUtils/DeclNameLocation.swift b/Sources/SwiftIDEUtils/DeclNameLocation.swift index c1475522b16..b7c5c886755 100644 --- a/Sources/SwiftIDEUtils/DeclNameLocation.swift +++ b/Sources/SwiftIDEUtils/DeclNameLocation.swift @@ -102,6 +102,12 @@ public struct DeclNameLocation: Equatable { /// The parameter of a function declaration, like `func foo(a b: Int)` case parameters([Argument]) + /// An enum case declaration like `case myCase(label: String)`. + /// + /// For enum case parameters the argument label is removed when set to empty instead of being changed to eg. + /// `myCase(_ label: String)` + case enumCaseParameters([Argument]) + /// Same as `param` but the parameters can't be collapsed if they are the same. This is the case for subscript /// declarations. /// @@ -117,9 +123,14 @@ public struct DeclNameLocation: Equatable { case .noArguments: return .noArguments case .call(let arguments, firstTrailingClosureIndex: let firstTrailingClosureIndex): - return .call(arguments.map { $0.advanced(by: utf8Offset) }, firstTrailingClosureIndex: firstTrailingClosureIndex) + return .call( + arguments.map { $0.advanced(by: utf8Offset) }, + firstTrailingClosureIndex: firstTrailingClosureIndex + ) case .parameters(let parameters): return .parameters(parameters.map { $0.advanced(by: utf8Offset) }) + case .enumCaseParameters(let parameters): + return .enumCaseParameters(parameters.map { $0.advanced(by: utf8Offset) }) case .noncollapsibleParameters(let parameters): return .noncollapsibleParameters(parameters.map { $0.advanced(by: utf8Offset) }) case .selector(let arguments): diff --git a/Sources/SwiftIDEUtils/FixItApplier.swift b/Sources/SwiftIDEUtils/FixItApplier.swift index e9569ebbf82..650803ef301 100644 --- a/Sources/SwiftIDEUtils/FixItApplier.swift +++ b/Sources/SwiftIDEUtils/FixItApplier.swift @@ -77,8 +77,12 @@ public enum FixItApplier { // If the remaining edit starts after or at the end of the edit that we just applied, // shift it by the current edit's difference in length. if edit.endUtf8Offset <= remainingEdit.startUtf8Offset { - let startPosition = AbsolutePosition(utf8Offset: remainingEdit.startUtf8Offset - edit.replacementRange.count + edit.replacementLength) - let endPosition = AbsolutePosition(utf8Offset: remainingEdit.endUtf8Offset - edit.replacementRange.count + edit.replacementLength) + let startPosition = AbsolutePosition( + utf8Offset: remainingEdit.startUtf8Offset - edit.replacementRange.count + edit.replacementLength + ) + let endPosition = AbsolutePosition( + utf8Offset: remainingEdit.endUtf8Offset - edit.replacementRange.count + edit.replacementLength + ) return SourceEdit(range: startPosition.., 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 @@ -99,6 +102,21 @@ public class NameMatcher: SyntaxAnyVisitor { return nil } + /// Finds the first position to resolve that is in the leading or trailing trivia of this token. + /// + /// If one is found, also returns the range of the trivia in which the position was found. + private func firstPositionToResolve( + inTriviaOf token: TokenSyntax + ) -> (position: AbsolutePosition, triviaRange: Range)? { + if let position = firstPositionToResolve(in: token.leadingTriviaRange) { + return (position, token.leadingTriviaRange) + } + if let position = firstPositionToResolve(in: token.trailingTriviaRange) { + return (position, token.trailingTriviaRange) + } + return nil + } + // MARK: - addResolvedLocIfRequested overloads /// If a position should be resolved at at the start of `baseNameRange`, create a new `DeclNameLocation` to @@ -172,7 +190,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 +220,25 @@ 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, triviaRange) = firstPositionToResolve(inTriviaOf: token) { // 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 triviaRangeEndOffsetInToken = triviaRange.upperBound.utf8Offset - token.position.utf8Offset + let commentTree = token.syntaxTextBytes[positionOffsetInToken.. 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 @@ -286,7 +312,7 @@ public class NameMatcher: SyntaxAnyVisitor { return .unlabeled(argument: Syntax(argument.secondName) ?? Syntax(argument.colon) ?? Syntax(argument.type)) } } - addResolvedLocIfRequested(baseName: node.name, argumentLabels: .parameters(argumentLabels)) + addResolvedLocIfRequested(baseName: node.name, argumentLabels: .enumCaseParameters(argumentLabels)) } return .visitChildren } @@ -381,7 +407,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/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift b/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift index 90a3bcf7fd7..b51140d8dcb 100644 --- a/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift +++ b/Sources/SwiftIDEUtils/SwiftIDEUtilsCompatibility.swift @@ -13,35 +13,35 @@ // This file provides compatiblity aliases to keep dependents of SwiftSyntax building. // All users of the declarations in this file should transition away from them ASAP. -public extension SyntaxClassification { +extension SyntaxClassification { /// A `#` keyword like `#warning`. @available(*, deprecated, renamed: "ifConfigDirective") - static var poundDirective: SyntaxClassification { + public static var poundDirective: SyntaxClassification { return .ifConfigDirective } @available(*, deprecated, renamed: "ifConfigDirective") - static var buildConfigId: SyntaxClassification { + public static var buildConfigId: SyntaxClassification { return .ifConfigDirective } @available(*, deprecated, message: "String interpolation anchors are now classified as .none") - static var stringInterpolationAnchor: SyntaxClassification { + public static var stringInterpolationAnchor: SyntaxClassification { return .none } @available(*, deprecated, renamed: "type") - static var typeIdentifier: SyntaxClassification { + public static var typeIdentifier: SyntaxClassification { return .type } @available(*, deprecated, renamed: "operator") - static var operatorIdentifier: SyntaxClassification { + public static var operatorIdentifier: SyntaxClassification { return .operator } @available(*, deprecated, renamed: "floatLiteral") - static var floatingLiteral: SyntaxClassification { + public static var floatingLiteral: SyntaxClassification { return .floatLiteral } } diff --git a/Sources/SwiftIDEUtils/Syntax+Classifications.swift b/Sources/SwiftIDEUtils/Syntax+Classifications.swift index 3c094975f7c..5bcc181e15e 100644 --- a/Sources/SwiftIDEUtils/Syntax+Classifications.swift +++ b/Sources/SwiftIDEUtils/Syntax+Classifications.swift @@ -16,7 +16,7 @@ public import SwiftSyntax import SwiftSyntax #endif -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Sequence of ``SyntaxClassifiedRange``s for this syntax node. /// @@ -24,7 +24,7 @@ public extension SyntaxProtocol { /// text of the node. The ranges may also span multiple tokens, if multiple /// consecutive tokens would have the same classification then a single classified /// range is provided for all of them. - var classifications: SyntaxClassifications { + public var classifications: SyntaxClassifications { let fullRange = ByteSourceRange(offset: 0, length: totalLength.utf8Length) return SyntaxClassifications(_syntaxNode, in: fullRange) } @@ -43,7 +43,7 @@ public extension SyntaxProtocol { /// - Parameters: /// - in: The relative byte range to pull ``SyntaxClassifiedRange``s from. /// - Returns: Sequence of ``SyntaxClassifiedRange``s. - func classifications(in range: ByteSourceRange) -> SyntaxClassifications { + public func classifications(in range: ByteSourceRange) -> SyntaxClassifications { return SyntaxClassifications(_syntaxNode, in: range) } @@ -52,7 +52,7 @@ public extension SyntaxProtocol { /// - at: The relative to the node byte offset. /// - Returns: The ``SyntaxClassifiedRange`` for the offset or nil if the source text /// at the given offset is unclassified. - func classification(at offset: Int) -> SyntaxClassifiedRange? { + public func classification(at offset: Int) -> SyntaxClassifiedRange? { let classifications = SyntaxClassifications(_syntaxNode, in: ByteSourceRange(offset: offset, length: 1)) var iterator = classifications.makeIterator() return iterator.next() @@ -63,7 +63,7 @@ public extension SyntaxProtocol { /// - at: The absolute position. /// - Returns: The ``SyntaxClassifiedRange`` for the position or nil if the source text /// at the given position is unclassified. - func classification(at position: AbsolutePosition) -> SyntaxClassifiedRange? { + public func classification(at position: AbsolutePosition) -> SyntaxClassifiedRange? { let relativeOffset = position.utf8Offset - self.position.utf8Offset return self.classification(at: relativeOffset) } diff --git a/Sources/SwiftIDEUtils/SyntaxClassification.swift b/Sources/SwiftIDEUtils/SyntaxClassification.swift index fd66e58e41b..2295f6f479d 100644 --- a/Sources/SwiftIDEUtils/SyntaxClassification.swift +++ b/Sources/SwiftIDEUtils/SyntaxClassification.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif public enum SyntaxClassification: Sendable { /// An attribute starting with an `@`. diff --git a/Sources/SwiftIDEUtils/Utils.swift b/Sources/SwiftIDEUtils/Utils.swift index 2bba57c7934..85125f7fcef 100644 --- a/Sources/SwiftIDEUtils/Utils.swift +++ b/Sources/SwiftIDEUtils/Utils.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif extension Range { /// Shift the range `utf8Offset` bytes to the right, ie. add `utf8Offset` to the upper and lower bound. diff --git a/Sources/SwiftLibraryPluginProvider/CMakeLists.txt b/Sources/SwiftLibraryPluginProvider/CMakeLists.txt new file mode 100644 index 00000000000..fc3d24c086b --- /dev/null +++ b/Sources/SwiftLibraryPluginProvider/CMakeLists.txt @@ -0,0 +1,18 @@ +# This source file is part of the Swift.org open source project +# +# Copyright (c) 2024 Apple Inc. and the Swift project authors +# Licensed under Apache License v2.0 with Runtime Library Exception +# +# See http://swift.org/LICENSE.txt for license information +# See http://swift.org/CONTRIBUTORS.txt for Swift project authors + +add_swift_syntax_library(SwiftLibraryPluginProvider + LibraryPluginProvider.swift +) +target_link_libraries(SwiftLibraryPluginProvider PRIVATE + _SwiftLibraryPluginProviderCShims +) +target_link_swift_syntax_libraries(SwiftLibraryPluginProvider PUBLIC + SwiftSyntaxMacros + SwiftCompilerPluginMessageHandling +) diff --git a/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift b/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift new file mode 100644 index 00000000000..eb06cca2686 --- /dev/null +++ b/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift @@ -0,0 +1,201 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if swift(>=6.0) +public import SwiftSyntaxMacros +@_spi(PluginMessage) public import SwiftCompilerPluginMessageHandling +private import _SwiftLibraryPluginProviderCShims +// NOTE: Do not use '_SwiftSyntaxCShims' for 'dlopen' and 'LoadLibraryW' (Windows) +// because we don't want other modules depend on 'WinSDK'. +#if canImport(Darwin) +private import Darwin +#elseif canImport(Glibc) +private import Glibc +#elseif canImport(Musl) +private import Musl +#endif +#else +import SwiftSyntaxMacros +@_spi(PluginMessage) import SwiftCompilerPluginMessageHandling +@_implementationOnly import _SwiftLibraryPluginProviderCShims +#if canImport(Darwin) +@_implementationOnly import Darwin +#elseif canImport(Glibc) +@_implementationOnly import Glibc +#elseif canImport(Musl) +@_implementationOnly import Musl +#endif +#endif + +/// Singleton 'PluginProvider' that can serve shared library plugins. +@_spi(PluginMessage) +public class LibraryPluginProvider: PluginProvider { + struct LoadedLibraryPlugin { + var libraryPath: String + var handle: UnsafeMutableRawPointer + } + + struct MacroRef: Hashable { + var moduleName: String + var typeName: String + } + + /// Loaded dynamic link library handles associated with the module name. + var loadedLibraryPlugins: [String: LoadedLibraryPlugin] = [:] + + /// Resolved macros cache. + var resolvedMacros: [MacroRef: Macro.Type] = [:] + + private init() {} + + /// Singleton. + @MainActor + public static let shared: LibraryPluginProvider = LibraryPluginProvider() + + public var features: [PluginFeature] { + [.loadPluginLibrary] + } + + public func loadPluginLibrary(libraryPath: String, moduleName: String) throws { + if let loaded = loadedLibraryPlugins[moduleName] { + guard loaded.libraryPath == libraryPath else { + // NOTE: Should be unreachable. Compiler should not load different + // library for the same module name. + throw LibraryPluginError( + message: + "library plugin for module '\(moduleName)' is already loaded from different path '\(loaded.libraryPath)'" + ) + } + return + } + + let dlHandle = try _loadLibrary(libraryPath) + + loadedLibraryPlugins[moduleName] = LoadedLibraryPlugin( + libraryPath: libraryPath, + handle: dlHandle + ) + } + + public func resolveMacro(moduleName: String, typeName: String) throws -> SwiftSyntaxMacros.Macro.Type { + let macroRef = MacroRef(moduleName: moduleName, typeName: typeName) + if let resolved = resolvedMacros[macroRef] { + return resolved + } + + // Find 'dlopen'ed library for the module name. + guard let plugin = loadedLibraryPlugins[moduleName] else { + // NOTE: Should be unreachable. Compiler should not use this server + // unless the plugin loading succeeded. + throw LibraryPluginError(message: "plugin not loaded for module '\(moduleName)'") + } + + // Lookup the type metadata. + guard let type = _findAnyType(moduleName, typeName) else { + throw LibraryPluginError( + message: "type '\(moduleName).\(typeName)' could not be found in library plugin '\(plugin.libraryPath)'" + ) + } + + // The type must be a 'Macro' type. + guard let macro = type as? Macro.Type else { + throw LibraryPluginError( + message: + "type '\(moduleName).\(typeName)' is not a valid macro implementation type in library plugin '\(plugin.libraryPath)'" + ) + } + + // Cache the resolved type. + resolvedMacros[macroRef] = macro + return macro + } +} + +#if os(Windows) +private func _loadLibrary(_ path: String) throws -> UnsafeMutableRawPointer { + // Create NULL terminated UTF16 string. + let utf16Path = UnsafeMutableBufferPointer.allocate(capacity: path.utf16.count + 1) + defer { utf16Path.deallocate() } + let end = utf16Path.initialize(fromContentsOf: path.utf16) + utf16Path.initializeElement(at: end, to: 0) + + guard let dlHandle = swiftlibrarypluginprovider_LoadLibraryW(utf16Path.baseAddress) else { + // FIXME: Format the error code to string. + throw LibraryPluginError(message: "loader error: \(swiftlibrarypluginprovider_GetLastError())") + } + return UnsafeMutableRawPointer(dlHandle) +} +#else +private func _loadLibrary(_ path: String) throws -> UnsafeMutableRawPointer { + guard let dlHandle = dlopen(path, RTLD_LAZY | RTLD_LOCAL) else { + throw LibraryPluginError(message: "loader error: \(String(cString: dlerror()))") + } + return dlHandle +} +#endif + +private func _findAnyType(_ moduleName: String, _ typeName: String) -> Any.Type? { + // Create a mangled name for struct, enum, and class. And use a runtime + // function to find the type. Note that this simple mangling works even if the + // actual symbol name doesn't match with it. i.e. We don't need to perform + // punycode encodings or word substitutions. + // FIXME: This is process global. Can we limit it to a specific .dylib ? + for suffix in [ /*struct*/"V", /*enum*/ "O", /*class*/ "C"] { + let mangled = "\(moduleName.utf8.count)\(moduleName)\(typeName.utf8.count)\(typeName)\(suffix)" + if let type = _typeByName(mangled) { + return type + } + } + return nil +} + +private struct LibraryPluginError: Error, CustomStringConvertible { + var description: String + init(message: String) { + self.description = message + } +} + +// Compatibility shim for SE-0370 +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + private func initialize(fromContentsOf source: some Collection) -> Index { + let count = source.withContiguousStorageIfAvailable { + guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { + return 0 + } + precondition( + $0.count <= self.count, + "buffer cannot contain every element from source." + ) + baseAddress?.initialize(from: sourceAddress, count: $0.count) + return $0.count + } + if let count { + return startIndex.advanced(by: count) + } + + var (iterator, copied) = self.initialize(from: source) + precondition( + iterator.next() == nil, + "buffer cannot contain every element from source." + ) + return startIndex.advanced(by: copied) + } + + private func initializeElement(at index: Index, to value: Element) { + precondition(startIndex <= index && index < endIndex) + let p = baseAddress!.advanced(by: index) + p.initialize(to: value) + } +} +#endif diff --git a/Sources/SwiftOperators/OperatorError+Diagnostics.swift b/Sources/SwiftOperators/OperatorError+Diagnostics.swift index 5360ba5a87b..efedd4e9844 100644 --- a/Sources/SwiftOperators/OperatorError+Diagnostics.swift +++ b/Sources/SwiftOperators/OperatorError+Diagnostics.swift @@ -12,8 +12,8 @@ #if swift(>=6) public import SwiftDiagnostics -import SwiftParser -import SwiftSyntax +internal import SwiftParser +internal import SwiftSyntax #else import SwiftDiagnostics import SwiftParser diff --git a/Sources/SwiftOperators/OperatorTable+Defaults.swift b/Sources/SwiftOperators/OperatorTable+Defaults.swift index 6c9cdce5401..7514e2f47f8 100644 --- a/Sources/SwiftOperators/OperatorTable+Defaults.swift +++ b/Sources/SwiftOperators/OperatorTable+Defaults.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif /// Prefabricated operator precedence graphs. extension OperatorTable { @@ -60,7 +64,7 @@ extension OperatorTable { /// without requiring access to the standard library source code. However, /// because it does not incorporate user-defined operators, it will only /// ever be useful for a quick approximation. - public static var standardOperators: OperatorTable { + public static let standardOperators: OperatorTable = { let precedenceGroups: [PrecedenceGroup] = [ PrecedenceGroup( name: "AssignmentPrecedence", @@ -433,5 +437,5 @@ extension OperatorTable { precedenceGroups: precedenceGroups, operators: operators ) - } + }() } diff --git a/Sources/SwiftOperators/OperatorTable.swift b/Sources/SwiftOperators/OperatorTable.swift index 6691bc59855..e80f6803bd3 100644 --- a/Sources/SwiftOperators/OperatorTable.swift +++ b/Sources/SwiftOperators/OperatorTable.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif /// Maintains and validates information about all operators in a Swift program. /// diff --git a/Sources/SwiftOperators/PrecedenceGraph.swift b/Sources/SwiftOperators/PrecedenceGraph.swift index 10be03b312e..9598a1dcd2d 100644 --- a/Sources/SwiftOperators/PrecedenceGraph.swift +++ b/Sources/SwiftOperators/PrecedenceGraph.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif /// Describes the relative precedence of two groups. enum Precedence: Sendable { diff --git a/Sources/SwiftParser/Attributes.swift b/Sources/SwiftParser/Attributes.swift index 2d02f58db4b..b528f8273ae 100644 --- a/Sources/SwiftParser/Attributes.swift +++ b/Sources/SwiftParser/Attributes.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { mutating func parseAttributeList() -> RawAttributeListSyntax { @@ -190,7 +194,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 +204,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 +291,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 +361,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 +411,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 +432,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 +444,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 +588,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 +612,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 +1087,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 +1195,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 d20b1ca50cc..377900082ec 100644 --- a/Sources/SwiftParser/Availability.swift +++ b/Sources/SwiftParser/Availability.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { /// Parse a list of availability arguments. @@ -117,7 +121,7 @@ extension Parser { (.obsoleted, let handle)?: let argumentLabel = self.eat(handle) let (unexpectedBeforeColon, colon) = self.expect(.colon) - let version = self.parseVersionTuple(maxComponentCount: 3) + let version = self.parseVersionTuple() entry = .availabilityLabeledArgument( RawAvailabilityLabeledArgumentSyntax( label: argumentLabel, @@ -130,7 +134,7 @@ extension Parser { case (.deprecated, let handle)?: let argumentLabel = self.eat(handle) if let colon = self.consume(if: .colon) { - let version = self.parseVersionTuple(maxComponentCount: 3) + let version = self.parseVersionTuple() entry = .availabilityLabeledArgument( RawAvailabilityLabeledArgumentSyntax( label: argumentLabel, @@ -206,7 +210,7 @@ extension Parser { let version: RawVersionTupleSyntax? if self.at(.integerLiteral, .floatLiteral) { - version = self.parseVersionTuple(maxComponentCount: 3) + version = self.parseVersionTuple() } else { version = nil } @@ -250,19 +254,22 @@ extension Parser { } /// Parse a dot-separated list of version numbers. - mutating func parseVersionTuple(maxComponentCount: Int) -> RawVersionTupleSyntax { + mutating func parseVersionTuple() -> RawVersionTupleSyntax { if self.at(.floatLiteral), let periodIndex = self.currentToken.tokenText.firstIndex(of: UInt8(ascii: ".")), self.currentToken.tokenText[0..=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension DeclarationModifier { var canHaveParenthesizedArgument: Bool { @@ -19,7 +23,7 @@ extension DeclarationModifier { .borrowing, .class, .consuming, .convenience, .distributed, .dynamic, .final, .indirect, .infix, .isolated, .lazy, .mutating, .nonmutating, .optional, .override, .postfix, .prefix, .reasync, ._resultDependsOn, ._resultDependsOnSelf, .required, - .rethrows, .static, .weak, .transferring: + .rethrows, .static, .weak, .sending: return false case .fileprivate, .internal, .nonisolated, .package, .open, .private, .public, .unowned: @@ -225,15 +229,23 @@ extension Parser { case (.lhs(.import), let handle)?: return RawDeclSyntax(self.parseImportDeclaration(attrs, handle)) case (.lhs(.class), let handle)?: - return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawClassDeclSyntax.self, attrs: attrs, introucerHandle: handle)) + return RawDeclSyntax( + self.parseNominalTypeDeclaration(for: RawClassDeclSyntax.self, attrs: attrs, introucerHandle: handle) + ) case (.lhs(.enum), let handle)?: - return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawEnumDeclSyntax.self, attrs: attrs, introucerHandle: handle)) + return RawDeclSyntax( + self.parseNominalTypeDeclaration(for: RawEnumDeclSyntax.self, attrs: attrs, introucerHandle: handle) + ) case (.lhs(.case), let handle)?: return RawDeclSyntax(self.parseEnumCaseDeclaration(attrs, handle)) case (.lhs(.struct), let handle)?: - return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawStructDeclSyntax.self, attrs: attrs, introucerHandle: handle)) + return RawDeclSyntax( + self.parseNominalTypeDeclaration(for: RawStructDeclSyntax.self, attrs: attrs, introucerHandle: handle) + ) case (.lhs(.protocol), let handle)?: - return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawProtocolDeclSyntax.self, attrs: attrs, introucerHandle: handle)) + return RawDeclSyntax( + self.parseNominalTypeDeclaration(for: RawProtocolDeclSyntax.self, attrs: attrs, introucerHandle: handle) + ) case (.lhs(.associatedtype), let handle)?: return RawDeclSyntax(self.parseAssociatedTypeDeclaration(attrs, handle)) case (.lhs(.typealias), let handle)?: @@ -253,7 +265,9 @@ extension Parser { case (.lhs(.precedencegroup), let handle)?: return RawDeclSyntax(self.parsePrecedenceGroupDeclaration(attrs, handle)) case (.lhs(.actor), let handle)?: - return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawActorDeclSyntax.self, attrs: attrs, introucerHandle: handle)) + return RawDeclSyntax( + self.parseNominalTypeDeclaration(for: RawActorDeclSyntax.self, attrs: attrs, introucerHandle: handle) + ) case (.lhs(.macro), let handle)?: return RawDeclSyntax(self.parseMacroDeclaration(attrs: attrs, introducerHandle: handle)) case (.lhs(.pound), let handle)?: @@ -421,7 +435,9 @@ extension Parser { var each = self.consume(if: .keyword(.each)) let (unexpectedBetweenEachAndName, name) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true) - if attributes.isEmpty && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing && elements.isEmpty && !self.at(prefix: ">") { + if attributes.isEmpty && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing + && elements.isEmpty && !self.at(prefix: ">") + { break } @@ -699,7 +715,7 @@ extension Parser { extension Parser { mutating func parseMemberBlockItem() -> RawMemberBlockItemSyntax? { let startToken = self.currentToken - if let syntax = self.loadCurrentSyntaxNodeFromCache(for: .memberDeclListItem) { + if let syntax = self.loadCurrentSyntaxNodeFromCache(for: .memberBlockItem) { self.registerNodeForIncrementalParse(node: syntax.raw, startToken: startToken) return RawMemberBlockItemSyntax(syntax.raw) } @@ -952,7 +968,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 +1066,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 +1164,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 +1208,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 +1336,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 +1429,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 +1590,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 +1640,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 +1666,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 +1817,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 +1845,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..e26520d1a07 100644 --- a/Sources/SwiftParser/Directives.swift +++ b/Sources/SwiftParser/Directives.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { private enum IfConfigContinuationClauseStartKeyword: TokenSpecSet { @@ -54,7 +58,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 +91,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 +107,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 +125,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 +145,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 +198,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/ExpressionInterpretedAsVersionTuple.swift b/Sources/SwiftParser/ExpressionInterpretedAsVersionTuple.swift new file mode 100644 index 00000000000..91d94b7215c --- /dev/null +++ b/Sources/SwiftParser/ExpressionInterpretedAsVersionTuple.swift @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if swift(>=6) +@_spi(RawSyntax) public import SwiftSyntax +#else +@_spi(RawSyntax) import SwiftSyntax +#endif + +extension ExprSyntax { + /// Parse the source code of this node as a `VersionTupleSyntax`. + /// + /// In some situations, like the `_version` argument of the `canImport` condition in `#if`, the version gets parsed as a normal expression, which results in + /// - an integer literal for single-component versions + /// - a floating point number for two-component versions + /// - a floating point number with a member accesses for versions with more than three components + /// + /// This is done so the parser can parse `canImport` like any other function call, reducing the need for special handling. + /// + /// This property re-interprets such an expression as a version tuple in cases where the client know that it should semantically represent a version. + /// + /// If the expression cannot be interpreted as a valid version tuple, returns `nil`. + public var interpretedAsVersionTuple: VersionTupleSyntax? { + self.syntaxTextBytes.withUnsafeBufferPointer { bytes in + var parser = Parser(bytes) + let versionTuple = VersionTupleSyntax.parse(from: &parser) + if versionTuple.hasError { + return nil + } + return versionTuple + } + } +} diff --git a/Sources/SwiftParser/Expressions.swift b/Sources/SwiftParser/Expressions.swift index 99b0c95ea69..20c776c504e 100644 --- a/Sources/SwiftParser/Expressions.swift +++ b/Sources/SwiftParser/Expressions.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension TokenConsumer { mutating func atStartOfExpression() -> Bool { @@ -124,7 +128,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) @@ -522,7 +527,7 @@ extension Parser { ) case (.any, _)?: - if !atContextualExpressionModifier() { + if !atContextualExpressionModifier() && !self.peek().isContextualPunctuator("~") { break EXPR_PREFIX } @@ -747,7 +752,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 +789,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 +813,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) @@ -1092,10 +1101,6 @@ extension Parser { pattern: PatternContext, flavor: ExprFlavor ) -> RawExprSyntax { - if flavor == .poundIfDirective, let directiveExpr = self.parsePrimaryExprForDirective() { - return RawExprSyntax(directiveExpr) - } - switch self.at(anyIn: PrimaryExpressionStart.self) { case (.integerLiteral, let handle)?: let literal = self.eat(handle) @@ -1136,7 +1141,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. @@ -1190,7 +1196,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( @@ -1237,18 +1245,6 @@ extension Parser { return RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } } - - // try to parse a primary expression for a directive - mutating func parsePrimaryExprForDirective() -> RawExprSyntax? { - switch self.at(anyIn: CompilationCondition.self) { - case (.canImport, let handle)?: - return RawExprSyntax(self.parseCanImportExpression(handle)) - - // TODO: add case `swift` and `compiler` here - default: - return nil - } - } } extension Parser { @@ -1393,7 +1389,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, @@ -1440,7 +1439,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) } @@ -1525,8 +1529,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 { @@ -1699,7 +1703,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 { @@ -1791,7 +1799,10 @@ extension Parser { effectSpecifiers = self.parseTypeEffectSpecifiers() if self.at(.arrow) { - returnClause = self.parseFunctionReturnClause(effectSpecifiers: &effectSpecifiers, allowNamedOpaqueResultType: false) + returnClause = self.parseFunctionReturnClause( + effectSpecifiers: &effectSpecifiers, + allowNamedOpaqueResultType: false + ) } } @@ -1853,7 +1864,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( @@ -1918,7 +1932,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() @@ -2260,7 +2276,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() }) }) } @@ -2273,7 +2290,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, @@ -2296,7 +2315,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 @@ -2391,62 +2412,21 @@ extension Parser { } } -// MARK: Platform Condition -extension Parser { - mutating func parseCanImportExpression(_ handle: TokenConsumptionHandle) -> RawExprSyntax { - let canImportKeyword = self.eat(handle) - - let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen) - - let (unexpectedBeforeImportPath, importPath) = self.expect(.identifier) - - var versionInfo: RawCanImportVersionInfoSyntax? - - if let comma = self.consume(if: .comma) { - let (unexpectedBeforeLabel, label) = self.expect(anyIn: CanImportVersionInfoSyntax.LabelOptions.self, default: ._version) - let (unexpectedBeforeColon, colon) = self.expect(.colon) - - let version = self.parseVersionTuple(maxComponentCount: 4) - - versionInfo = RawCanImportVersionInfoSyntax( - comma: comma, - unexpectedBeforeLabel, - label: label, - unexpectedBeforeColon, - colon: colon, - version: version, - arena: self.arena - ) - } - - let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) - - return RawExprSyntax( - RawCanImportExprSyntax( - canImportKeyword: canImportKeyword, - unexpectedBeforeLeftParen, - leftParen: leftParen, - unexpectedBeforeImportPath, - importPath: importPath, - versionInfo: versionInfo, - unexpectedBeforeRightParen, - rightParen: rightParen, - arena: self.arena - ) - ) - } -} - // MARK: Lookahead extension Parser.Lookahead { // Consume 'async', 'throws', and 'rethrows', but in any order. mutating func consumeEffectsSpecifiers() { var loopProgress = LoopProgressCondition() - while let (_, handle) = self.at(anyIn: EffectSpecifier.self), + while let (spec, handle) = self.at(anyIn: EffectSpecifier.self), self.hasProgressed(&loopProgress) { self.eat(handle) + + if spec.isThrowsSpecifier, self.consume(if: .leftParen) != nil { + _ = self.canParseSimpleOrCompositionType() + self.consume(if: .rightParen) + } } } @@ -2473,7 +2453,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) { @@ -2491,7 +2473,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 @@ -2561,7 +2545,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/IsValidIdentifier.swift b/Sources/SwiftParser/IsValidIdentifier.swift index 6e734bd0fda..d8305c86643 100644 --- a/Sources/SwiftParser/IsValidIdentifier.swift +++ b/Sources/SwiftParser/IsValidIdentifier.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif /// Context in which to check if a name can be used as an identifier. /// diff --git a/Sources/SwiftParser/Lexer/Cursor.swift b/Sources/SwiftParser/Lexer/Cursor.swift index b2a80510417..4c2372fb886 100644 --- a/Sources/SwiftParser/Lexer/Cursor.swift +++ b/Sources/SwiftParser/Lexer/Cursor.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(BumpPtrAllocator) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(BumpPtrAllocator) import SwiftSyntax +#endif extension SyntaxText { fileprivate func containsPlaceholderEnd() -> Bool { @@ -52,7 +56,7 @@ extension Lexer.Cursor { /// - A string interpolation inside is entered /// - A regex literal is being lexed /// - A narrow case for 'try?' and 'try!' to ensure correct regex lexing - enum State { + enum State: Equatable { /// Normal top-level lexing mode case normal @@ -187,7 +191,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: @@ -203,6 +212,11 @@ extension Lexer.Cursor { } } } + + /// See `Lexer.Cursor.hasProgressed(comparedTo:)`. + fileprivate func hasProgressed(comparedTo other: StateStack) -> Bool { + return currentState != other.currentState || stateStack?.count != other.stateStack?.count + } } /// An error that was discovered in a lexeme while lexing it. @@ -257,6 +271,16 @@ extension Lexer { self.position = Position(input: input, previous: previous) } + /// Returns `true` if this cursor is sufficiently different to `other` in a way that indicates that the lexer has + /// made progress. + /// + /// This is the case if the lexer advanced its position in the source file or if it has performed a state + /// transition. + func hasProgressed(comparedTo other: Cursor) -> Bool { + return position.input.baseAddress != other.position.input.baseAddress + || stateStack.hasProgressed(comparedTo: other.stateStack) + } + var input: UnsafeBufferPointer { position.input } var previous: UInt8 { position.previous } @@ -436,7 +460,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) } @@ -554,7 +582,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 } @@ -583,7 +616,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 } @@ -913,7 +951,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. @@ -1033,7 +1074,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: @@ -1041,14 +1085,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() @@ -1057,7 +1107,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": @@ -1392,7 +1444,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)) } @@ -1454,7 +1509,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) @@ -1554,7 +1611,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()!) @@ -1776,7 +1836,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 } @@ -1880,7 +1943,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 @@ -2257,7 +2323,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 }) { @@ -2265,7 +2334,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..59e47831e36 100644 --- a/Sources/SwiftParser/Lexer/LexemeSequence.swift +++ b/Sources/SwiftParser/Lexer/LexemeSequence.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(BumpPtrAllocator) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(BumpPtrAllocator) import SwiftSyntax +#endif extension Lexer { /// A sequence of ``Lexer/Lexeme`` tokens starting from a ``Lexer/Cursor`` @@ -44,10 +48,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 +74,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 +95,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 +111,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..e6ffe512ef9 100644 --- a/Sources/SwiftParser/Lexer/RegexLiteralLexer.swift +++ b/Sources/SwiftParser/Lexer/RegexLiteralLexer.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(BumpPtrAllocator) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(BumpPtrAllocator) import SwiftSyntax +#endif /// A separate lexer specifically for regex literals. fileprivate struct RegexLiteralLexer { @@ -656,7 +660,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/Lookahead.swift b/Sources/SwiftParser/Lookahead.swift index ba9bdae2bbd..ac4edd483c9 100644 --- a/Sources/SwiftParser/Lookahead.swift +++ b/Sources/SwiftParser/Lookahead.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { /// Token lookahead for the parser. diff --git a/Sources/SwiftParser/LoopProgressCondition.swift b/Sources/SwiftParser/LoopProgressCondition.swift index 9a9b6bf6803..1a145655772 100644 --- a/Sources/SwiftParser/LoopProgressCondition.swift +++ b/Sources/SwiftParser/LoopProgressCondition.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif /// A type that can be used to make sure that a loop in the parser makes process. /// @@ -29,14 +33,7 @@ struct LoopProgressCondition { guard let previousToken = self.currentToken else { return true } - // The loop has made progress if either - // - the parser is now pointing at a different location in the source file - // - the parser is still pointing at the same position in the source file - // but now has a different token kind (and thus consumed a zero-length - // token like an empty string interpolation - let hasMadeProgress = - previousToken.tokenText.baseAddress != currentToken.tokenText.baseAddress - || (previousToken.byteLength == 0 && previousToken.rawTokenKind != currentToken.rawTokenKind) + let hasMadeProgress = currentToken.cursor.hasProgressed(comparedTo: previousToken.cursor) assert(hasMadeProgress, "Loop should always make progress") return hasMadeProgress } diff --git a/Sources/SwiftParser/Modifiers.swift b/Sources/SwiftParser/Modifiers.swift index 83585156452..9f29fae0b5a 100644 --- a/Sources/SwiftParser/Modifiers.swift +++ b/Sources/SwiftParser/Modifiers.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { mutating func parseDeclModifierList() -> RawDeclModifierListSyntax { @@ -86,7 +90,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 +100,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..d33e203ef00 100644 --- a/Sources/SwiftParser/Names.swift +++ b/Sources/SwiftParser/Names.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { mutating func parseAnyIdentifier() -> RawTokenSyntax { @@ -66,7 +70,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 +222,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..0e16e857fd8 100644 --- a/Sources/SwiftParser/Nominals.swift +++ b/Sources/SwiftParser/Nominals.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif protocol NominalTypeDeclarationTrait { associatedtype PrimaryOrGenerics @@ -318,7 +322,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..1b7add9845a 100644 --- a/Sources/SwiftParser/Parameters.swift +++ b/Sources/SwiftParser/Parameters.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif // MARK: - Traits @@ -204,7 +208,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 +254,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 +272,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..6151ca3beb0 100644 --- a/Sources/SwiftParser/Patterns.swift +++ b/Sources/SwiftParser/Patterns.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif extension Parser { /// Parse a pattern. @@ -67,7 +71,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 +121,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 +183,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 +229,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( @@ -262,7 +272,7 @@ extension Parser.Lookahead { // TODO: the other ownership modifiers (borrowing/consuming/mutating) more // than likely need to be made contextual as well before finalizing their // grammar. - case ._borrowing where experimentalFeatures.contains(.borrowingSwitch): + case ._borrowing, .borrowing: return peek(isAt: TokenSpec(.identifier, allowAtStartOfLine: false)) default: // Other keywords can be parsed unconditionally. @@ -367,7 +377,7 @@ extension Parser.Lookahead { && !self.at(.keyword(.__owned)) && !self.at(.keyword(.borrowing)) && !self.at(.keyword(.consuming)) - && !(experimentalFeatures.contains(.transferringArgsAndResults) && self.at(.keyword(.transferring))) + && !self.at(.keyword(.sending)) && !(experimentalFeatures.contains(.nonescapableTypes) && self.at(.keyword(._resultDependsOn))) { return true diff --git a/Sources/SwiftParser/README.md b/Sources/SwiftParser/README.md index 2818fc65fdf..8f66368771c 100644 --- a/Sources/SwiftParser/README.md +++ b/Sources/SwiftParser/README.md @@ -8,7 +8,11 @@ The easiest way to parse Swift source code is to call the `Parser.parse` method, ```swift import SwiftParser +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif let sourceText = """ diff --git a/Sources/SwiftParser/Recovery.swift b/Sources/SwiftParser/Recovery.swift index aeab4f7bde3..df0c32ae130 100644 --- a/Sources/SwiftParser/Recovery.swift +++ b/Sources/SwiftParser/Recovery.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif // MARK: Lookahead @@ -90,7 +94,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..e4e94645f68 100644 --- a/Sources/SwiftParser/Statements.swift +++ b/Sources/SwiftParser/Statements.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif extension TokenConsumer { /// Returns `true` if the current token represents the start of a statement @@ -162,11 +166,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 +237,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 +317,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 +890,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..95c7c975fd2 100644 --- a/Sources/SwiftParser/StringLiterals.swift +++ b/Sources/SwiftParser/StringLiterals.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif // MARK: - Check multiline string literal indentation @@ -149,7 +153,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 +200,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 +248,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 +276,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 +410,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/SwiftParser.docc/FilingBugReports.md b/Sources/SwiftParser/SwiftParser.docc/FilingBugReports.md index 915afc1ab19..7a9b2bafb6e 100644 --- a/Sources/SwiftParser/SwiftParser.docc/FilingBugReports.md +++ b/Sources/SwiftParser/SwiftParser.docc/FilingBugReports.md @@ -12,7 +12,7 @@ If you encounter a case where printing the parsed syntax tree does not reproduce ``` swift-parser-cli reduce /pth/to/file/that/does/not/roundtrip.swift ``` -2. File a bug report on with the reduced source code or fix the issue yourself by following the steps in . +2. File a bug report on with the reduced source code or fix the issue yourself by following the steps in . ## Parse of Valid Source Failed or Bad Diagnostic Produced @@ -23,7 +23,7 @@ If you have source code that is parsed correctly by the current Swift compiler ( swift-parser-cli print-diags /path/to/file.swift ``` 2. Remove as much code as possible from your test file and check if it still produces the same diagnostic. -3. File a bug report on with the reduced source code or fix the issue yourself by following the steps in . +3. File a bug report on with the reduced source code or fix the issue yourself by following the steps in . ## Parse of Valid Source Code Produced an Invalid Syntax Tree @@ -34,4 +34,4 @@ If you have valid source code that produced a syntax tree which doesn’t repres swift-parser-cli print-tree /path/to/file.swift ``` 2. Remove as much code as possible from your test file and check if it still produces the same invalid tree -3. File a bug report on with the reduced source code or fix the issue yourself by following the steps in . +3. File a bug report on with the reduced source code or fix the issue yourself by following the steps in . diff --git a/Sources/SwiftParser/SwiftParser.docc/SwiftParser.md b/Sources/SwiftParser/SwiftParser.docc/SwiftParser.md index cb411c5297b..b1346bb0618 100644 --- a/Sources/SwiftParser/SwiftParser.docc/SwiftParser.md +++ b/Sources/SwiftParser/SwiftParser.docc/SwiftParser.md @@ -12,7 +12,11 @@ The easiest way to parse Swift source code is to call the `Parser.parse` method, ```swift import SwiftParser +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif let sourceText = """ diff --git a/Sources/SwiftParser/SwiftParserCompatibility.swift b/Sources/SwiftParser/SwiftParserCompatibility.swift index 28b52807e26..5dfc982fdfc 100644 --- a/Sources/SwiftParser/SwiftParserCompatibility.swift +++ b/Sources/SwiftParser/SwiftParserCompatibility.swift @@ -10,19 +10,23 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif // This file provides compatibility aliases to keep dependents of SwiftSyntax building. // All users of the declarations in this file should transition away from them ASAP. -public extension TokenSpec { +extension TokenSpec { @available(*, deprecated, renamed: "leftSquare") - static var leftSquareBracket: TokenSpec { + public static var leftSquareBracket: TokenSpec { return .leftSquare } @available(*, deprecated, renamed: "rightSquare") - static var rightSquareBracket: TokenSpec { + public static var rightSquareBracket: TokenSpec { return .rightSquare } } diff --git a/Sources/SwiftParser/SyntaxUtils.swift b/Sources/SwiftParser/SyntaxUtils.swift index 5891956f1fe..01bf1e7b141 100644 --- a/Sources/SwiftParser/SyntaxUtils.swift +++ b/Sources/SwiftParser/SyntaxUtils.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif // MARK: - Unexpected nodes @@ -73,7 +77,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..f7ee632ba59 100644 --- a/Sources/SwiftParser/TokenConsumer.swift +++ b/Sources/SwiftParser/TokenConsumer.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif /// A type that consumes instances of ``TokenSyntax``. protocol TokenConsumer { @@ -134,7 +138,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)) @@ -372,6 +378,9 @@ extension TokenConsumer { return false } + case .prefixOperator where lexeme.isContextualPunctuator("~"): + return true + default: return false } diff --git a/Sources/SwiftParser/TokenPrecedence.swift b/Sources/SwiftParser/TokenPrecedence.swift index 3e620a67b9f..450f106e448 100644 --- a/Sources/SwiftParser/TokenPrecedence.swift +++ b/Sources/SwiftParser/TokenPrecedence.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif /// Describes how distinctive a token is for parser recovery. /// @@ -228,10 +232,12 @@ 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, - .transferring, ._consume, ._copy, ._mutate, + .inout, ._mutating, ._borrow, ._borrowing, .borrowing, ._consuming, .consuming, .consume, ._resultDependsOnSelf, + ._resultDependsOn, + .dependsOn, .scoped, .sending, // Accessors .get, .set, .didSet, .willSet, .unsafeAddress, .addressWithOwner, .addressWithNativeOwner, .unsafeMutableAddress, .mutableAddressWithOwner, .mutableAddressWithNativeOwner, ._read, ._modify, diff --git a/Sources/SwiftParser/TokenSpec.swift b/Sources/SwiftParser/TokenSpec.swift index ff5278f7b5b..8f96d124282 100644 --- a/Sources/SwiftParser/TokenSpec.swift +++ b/Sources/SwiftParser/TokenSpec.swift @@ -49,7 +49,7 @@ struct PrepareForKeywordMatch { /// matching against and is thus able to rule out one of the branches in /// `matches(rawTokenKind:text:)` based on the matched kind. @_spi(AlternateTokenIntrospection) -public struct TokenSpec { +public struct TokenSpec: Sendable { /// The kind we expect the token that we want to consume to have. /// This can be a keyword, in which case the ``TokenSpec`` will also match an /// identifier with the same text as the keyword and remap it to that keyword @@ -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..bd9b825977b 100644 --- a/Sources/SwiftParser/TokenSpecSet.swift +++ b/Sources/SwiftParser/TokenSpecSet.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) public import SwiftSyntax +@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax #else @_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax #endif @@ -377,8 +377,8 @@ enum DeclarationModifier: TokenSpecSet { case reasync case required case `rethrows` + case sending case `static` - case transferring case unowned case weak case _resultDependsOn @@ -419,11 +419,12 @@ enum DeclarationModifier: TokenSpecSet { case TokenSpec(.required): self = .required case TokenSpec(.rethrows): self = .rethrows case TokenSpec(.static): self = .static - case TokenSpec(.transferring): self = .transferring + case TokenSpec(.sending): self = .sending 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 } } @@ -463,7 +464,7 @@ enum DeclarationModifier: TokenSpecSet { case .required: return .keyword(.required) case .rethrows: return TokenSpec(.rethrows, recoveryPrecedence: .declKeyword) case .static: return .keyword(.static) - case .transferring: return .keyword(.transferring) + case .sending: return .keyword(.sending) case .unowned: return TokenSpec(.unowned, recoveryPrecedence: .declKeyword) case .weak: return TokenSpec(.weak, recoveryPrecedence: .declKeyword) case ._resultDependsOn: return TokenSpec(._resultDependsOn, recoveryPrecedence: .declKeyword) @@ -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..330f1fbfc27 100644 --- a/Sources/SwiftParser/TopLevel.swift +++ b/Sources/SwiftParser/TopLevel.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension Parser { /// Consumes and returns all remaining tokens in the source file. @@ -208,7 +212,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..88772f2fe75 100644 --- a/Sources/SwiftParser/Types.swift +++ b/Sources/SwiftParser/Types.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else @_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif extension Parser { /// Parse a type. @@ -33,9 +37,12 @@ extension Parser { mutating func parseTypeScalar(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax { let specifiersAndAttributes = self.parseTypeAttributeList(misplacedSpecifiers: misplacedSpecifiers) var base = RawTypeSyntax(self.parseSimpleOrCompositionType()) - if self.withLookahead({ $0.atFunctionTypeArrow() }) { + if self.withLookahead({ $0.canParseFunctionTypeArrow() }) { 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 +349,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 +632,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() @@ -646,21 +656,9 @@ extension Parser.Lookahead { return false } - if self.atFunctionTypeArrow() { - // Handle type-function if we have an '->' with optional - // 'async' and/or 'throws'. - var loopProgress = LoopProgressCondition() - while let (_, handle) = self.at(anyIn: EffectSpecifier.self), self.hasProgressed(&loopProgress) { - self.eat(handle) - } - - guard self.consume(if: .arrow) != nil else { - return false - } - + if self.canParseFunctionTypeArrow() { return self.canParseType() } - return true } @@ -688,6 +686,9 @@ extension Parser.Lookahead { switch self.currentToken { case TokenSpec(.Any): self.consumeAnyToken() + case TokenSpec(.prefixOperator) where self.currentToken.tokenText == "~": + self.consumeAnyToken(); + fallthrough case TokenSpec(.Self), TokenSpec(.identifier): guard self.canParseTypeIdentifier() else { return false @@ -734,7 +735,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 } @@ -804,33 +807,12 @@ extension Parser.Lookahead { return self.consume(if: .rightParen) != nil } - mutating func atFunctionTypeArrow() -> Bool { - if self.at(.arrow) { + mutating func canParseFunctionTypeArrow() -> Bool { + if self.consume(if: .arrow) != nil { return true } - - if let effect = self.at(anyIn: EffectSpecifier.self) { - if self.peek().rawTokenKind == .arrow { - return true - } - - if effect.spec.isThrowsSpecifier && self.peek().rawTokenKind == .leftParen { - var lookahead = self.lookahead() - lookahead.consumeAnyToken() - lookahead.skipSingle() - return lookahead.atFunctionTypeArrow() - } - - if peek(isAtAnyIn: EffectSpecifier.self) != nil { - var lookahead = self.lookahead() - lookahead.consumeAnyToken() - return lookahead.atFunctionTypeArrow() - } - - return false - } - - return false + self.consumeEffectsSpecifiers() + return self.consume(if: .arrow) != nil } mutating func canParseTypeIdentifier(allowKeyword: Bool = false) -> Bool { @@ -840,7 +822,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() @@ -890,29 +874,31 @@ extension Parser.Lookahead { } extension Parser { - private mutating func parseLifetimeTypeSpecifier( - specifierHandle: TokenConsumptionHandle - ) -> RawTypeSpecifierListSyntax.Element { - let specifier = self.eat(specifierHandle) + private mutating func parseLifetimeTypeSpecifier() -> RawTypeSpecifierListSyntax.Element { + let (unexpectedBeforeDependsOnKeyword, dependsOnKeyword) = self.expect(.keyword(.dependsOn)) guard let leftParen = self.consume(if: .leftParen) else { // If there is no left paren, add an entirely missing detail. Otherwise, we start to consume the following type // name as a token inside the detail, which leads to confusing recovery results. - let arguments = RawLifetimeSpecifierArgumentsSyntax( + let lifetimeSpecifierArgumentList = RawLifetimeSpecifierArgumentListSyntax( + elements: [ + RawLifetimeSpecifierArgumentSyntax(parameter: missingToken(.identifier), trailingComma: nil, arena: arena) + ], + arena: self.arena + ) + let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax( + unexpectedBeforeDependsOnKeyword, + dependsOnKeyword: dependsOnKeyword, leftParen: missingToken(.leftParen), - arguments: RawLifetimeSpecifierArgumentListSyntax( - elements: [ - RawLifetimeSpecifierArgumentSyntax(parameter: missingToken(.identifier), trailingComma: nil, arena: arena) - ], - arena: self.arena - ), + scopedKeyword: nil, + arguments: lifetimeSpecifierArgumentList, rightParen: missingToken(.rightParen), arena: self.arena ) - let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax(specifier: specifier, arguments: arguments, arena: self.arena) return .lifetimeTypeSpecifier(lifetimeSpecifier) } + let scoped = self.consume(if: .keyword(.scoped)) var keepGoing: RawTokenSyntax? var arguments: [RawLifetimeSpecifierArgumentSyntax] = [] var loopProgress = LoopProgressCondition() @@ -933,14 +919,16 @@ extension Parser { } while keepGoing != nil && self.hasProgressed(&loopProgress) let lifetimeSpecifierArgumentList = RawLifetimeSpecifierArgumentListSyntax(elements: arguments, arena: self.arena) let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) - let argumentsSyntax = RawLifetimeSpecifierArgumentsSyntax( + let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax( + unexpectedBeforeDependsOnKeyword, + dependsOnKeyword: dependsOnKeyword, leftParen: leftParen, + scopedKeyword: scoped, arguments: lifetimeSpecifierArgumentList, unexpectedBeforeRightParen, rightParen: rightParen, arena: self.arena ) - let lifetimeSpecifier = RawLifetimeTypeSpecifierSyntax(specifier: specifier, arguments: argumentsSyntax, arena: self.arena) return .lifetimeTypeSpecifier(lifetimeSpecifier) } @@ -958,17 +946,18 @@ extension Parser { specifiers: RawTypeSpecifierListSyntax, attributes: RawAttributeListSyntax )? { - typealias SimpleOrLifetimeSpecifier = EitherTokenSpecSet var specifiers: [RawTypeSpecifierListSyntax.Element] = [] - SPECIFIER_PARSING: while canHaveParameterSpecifier, let (specifierSpec, specifierHandle) = self.at(anyIn: SimpleOrLifetimeSpecifier.self) { - switch specifierSpec { - case .lhs: specifiers.append(parseSimpleTypeSpecifier(specifierHandle: specifierHandle)) - case .rhs: + SPECIFIER_PARSING: while canHaveParameterSpecifier { + if let (_, specifierHandle) = self.at(anyIn: SimpleTypeSpecifierSyntax.SpecifierOptions.self) { + specifiers.append(parseSimpleTypeSpecifier(specifierHandle: specifierHandle)) + } else if self.at(.keyword(.dependsOn)) { if self.experimentalFeatures.contains(.nonescapableTypes) { - specifiers.append(parseLifetimeTypeSpecifier(specifierHandle: specifierHandle)) + specifiers.append(parseLifetimeTypeSpecifier()) } else { break SPECIFIER_PARSING } + } else { + break SPECIFIER_PARSING } } specifiers += misplacedSpecifiers.map { diff --git a/Sources/SwiftParser/generated/ExperimentalFeatures.swift b/Sources/SwiftParser/generated/ExperimentalFeatures.swift index 6fae76a97a2..1e9be23ca28 100644 --- a/Sources/SwiftParser/generated/ExperimentalFeatures.swift +++ b/Sources/SwiftParser/generated/ExperimentalFeatures.swift @@ -36,9 +36,9 @@ extension Parser.ExperimentalFeatures { /// Whether to enable the parsing of NonEscableTypes. public static let nonescapableTypes = Self (rawValue: 1 << 3) - /// Whether to enable the parsing of TransferringArgsAndResults. - public static let transferringArgsAndResults = Self (rawValue: 1 << 4) - /// Whether to enable the parsing of borrowing pattern matching. - public static let borrowingSwitch = Self (rawValue: 1 << 5) + public static let borrowingSwitch = Self (rawValue: 1 << 4) + + /// Whether to enable the parsing of SendingArgsAndResults. + public static let sendingArgsAndResults = Self (rawValue: 1 << 5) } diff --git a/Sources/SwiftParser/generated/LayoutNodes+Parsable.swift b/Sources/SwiftParser/generated/LayoutNodes+Parsable.swift index 364bcf12c17..1fe2e6b16a2 100644 --- a/Sources/SwiftParser/generated/LayoutNodes+Parsable.swift +++ b/Sources/SwiftParser/generated/LayoutNodes+Parsable.swift @@ -346,6 +346,24 @@ extension TypeSyntax: SyntaxParseable { } } +extension VersionTupleSyntax: SyntaxParseable { + public static func parse(from parser: inout Parser) -> Self { + // Keep the parser alive so that the arena in which `raw` is allocated + // doesn’t get deallocated before we have a chance to create a syntax node + // from it. We can’t use `parser.arena` as the parameter to + // `Syntax(raw:arena:)` because the node might have been re-used during an + // incremental parse and would then live in a different arena than + // `parser.arena`. + defer { + withExtendedLifetime(parser) { + } + } + let node = parser.parseVersionTuple() + let raw = RawSyntax(parser.parseRemainder(into: node)) + return Syntax(raw: raw, rawNodeArena: parser.arena).cast(Self.self) + } +} + fileprivate extension Parser { mutating func parseNonOptionalCodeBlockItem() -> RawCodeBlockItemSyntax { guard let node = self.parseCodeBlockItem(isAtTopLevel: false, allowInitDecl: true) else { diff --git a/Sources/SwiftParser/generated/Parser+TokenSpecSet.swift b/Sources/SwiftParser/generated/Parser+TokenSpecSet.swift index 98c91c193d4..0411704b399 100644 --- a/Sources/SwiftParser/generated/Parser+TokenSpecSet.swift +++ b/Sources/SwiftParser/generated/Parser+TokenSpecSet.swift @@ -404,7 +404,7 @@ extension BooleanLiteralExprSyntax { } } -extension CanImportVersionInfoSyntax { +extension _CanImportVersionInfoSyntax { @_spi(Diagnostics) public enum LabelOptions: TokenSpecSet { case _version @@ -802,14 +802,15 @@ extension DeclModifierSyntax { case `private` case `public` case reasync + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _resultDependsOnSelf case required case `static` - @_spi(ExperimentalLanguageFeatures) - case transferring case unowned case weak + case sending init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) { switch PrepareForKeywordMatch(lexeme) { @@ -881,12 +882,12 @@ extension DeclModifierSyntax { self = .required case TokenSpec(.static): self = .static - case TokenSpec(.transferring) where experimentalFeatures.contains(.transferringArgsAndResults): - self = .transferring case TokenSpec(.unowned): self = .unowned case TokenSpec(.weak): self = .weak + case TokenSpec(.sending): + self = .sending default: return nil } @@ -962,12 +963,12 @@ extension DeclModifierSyntax { self = .required case TokenSpec(.static): self = .static - case TokenSpec(.transferring): - self = .transferring case TokenSpec(.unowned): self = .unowned case TokenSpec(.weak): self = .weak + case TokenSpec(.sending): + self = .sending default: return nil } @@ -1043,12 +1044,12 @@ extension DeclModifierSyntax { return .keyword(.required) case .static: return .keyword(.static) - case .transferring: - return .keyword(.transferring) case .unowned: return .keyword(.unowned) case .weak: return .keyword(.weak) + case .sending: + return .keyword(.sending) } } @@ -1126,12 +1127,12 @@ extension DeclModifierSyntax { return .keyword(.required) case .static: return .keyword(.static) - case .transferring: - return .keyword(.transferring) case .unowned: return .keyword(.unowned) case .weak: return .keyword(.weak) + case .sending: + return .keyword(.sending) } } } @@ -2623,79 +2624,6 @@ extension LifetimeSpecifierArgumentSyntax { } } -extension LifetimeTypeSpecifierSyntax { - @_spi(Diagnostics) - public enum SpecifierOptions: TokenSpecSet { - @_spi(ExperimentalLanguageFeatures) - case _copy - @_spi(ExperimentalLanguageFeatures) - case _consume - case _borrow - @_spi(ExperimentalLanguageFeatures) - case _mutate - - init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) { - switch PrepareForKeywordMatch(lexeme) { - case TokenSpec(._copy) where experimentalFeatures.contains(.nonescapableTypes): - self = ._copy - case TokenSpec(._consume) where experimentalFeatures.contains(.nonescapableTypes): - self = ._consume - case TokenSpec(._borrow): - self = ._borrow - case TokenSpec(._mutate) where experimentalFeatures.contains(.nonescapableTypes): - self = ._mutate - default: - return nil - } - } - - public init?(token: TokenSyntax) { - switch token { - case TokenSpec(._copy): - self = ._copy - case TokenSpec(._consume): - self = ._consume - case TokenSpec(._borrow): - self = ._borrow - case TokenSpec(._mutate): - self = ._mutate - default: - return nil - } - } - - var spec: TokenSpec { - switch self { - case ._copy: - return .keyword(._copy) - case ._consume: - return .keyword(._consume) - case ._borrow: - return .keyword(._borrow) - case ._mutate: - return .keyword(._mutate) - } - } - - /// Returns a token that satisfies the `TokenSpec` of this case. - /// - /// If the token kind of this spec has variable text, e.g. for an identifier, this returns a token with empty text. - @_spi(Diagnostics) - public var tokenSyntax: TokenSyntax { - switch self { - case ._copy: - return .keyword(._copy) - case ._consume: - return .keyword(._consume) - case ._borrow: - return .keyword(._borrow) - case ._mutate: - return .keyword(._mutate) - } - } - } -} - extension MemberTypeSyntax { @_spi(Diagnostics) public enum NameOptions: TokenSpecSet { @@ -2980,11 +2908,14 @@ extension OptionalBindingConditionSyntax { case `let` case `var` case `inout` + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _mutating - @_spi(ExperimentalLanguageFeatures) case _borrowing + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _consuming init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) { @@ -2997,7 +2928,7 @@ extension OptionalBindingConditionSyntax { self = .inout case TokenSpec(._mutating) where experimentalFeatures.contains(.referenceBindings): self = ._mutating - case TokenSpec(._borrowing) where experimentalFeatures.contains(.referenceBindings) || experimentalFeatures.contains(.borrowingSwitch): + case TokenSpec(._borrowing): self = ._borrowing case TokenSpec(._consuming) where experimentalFeatures.contains(.referenceBindings): self = ._consuming @@ -3405,10 +3336,11 @@ extension SimpleTypeSpecifierSyntax { case _const case borrowing case consuming + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) - case transferring - @_spi(ExperimentalLanguageFeatures) + #endif case _resultDependsOn + case sending init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) { switch PrepareForKeywordMatch(lexeme) { @@ -3426,10 +3358,10 @@ extension SimpleTypeSpecifierSyntax { self = .borrowing case TokenSpec(.consuming): self = .consuming - case TokenSpec(.transferring) where experimentalFeatures.contains(.transferringArgsAndResults): - self = .transferring case TokenSpec(._resultDependsOn) where experimentalFeatures.contains(.nonescapableTypes): self = ._resultDependsOn + case TokenSpec(.sending): + self = .sending default: return nil } @@ -3451,10 +3383,10 @@ extension SimpleTypeSpecifierSyntax { self = .borrowing case TokenSpec(.consuming): self = .consuming - case TokenSpec(.transferring): - self = .transferring case TokenSpec(._resultDependsOn): self = ._resultDependsOn + case TokenSpec(.sending): + self = .sending default: return nil } @@ -3476,10 +3408,10 @@ extension SimpleTypeSpecifierSyntax { return .keyword(.borrowing) case .consuming: return .keyword(.consuming) - case .transferring: - return .keyword(.transferring) case ._resultDependsOn: return .keyword(._resultDependsOn) + case .sending: + return .keyword(.sending) } } @@ -3503,10 +3435,10 @@ extension SimpleTypeSpecifierSyntax { return .keyword(.borrowing) case .consuming: return .keyword(.consuming) - case .transferring: - return .keyword(.transferring) case ._resultDependsOn: return .keyword(._resultDependsOn) + case .sending: + return .keyword(.sending) } } } @@ -3952,12 +3884,16 @@ extension ValueBindingPatternSyntax { case `let` case `var` case `inout` + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _mutating - @_spi(ExperimentalLanguageFeatures) case _borrowing + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _consuming + case borrowing init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) { switch PrepareForKeywordMatch(lexeme) { @@ -3969,10 +3905,12 @@ extension ValueBindingPatternSyntax { self = .inout case TokenSpec(._mutating) where experimentalFeatures.contains(.referenceBindings): self = ._mutating - case TokenSpec(._borrowing) where experimentalFeatures.contains(.referenceBindings) || experimentalFeatures.contains(.borrowingSwitch): + case TokenSpec(._borrowing): self = ._borrowing case TokenSpec(._consuming) where experimentalFeatures.contains(.referenceBindings): self = ._consuming + case TokenSpec(.borrowing): + self = .borrowing default: return nil } @@ -3992,6 +3930,8 @@ extension ValueBindingPatternSyntax { self = ._borrowing case TokenSpec(._consuming): self = ._consuming + case TokenSpec(.borrowing): + self = .borrowing default: return nil } @@ -4011,6 +3951,8 @@ extension ValueBindingPatternSyntax { return .keyword(._borrowing) case ._consuming: return .keyword(._consuming) + case .borrowing: + return .keyword(.borrowing) } } @@ -4032,6 +3974,8 @@ extension ValueBindingPatternSyntax { return .keyword(._borrowing) case ._consuming: return .keyword(._consuming) + case .borrowing: + return .keyword(.borrowing) } } } @@ -4043,11 +3987,14 @@ extension VariableDeclSyntax { case `let` case `var` case `inout` + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _mutating - @_spi(ExperimentalLanguageFeatures) case _borrowing + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _consuming init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) { @@ -4060,7 +4007,7 @@ extension VariableDeclSyntax { self = .inout case TokenSpec(._mutating) where experimentalFeatures.contains(.referenceBindings): self = ._mutating - case TokenSpec(._borrowing) where experimentalFeatures.contains(.referenceBindings) || experimentalFeatures.contains(.borrowingSwitch): + case TokenSpec(._borrowing): self = ._borrowing case TokenSpec(._consuming) where experimentalFeatures.contains(.referenceBindings): self = ._consuming diff --git a/Sources/SwiftParser/generated/TokenSpecStaticMembers.swift b/Sources/SwiftParser/generated/TokenSpecStaticMembers.swift index 7f0f81a9ba7..a495ca75d2a 100644 --- a/Sources/SwiftParser/generated/TokenSpecStaticMembers.swift +++ b/Sources/SwiftParser/generated/TokenSpecStaticMembers.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension TokenSpec { static var arrow: TokenSpec { diff --git a/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift b/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift index 60bf45cf59c..42128ddd58d 100644 --- a/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift +++ b/Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift @@ -10,9 +10,15 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftBasicFormat +internal import SwiftDiagnostics +@_spi(RawSyntax) internal import SwiftSyntax +#else import SwiftBasicFormat import SwiftDiagnostics @_spi(RawSyntax) import SwiftSyntax +#endif extension FixIt { /// A more complex set of changes that affects multiple syntax nodes and thus diff --git a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift index 570cff6c023..20fcc3a4d12 100644 --- a/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/LexerDiagnosticMessages.swift @@ -12,7 +12,7 @@ #if swift(>=6) public import SwiftDiagnostics -@_spi(Diagnostics) import SwiftParser +@_spi(Diagnostics) internal import SwiftParser @_spi(RawSyntax) public import SwiftSyntax #else import SwiftDiagnostics @@ -27,16 +27,16 @@ public protocol TokenError: DiagnosticMessage { var diagnosticID: MessageID { get } } -public extension TokenError { - static var diagnosticID: MessageID { +extension TokenError { + public static var diagnosticID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") } - var diagnosticID: MessageID { + public var diagnosticID: MessageID { return Self.diagnosticID } - var severity: DiagnosticSeverity { + public var severity: DiagnosticSeverity { return .error } } @@ -46,16 +46,16 @@ public protocol TokenWarning: DiagnosticMessage { var diagnosticID: MessageID { get } } -public extension TokenWarning { - static var diagnosticID: MessageID { +extension TokenWarning { + public static var diagnosticID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") } - var diagnosticID: MessageID { + public var diagnosticID: MessageID { return Self.diagnosticID } - var severity: DiagnosticSeverity { + public var severity: DiagnosticSeverity { return .warning } } @@ -180,11 +180,11 @@ public struct ErrorToWarningDowngrade: TokenWarning { // MARK: - Convert TokenDiagnostic from SwiftSyntax to error messages -public extension SwiftSyntax.TokenDiagnostic { +extension SwiftSyntax.TokenDiagnostic { /// `tokenText` is the entire text of the token in which the ``TokenDiagnostic`` /// occurred, including trivia. @_spi(RawSyntax) - func diagnosticMessage(in token: TokenSyntax) -> DiagnosticMessage { + public func diagnosticMessage(in token: TokenSyntax) -> DiagnosticMessage { var scalarAtErrorOffset: UnicodeScalar { // Fall back to the Unicode replacement character U+FFFD in case we can't // lex the unicode character at `byteOffset`. It's the best we can do @@ -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 @@ -237,7 +241,7 @@ public extension SwiftSyntax.TokenDiagnostic { } } - func position(in token: TokenSyntax) -> AbsolutePosition { + public func position(in token: TokenSyntax) -> AbsolutePosition { switch kind { case .extraneousLeadingWhitespaceError, .extraneousLeadingWhitespaceWarning: if let previousToken = token.previousToken(viewMode: .all) { @@ -249,7 +253,7 @@ public extension SwiftSyntax.TokenDiagnostic { return token.position.advanced(by: Int(byteOffset)) } - func fixIts(in token: TokenSyntax) -> [FixIt] { + public func fixIts(in token: TokenSyntax) -> [FixIt] { switch self.kind { case .nonBreakingSpace: let replaceNonBreakingSpace = { (piece: TriviaPiece) -> TriviaPiece in @@ -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..29651d250fe 100644 --- a/Sources/SwiftParserDiagnostics/MissingNodesError.swift +++ b/Sources/SwiftParserDiagnostics/MissingNodesError.swift @@ -11,8 +11,8 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftBasicFormat -import SwiftDiagnostics +internal import SwiftBasicFormat +internal import SwiftDiagnostics @_spi(RawSyntax) public import SwiftSyntax #else import SwiftBasicFormat @@ -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..dde8049f7f6 100644 --- a/Sources/SwiftParserDiagnostics/MissingTokenError.swift +++ b/Sources/SwiftParserDiagnostics/MissingTokenError.swift @@ -10,9 +10,15 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftDiagnostics +@_spi(Diagnostics) internal import SwiftParser +@_spi(RawSyntax) internal import SwiftSyntax +#else import SwiftDiagnostics @_spi(Diagnostics) import SwiftParser @_spi(RawSyntax) import SwiftSyntax +#endif extension ParseDiagnosticsGenerator { func handleMissingToken(_ missingToken: TokenSyntax) { @@ -31,13 +37,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 +68,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 +82,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 +104,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 +127,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 +141,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 +172,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..055e9760008 100644 --- a/Sources/SwiftParserDiagnostics/MultiLineStringLiteralDiagnosticsGenerator.swift +++ b/Sources/SwiftParserDiagnostics/MultiLineStringLiteralDiagnosticsGenerator.swift @@ -10,8 +10,13 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftDiagnostics +@_spi(RawSyntax) internal import SwiftSyntax +#else import SwiftDiagnostics @_spi(RawSyntax) import SwiftSyntax +#endif /// A diagnostic that `MultiLineStringLiteralIndentationDiagnosticsGenerator` is building. /// As indentation errors are found on more lines, this diagnostic is modified @@ -29,7 +34,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 +65,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..=6) public import SwiftDiagnostics -@_spi(Diagnostics) import SwiftParser -@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) public import SwiftSyntax +@_spi(Diagnostics) internal import SwiftParser +@_spi(ExperimentalLanguageFeatures) public import SwiftSyntax #else import SwiftDiagnostics @_spi(Diagnostics) import SwiftParser -@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +@_spi(ExperimentalLanguageFeatures) import SwiftSyntax #endif fileprivate func getTokens(between first: TokenSyntax, and second: TokenSyntax) -> [TokenSyntax] { @@ -66,7 +66,9 @@ fileprivate extension TokenSyntax { case .poundUnavailable: return self.with(\.tokenKind, .poundAvailable) default: - preconditionFailure("The availability token of an AvailabilityConditionSyntax should always be #available or #unavailable") + preconditionFailure( + "The availability token of an AvailabilityConditionSyntax should always be #available or #unavailable" + ) } } } @@ -117,7 +119,7 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return false } else { // If multiple tokens are missing at the same location, emit diagnostics about nodes that occur earlier in the tree first. - return $0.node.id.indexInTree < $1.node.id.indexInTree + return $0.node.id < $1.node.id } } return diagProducer.diagnostics @@ -136,7 +138,14 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { fixIts: [FixIt] = [], handledNodes: [SyntaxIdentifier] = [] ) { - let diagnostic = Diagnostic(node: Syntax(node), position: position, message: message, highlights: highlights, notes: notes, fixIts: fixIts) + let diagnostic = Diagnostic( + node: Syntax(node), + position: position, + message: message, + highlights: highlights, + notes: notes, + fixIts: fixIts + ) addDiagnostic(diagnostic, handledNodes: handledNodes) } @@ -184,7 +193,8 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { let correctAndMissingTokens = correctTokens.filter({ $0.isMissing }) var changes: [FixIt.MultiNodeChange] = [] if let misplacedToken = misplacedTokens.only, let correctToken = correctTokens.only, - misplacedToken.nextToken(viewMode: .all) == correctToken || misplacedToken.previousToken(viewMode: .all) == correctToken, + misplacedToken.nextToken(viewMode: .all) == correctToken + || misplacedToken.previousToken(viewMode: .all) == correctToken, correctToken.isMissing { // We are exchanging two adjacent tokens, transfer the trivia from the incorrect token to the corrected token. @@ -209,7 +219,12 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { fixIts.append(FixIt(message: removeFixIt, changes: changes)) } - addDiagnostic(incorrectContainer, message(misplacedTokens), fixIts: fixIts, handledNodes: [incorrectContainer.id] + correctAndMissingTokens.map(\.id)) + addDiagnostic( + incorrectContainer, + message(misplacedTokens), + fixIts: fixIts, + handledNodes: [incorrectContainer.id] + correctAndMissingTokens.map(\.id) + ) } /// If `unexpected` only contains a single token that satisfies `predicate`, @@ -238,7 +253,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { ) } - private func handleMisplacedEffectSpecifiersAfterArrow(effectSpecifiers: (some EffectSpecifiersSyntax)?, misplacedSpecifiers: UnexpectedNodesSyntax?) { + private func handleMisplacedEffectSpecifiersAfterArrow( + effectSpecifiers: (some EffectSpecifiersSyntax)?, + misplacedSpecifiers: UnexpectedNodesSyntax? + ) { exchangeTokens( unexpected: misplacedSpecifiers, unexpectedTokenCondition: { EffectSpecifier(token: $0) != nil }, @@ -249,9 +267,18 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { ) } - private func handleMisplacedEffectSpecifiers(effectSpecifiers: (some EffectSpecifiersSyntax)?, output: ReturnClauseSyntax?) { - handleMisplacedEffectSpecifiersAfterArrow(effectSpecifiers: effectSpecifiers, misplacedSpecifiers: output?.unexpectedBetweenArrowAndType) - handleMisplacedEffectSpecifiersAfterArrow(effectSpecifiers: effectSpecifiers, misplacedSpecifiers: output?.unexpectedAfterType) + private func handleMisplacedEffectSpecifiers( + effectSpecifiers: (some EffectSpecifiersSyntax)?, + output: ReturnClauseSyntax? + ) { + handleMisplacedEffectSpecifiersAfterArrow( + effectSpecifiers: effectSpecifiers, + misplacedSpecifiers: output?.unexpectedBetweenArrowAndType + ) + handleMisplacedEffectSpecifiersAfterArrow( + effectSpecifiers: effectSpecifiers, + misplacedSpecifiers: output?.unexpectedAfterType + ) } private func handleEffectSpecifiers(_ node: some EffectSpecifiersSyntax) -> 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)) @@ -595,50 +661,6 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { return .visitChildren } - public override func visit(_ node: CanImportExprSyntax) -> SyntaxVisitorContinueKind { - if shouldSkip(node) { - return .skipChildren - } - - if let versionTuple = node.versionInfo?.version, - let unexpectedVersionTuple = node.unexpectedBetweenVersionInfoAndRightParen - { - if versionTuple.major.isMissing { - addDiagnostic( - versionTuple, - CannotParseVersionTuple(versionTuple: unexpectedVersionTuple), - handledNodes: [versionTuple.id, unexpectedVersionTuple.id] - ) - } else { - addDiagnostic( - unexpectedVersionTuple, - .canImportWrongNumberOfParameter, - handledNodes: [unexpectedVersionTuple.id] - ) - } - } - - return .visitChildren - } - - public override func visit(_ node: CanImportVersionInfoSyntax) -> SyntaxVisitorContinueKind { - if shouldSkip(node) { - return .skipChildren - } - - if node.label.isMissing { - addDiagnostic( - node.label, - .canImportWrongSecondParameterLabel, - handledNodes: [node.label.id] - ) - - handledNodes.append(contentsOf: [node.unexpectedBetweenLabelAndColon?.id, node.colon.id, node.version.id].compactMap { $0 }) - } - - return .visitChildren - } - public override func visit(_ node: ConditionElementSyntax) -> SyntaxVisitorContinueKind { if shouldSkip(node) { return .skipChildren @@ -694,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 @@ -851,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] ) } @@ -1018,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 == "!", @@ -1033,7 +1069,10 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor { ) addDiagnostic( unexpected, - NegatedAvailabilityCondition(availabilityCondition: availability, negatedAvailabilityKeyword: negatedAvailabilityKeyword), + NegatedAvailabilityCondition( + availabilityCondition: availability, + negatedAvailabilityKeyword: negatedAvailabilityKeyword + ), fixIts: [ FixIt( message: ReplaceTokensFixIt( @@ -1048,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] + ) } } } @@ -1061,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, @@ -1253,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 @@ -1337,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)) + ) + ) ] ), ], @@ -1387,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 } @@ -1418,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 } @@ -1489,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] } @@ -1547,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, @@ -1557,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( @@ -1607,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: [ @@ -1691,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 @@ -1720,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] ) @@ -1825,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 + ), ] ) ], @@ -1908,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 ecf2e5d2cde..d89d4fbd968 100644 --- a/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift +++ b/Sources/SwiftParserDiagnostics/ParserDiagnosticMessages.swift @@ -12,7 +12,7 @@ #if swift(>=6) public import SwiftDiagnostics -@_spi(Diagnostics) import SwiftParser +@_spi(Diagnostics) internal import SwiftParser @_spi(RawSyntax) public import SwiftSyntax #else import SwiftDiagnostics @@ -27,16 +27,16 @@ public protocol ParserError: DiagnosticMessage { var diagnosticID: MessageID { get } } -public extension ParserError { - static var diagnosticID: MessageID { +extension ParserError { + public static var diagnosticID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") } - var diagnosticID: MessageID { + public var diagnosticID: MessageID { return Self.diagnosticID } - var severity: DiagnosticSeverity { + public var severity: DiagnosticSeverity { return .error } } @@ -45,17 +45,17 @@ public protocol ParserNote: NoteMessage { var noteID: MessageID { get } } -public extension ParserNote { +extension ParserNote { @available(*, deprecated, message: "Use noteID instead.", renamed: "noteID") - static var fixItID: MessageID { + public static var fixItID: MessageID { return Self.noteID } - static var noteID: MessageID { + public static var noteID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") } - var noteID: MessageID { + public var noteID: MessageID { return Self.noteID } } @@ -64,12 +64,12 @@ public protocol ParserFixIt: FixItMessage { var fixItID: MessageID { get } } -public extension ParserFixIt { - static var fixItID: MessageID { +extension ParserFixIt { + public static var fixItID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") } - var fixItID: MessageID { + public var fixItID: MessageID { return Self.fixItID } } @@ -104,12 +104,6 @@ extension DiagnosticMessage where Self == StaticParserError { public static var associatedTypeCannotUsePack: Self { .init("associated types cannot be variadic") } - public static var canImportWrongSecondParameterLabel: Self { - .init("2nd parameter of canImport should be labeled as _version or _underlyingVersion") - } - public static var canImportWrongNumberOfParameter: Self { - .init("canImport can take only two parameters") - } public static var caseOutsideOfSwitchOrEnum: Self { .init("'case' can only appear inside a 'switch' statement or 'enum' declaration") } @@ -278,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))" } } @@ -295,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'" } } @@ -345,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))" } } } @@ -378,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" } } @@ -386,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)'" } } @@ -546,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)" } } @@ -572,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/PresenceUtils.swift b/Sources/SwiftParserDiagnostics/PresenceUtils.swift index bab06afe40c..524f2c8f50f 100644 --- a/Sources/SwiftParserDiagnostics/PresenceUtils.swift +++ b/Sources/SwiftParserDiagnostics/PresenceUtils.swift @@ -10,9 +10,13 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftBasicFormat +@_spi(RawSyntax) internal import SwiftSyntax +#else import SwiftBasicFormat @_spi(RawSyntax) import SwiftSyntax - +#endif /// Walks a tree and checks whether the tree contained any present tokens. class PresentNodeChecker: SyntaxAnyVisitor { var hasPresentToken: Bool = false diff --git a/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift b/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift index 6cd050c0a52..38ee98bbe30 100644 --- a/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift +++ b/Sources/SwiftParserDiagnostics/SyntaxExtensions.swift @@ -10,9 +10,15 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftBasicFormat +@_spi(Diagnostics) internal import SwiftParser +@_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else import SwiftBasicFormat @_spi(Diagnostics) import SwiftParser @_spi(RawSyntax) @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif extension UnexpectedNodesSyntax { func presentTokens(satisfying isIncluded: (TokenSyntax) -> Bool) -> [TokenSyntax] { @@ -100,7 +106,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/SwiftParserDiagnostics/generated/ChildNameForDiagnostics.swift b/Sources/SwiftParserDiagnostics/generated/ChildNameForDiagnostics.swift index 56066b8547f..36983cf5462 100644 --- a/Sources/SwiftParserDiagnostics/generated/ChildNameForDiagnostics.swift +++ b/Sources/SwiftParserDiagnostics/generated/ChildNameForDiagnostics.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif private func childNameForDiagnostics(_ keyPath: AnyKeyPath) -> String? { switch keyPath { diff --git a/Sources/SwiftParserDiagnostics/generated/SyntaxKindNameForDiagnostics.swift b/Sources/SwiftParserDiagnostics/generated/SyntaxKindNameForDiagnostics.swift index 8b2ccf9935c..4006f445c54 100644 --- a/Sources/SwiftParserDiagnostics/generated/SyntaxKindNameForDiagnostics.swift +++ b/Sources/SwiftParserDiagnostics/generated/SyntaxKindNameForDiagnostics.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(ExperimentalLanguageFeatures) internal import SwiftSyntax +#else @_spi(ExperimentalLanguageFeatures) import SwiftSyntax +#endif extension SyntaxKind { var nameForDiagnostics: String? { @@ -61,7 +65,7 @@ extension SyntaxKind { return "'_borrow' expression" case .breakStmt: return "'break' statement" - case .canImportExpr: + case ._canImportExpr: return "'canImport' expression" case .catchClauseList: return "'catch' clause" diff --git a/Sources/SwiftParserDiagnostics/generated/TokenNameForDiagnostics.swift b/Sources/SwiftParserDiagnostics/generated/TokenNameForDiagnostics.swift index 24357b732db..a760feca88b 100644 --- a/Sources/SwiftParserDiagnostics/generated/TokenNameForDiagnostics.swift +++ b/Sources/SwiftParserDiagnostics/generated/TokenNameForDiagnostics.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +@_spi(RawSyntax) internal import SwiftSyntax +#else @_spi(RawSyntax) import SwiftSyntax +#endif extension TokenKind { var nameForDiagnostics: String { 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/SwiftRefactor/IntegerLiteralUtilities.swift b/Sources/SwiftRefactor/IntegerLiteralUtilities.swift index 187d800f807..6c2ad764188 100644 --- a/Sources/SwiftRefactor/IntegerLiteralUtilities.swift +++ b/Sources/SwiftRefactor/IntegerLiteralUtilities.swift @@ -17,7 +17,7 @@ import SwiftSyntax #endif extension IntegerLiteralExprSyntax { - public enum Radix { + public enum Radix: Sendable { case binary case octal case decimal diff --git a/Sources/SwiftSyntax/CMakeLists.txt b/Sources/SwiftSyntax/CMakeLists.txt index 23cdd2fbb59..617183bab6f 100644 --- a/Sources/SwiftSyntax/CMakeLists.txt +++ b/Sources/SwiftSyntax/CMakeLists.txt @@ -15,6 +15,7 @@ add_swift_syntax_library(SwiftSyntax CommonAncestor.swift Convenience.swift CustomTraits.swift + Identifier.swift MemoryLayout.swift MissingNodeInitializers.swift SourceEdit.swift @@ -29,6 +30,7 @@ add_swift_syntax_library(SwiftSyntax SyntaxCollection.swift SyntaxHashable.swift SyntaxIdentifier.swift + SyntaxNodeFactory.swift SyntaxNodeStructure.swift SyntaxProtocol.swift SyntaxText.swift @@ -81,3 +83,6 @@ add_swift_syntax_library(SwiftSyntax generated/syntaxNodes/SyntaxNodesQRS.swift generated/syntaxNodes/SyntaxNodesTUVWXYZ.swift ) + +target_link_swift_syntax_libraries(SwiftSyntax PRIVATE + _SwiftSyntaxCShims) diff --git a/Sources/SwiftSyntax/CommonAncestor.swift b/Sources/SwiftSyntax/CommonAncestor.swift index 59722f407b1..6ccffd627a2 100644 --- a/Sources/SwiftSyntax/CommonAncestor.swift +++ b/Sources/SwiftSyntax/CommonAncestor.swift @@ -18,11 +18,11 @@ public func findCommonAncestorOrSelf(_ lhs: Syntax, _ rhs: Syntax) -> Syntax? { if lhs == rhs { return lhs } - if let lhsIndex = lhs?.indexInParent.data?.indexInTree, let rhsIndex = rhs?.indexInParent.data?.indexInTree { - if lhsIndex < rhsIndex { - rhs = rhs?.parent + if let lhsUnwrapped = lhs, let rhsUnwrapped = rhs { + if lhsUnwrapped.id < rhsUnwrapped.id { + rhs = rhsUnwrapped.parent } else { - lhs = lhs?.parent + lhs = lhsUnwrapped.parent } } } diff --git a/Sources/SwiftSyntax/Documentation.docc/Contributing/ChangingSwiftSyntax.md b/Sources/SwiftSyntax/Documentation.docc/Contributing/ChangingSwiftSyntax.md index dfeabbfe5d4..af35b3564f5 100644 --- a/Sources/SwiftSyntax/Documentation.docc/Contributing/ChangingSwiftSyntax.md +++ b/Sources/SwiftSyntax/Documentation.docc/Contributing/ChangingSwiftSyntax.md @@ -73,9 +73,9 @@ nodes will need to be changed in tandem. For example, the system will not allow changes to SwiftSyntax that break `swift-stress-tester` without a paired change to that repository. -[SyntaxSupport]: https://github.com/apple/swift-syntax/tree/main/CodeGeneration/Sources/SyntaxSupport -[swift-stress-tester]: https://github.com/apple/swift-stress-tester -[ParserBasics]: https://github.com/apple/swift-syntax/tree/main/Sources/SwiftParser/SwiftParser.docc/ParsingBasics.md +[SyntaxSupport]: https://github.com/swiftlang/swift-syntax/tree/main/CodeGeneration/Sources/SyntaxSupport +[swift-stress-tester]: https://github.com/swiftlang/swift-stress-tester +[ParserBasics]: https://github.com/swiftlang/swift-syntax/tree/main/Sources/SwiftParser/SwiftParser.docc/ParsingBasics.md @Comment { When docc resolves https://github.com/apple/swift-docc/issues/255, `ParserBasic` should be an inter-target link. diff --git a/Sources/SwiftSyntax/Documentation.docc/Macro Versioning.md b/Sources/SwiftSyntax/Documentation.docc/Macro Versioning.md index ff25aa65329..fe96bc4a94d 100644 --- a/Sources/SwiftSyntax/Documentation.docc/Macro Versioning.md +++ b/Sources/SwiftSyntax/Documentation.docc/Macro Versioning.md @@ -15,7 +15,7 @@ For simplicity, this article assumes that 509 is the current swift-syntax versio Any given version macro can depend on multiple major swift-syntax versions at once. For example, if a macro supports both swift-syntax 509 and swift-syntax 510, it may declare its dependency on swift-syntax as ``` -.package(url: "https://github.com/apple/swift-syntax.git", "509.0.0"..<"511.0.0"), +.package(url: "https://github.com/swiftlang/swift-syntax.git", "509.0.0"..<"511.0.0"), ``` In order to handle breaking API changes, clients can wrap uses of such APIs in conditional compilation clauses that check the version of swift-syntax it is building against. All versions of swift-syntax ≥ 509 will include an empty `SwiftSyntaxVersion509` module, swift-syntax ≥ 510 will include both a `SwiftSyntaxVersion510` and `SwiftSyntaxVersion509` module, and so on for any new releases. This allows clients to write diff --git a/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step3.swift b/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step3.swift index 9bac75daa90..bb572c9659a 100644 --- a/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step3.swift +++ b/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step3.swift @@ -14,7 +14,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/apple/swift-syntax.git", branch: "main") + .package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main") ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. diff --git a/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step4.swift b/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step4.swift index 920de5f4bdd..131b4f36a90 100644 --- a/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step4.swift +++ b/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step4.swift @@ -14,7 +14,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/apple/swift-syntax.git", branch: "main") + .package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main") ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. diff --git a/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step5.swift b/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step5.swift index ea36b7480eb..dc392b00c05 100644 --- a/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step5.swift +++ b/Sources/SwiftSyntax/Documentation.docc/Resources/Package.step5.swift @@ -17,7 +17,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/apple/swift-syntax.git", branch: "main") + .package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main") ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. diff --git a/Sources/SwiftSyntax/Documentation.docc/generated/SwiftSyntax.md b/Sources/SwiftSyntax/Documentation.docc/generated/SwiftSyntax.md index 3ffec83b129..b43846641b6 100644 --- a/Sources/SwiftSyntax/Documentation.docc/generated/SwiftSyntax.md +++ b/Sources/SwiftSyntax/Documentation.docc/generated/SwiftSyntax.md @@ -102,8 +102,6 @@ These articles are intended for developers wishing to contribute to SwiftSyntax - - - -- -- - - - diff --git a/Sources/SwiftSyntax/Identifier.swift b/Sources/SwiftSyntax/Identifier.swift new file mode 100644 index 00000000000..0864e754744 --- /dev/null +++ b/Sources/SwiftSyntax/Identifier.swift @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +/// A canonicalized representation of an identifier that strips away backticks. +public struct Identifier: Equatable, Hashable, Sendable { + /// The sanitized `text` of a token. + public var name: String { + String(syntaxText: raw.name) + } + + @_spi(RawSyntax) + public let raw: RawIdentifier + + private let arena: SyntaxArenaRef + + public init?(_ token: TokenSyntax) { + guard case .identifier = token.tokenKind else { + return nil + } + + self.raw = RawIdentifier(token.tokenView) + self.arena = token.tokenView.raw.arenaReference + } +} + +@_spi(RawSyntax) +public struct RawIdentifier: Equatable, Hashable, Sendable { + public let name: SyntaxText + + @_spi(RawSyntax) + fileprivate init(_ raw: RawSyntaxTokenView) { + let backtick = SyntaxText("`") + if raw.rawText.count > 2 && raw.rawText.hasPrefix(backtick) && raw.rawText.hasSuffix(backtick) { + let startIndex = raw.rawText.index(after: raw.rawText.startIndex) + let endIndex = raw.rawText.index(before: raw.rawText.endIndex) + self.name = SyntaxText(rebasing: raw.rawText[startIndex..") ) } } -public extension MissingPatternSyntax { - init() { +extension MissingPatternSyntax { + public init() { self.init( placeholder: TokenSyntax.identifier("<#pattern#>") ) } } -public extension MissingStmtSyntax { - init() { +extension MissingStmtSyntax { + public init() { self.init( placeholder: TokenSyntax.identifier("<#statement#>") ) } } -public extension MissingTypeSyntax { - init() { +extension MissingTypeSyntax { + public init() { self.init( placeholder: TokenSyntax.identifier("<#type#>") ) } } -public extension MissingSyntax { - init() { +extension MissingSyntax { + public init() { self.init( placeholder: TokenSyntax.identifier("<#syntax#>") ) @@ -66,8 +66,8 @@ public extension MissingSyntax { // MARK: - Raw -public extension RawMissingDeclSyntax { - init( +extension RawMissingDeclSyntax { + public init( attributes: RawAttributeListSyntax, modifiers: RawDeclModifierListSyntax, arena: __shared SyntaxArena @@ -81,8 +81,8 @@ public extension RawMissingDeclSyntax { } } -public extension RawMissingExprSyntax { - init(arena: __shared SyntaxArena) { +extension RawMissingExprSyntax { + public init(arena: __shared SyntaxArena) { self.init( placeholder: RawTokenSyntax(missing: .identifier, text: "<#expression#>", arena: arena), arena: arena @@ -90,8 +90,8 @@ public extension RawMissingExprSyntax { } } -public extension RawMissingPatternSyntax { - init(arena: __shared SyntaxArena) { +extension RawMissingPatternSyntax { + public init(arena: __shared SyntaxArena) { self.init( placeholder: RawTokenSyntax(missing: .identifier, text: "<#pattern#>", arena: arena), arena: arena @@ -99,8 +99,8 @@ public extension RawMissingPatternSyntax { } } -public extension RawMissingStmtSyntax { - init(arena: __shared SyntaxArena) { +extension RawMissingStmtSyntax { + public init(arena: __shared SyntaxArena) { self.init( placeholder: RawTokenSyntax(missing: .identifier, text: "<#statement#>", arena: arena), arena: arena @@ -108,8 +108,8 @@ public extension RawMissingStmtSyntax { } } -public extension RawMissingTypeSyntax { - init(arena: __shared SyntaxArena) { +extension RawMissingTypeSyntax { + public init(arena: __shared SyntaxArena) { self.init( placeholder: RawTokenSyntax(missing: .identifier, text: "<#type#>", arena: arena), arena: arena @@ -117,8 +117,8 @@ public extension RawMissingTypeSyntax { } } -public extension RawMissingSyntax { - init(arena: __shared SyntaxArena) { +extension RawMissingSyntax { + public init(arena: __shared SyntaxArena) { self.init( placeholder: RawTokenSyntax(missing: .identifier, text: "<#syntax#>", arena: arena), arena: arena 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/Raw/RawSyntaxNodeProtocol.swift b/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift index e63d1027111..8b30f9b312e 100644 --- a/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift +++ b/Sources/SwiftSyntax/Raw/RawSyntaxNodeProtocol.swift @@ -24,30 +24,30 @@ public protocol RawSyntaxNodeProtocol: CustomStringConvertible, TextOutputStream init?(_ other: some RawSyntaxNodeProtocol) } -public extension RawSyntaxNodeProtocol { +extension RawSyntaxNodeProtocol { /// Cast to the specified raw syntax type if possible. - func `as`(_: Node.Type) -> Node? { + public func `as`(_: Node.Type) -> Node? { Node(self) } /// Check if this instance can be cast to the specified syntax type. - func `is`(_: Node.Type) -> Bool { + public func `is`(_: Node.Type) -> Bool { Node.isKindOf(self.raw) } - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { return self.as(S.self)! } - var description: String { + public var description: String { raw.description } - func write(to target: inout some TextOutputStream) { + public func write(to target: inout some TextOutputStream) { raw.write(to: &target) } - var isEmpty: Bool { + public var isEmpty: Bool { return raw.byteLength == 0 } @@ -55,7 +55,7 @@ public extension RawSyntaxNodeProtocol { /// - missing nodes or /// - unexpected nodes or /// - tokens with a ``TokenDiagnostic`` of severity `error` - var hasError: Bool { + public var hasError: Bool { return raw.recursiveFlags.contains(.hasError) } } diff --git a/Sources/SwiftSyntax/SourceLocation.swift b/Sources/SwiftSyntax/SourceLocation.swift index 92cd90bbbf1..4a95ca77d53 100644 --- a/Sources/SwiftSyntax/SourceLocation.swift +++ b/Sources/SwiftSyntax/SourceLocation.swift @@ -103,22 +103,6 @@ public struct SourceRange: Hashable, Codable, Sendable { } } -/// Collects all `PoundSourceLocationSyntax` directives in a file. -fileprivate class SourceLocationCollector: SyntaxVisitor { - private var sourceLocationDirectives: [PoundSourceLocationSyntax] = [] - - override func visit(_ node: PoundSourceLocationSyntax) -> SyntaxVisitorContinueKind { - sourceLocationDirectives.append(node) - return .skipChildren - } - - static func collectSourceLocations(in tree: some SyntaxProtocol) -> [PoundSourceLocationSyntax] { - let collector = SourceLocationCollector(viewMode: .sourceAccurate) - collector.walk(tree) - return collector.sourceLocationDirectives - } -} - fileprivate struct SourceLocationDirectiveArguments { enum Error: Swift.Error, CustomStringConvertible { case nonDecimalLineNumber(TokenSyntax) @@ -157,7 +141,7 @@ fileprivate struct SourceLocationDirectiveArguments { /// Converts ``AbsolutePosition``s of syntax nodes to ``SourceLocation``s, and /// vice-versa. The ``AbsolutePosition``s must be originating from nodes that are /// part of the same tree that was used to initialize this class. -public final class SourceLocationConverter { +public final class SourceLocationConverter: Sendable { private let fileName: String /// The source of the file, modeled as data so it can contain invalid UTF-8. private let source: [UInt8] @@ -169,11 +153,11 @@ public final class SourceLocationConverter { /// The information from all `#sourceLocation` directives in the file /// necessary to compute presumed locations. /// - /// - `sourceLine` is the line at which the `#sourceLocation` statement occurs - /// within the current file. + /// - `sourceLine` is the physical line number of the end of the last token of + /// `#sourceLocation(...)` directive within the current file. /// - `arguments` are the `file` and `line` arguments of the directive or `nil` /// if spelled as `#sourceLocation()` to reset the source location directive. - private var sourceLocationDirectives: [(sourceLine: Int, arguments: SourceLocationDirectiveArguments?)] = [] + private let sourceLocationDirectives: [(sourceLine: Int, arguments: SourceLocationDirectiveArguments?)] /// Create a new ``SourceLocationConverter`` to convert between ``AbsolutePosition`` /// and ``SourceLocation`` in a syntax tree. @@ -189,21 +173,7 @@ public final class SourceLocationConverter { precondition(tree.parent == nil, "SourceLocationConverter must be passed the root of the syntax tree") self.fileName = fileName self.source = tree.syntaxTextBytes - (self.lines, endOfFile) = computeLines(tree: Syntax(tree)) - precondition(tree.totalLength.utf8Length == endOfFile.utf8Offset) - - for directive in SourceLocationCollector.collectSourceLocations(in: tree) { - let location = self.physicalLocation(for: directive.positionAfterSkippingLeadingTrivia) - if let args = directive.arguments { - if let parsedArgs = try? SourceLocationDirectiveArguments(args) { - // Ignore any malformed `#sourceLocation` directives. - sourceLocationDirectives.append((sourceLine: location.line, arguments: parsedArgs)) - } - } else { - // `#sourceLocation()` without any arguments resets the `#sourceLocation` directive. - sourceLocationDirectives.append((sourceLine: location.line, arguments: nil)) - } - } + (self.lines, self.endOfFile, self.sourceLocationDirectives) = computeLines(tree: Syntax(tree)) } /// Create a new ``SourceLocationConverter`` to convert between ``AbsolutePosition`` @@ -242,6 +212,7 @@ public final class SourceLocationConverter { return computeLines(SyntaxText(buffer: syntaxArenaBuf)) } precondition(source.utf8.count == endOfFile.utf8Offset) + self.sourceLocationDirectives = [] } /// Execute the body with an array that contains each source line. @@ -278,7 +249,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 @@ -392,14 +365,14 @@ public final class SourceLocationConverter { } } -public extension Syntax { +extension Syntax { /// The starting location, in the provided file, of this Syntax node. /// - Parameters: /// - converter: The `SourceLocationConverter` that was previously /// initialized using the root tree of this node. /// - afterLeadingTrivia: Whether to skip leading trivia when getting /// the node's location. Defaults to `true`. - func startLocation( + public func startLocation( converter: SourceLocationConverter, afterLeadingTrivia: Bool = true ) -> SourceLocation { @@ -413,7 +386,7 @@ public extension Syntax { /// initialized using the root tree of this node. /// - afterTrailingTrivia: Whether to skip trailing trivia when getting /// the node's location. Defaults to `false`. - func endLocation( + public func endLocation( converter: SourceLocationConverter, afterTrailingTrivia: Bool = false ) -> SourceLocation { @@ -434,7 +407,7 @@ public extension Syntax { /// the node's start location. Defaults to `true`. /// - afterTrailingTrivia: Whether to skip trailing trivia when getting /// the node's end location. Defaults to `false`. - func sourceRange( + public func sourceRange( converter: SourceLocationConverter, afterLeadingTrivia: Bool = true, afterTrailingTrivia: Bool = false @@ -451,14 +424,14 @@ public extension Syntax { } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// The starting location, in the provided file, of this Syntax node. /// - Parameters: /// - converter: The `SourceLocationConverter` that was previously /// initialized using the root tree of this node. /// - afterLeadingTrivia: Whether to skip leading trivia when getting /// the node's location. Defaults to `true`. - func startLocation( + public func startLocation( converter: SourceLocationConverter, afterLeadingTrivia: Bool = true ) -> SourceLocation { @@ -474,7 +447,7 @@ public extension SyntaxProtocol { /// initialized using the root tree of this node. /// - afterTrailingTrivia: Whether to skip trailing trivia when getting /// the node's location. Defaults to `false`. - func endLocation( + public func endLocation( converter: SourceLocationConverter, afterTrailingTrivia: Bool = false ) -> SourceLocation { @@ -492,7 +465,7 @@ public extension SyntaxProtocol { /// the node's start location. Defaults to `true`. /// - afterTrailingTrivia: Whether to skip trailing trivia when getting /// the node's end location. Defaults to `false`. - func sourceRange( + public func sourceRange( converter: SourceLocationConverter, afterLeadingTrivia: Bool = true, afterTrailingTrivia: Bool = false @@ -509,21 +482,21 @@ public extension SyntaxProtocol { /// the end-of-file position. fileprivate func computeLines( tree: Syntax -) -> ([AbsolutePosition], AbsolutePosition) { - var lines: [AbsolutePosition] = [] - // First line starts from the beginning. - lines.append(.startOfFile) +) -> ( + lines: [AbsolutePosition], + endOfFile: AbsolutePosition, + sourceLocationDirectives: [(sourceLine: Int, arguments: SourceLocationDirectiveArguments?)] +) { + var lines: [AbsolutePosition] = [.startOfFile] var position: AbsolutePosition = .startOfFile - let addLine = { (lineLength: SourceLength) in + var sourceLocationDirectives: [(sourceLine: Int, arguments: SourceLocationDirectiveArguments?)] = [] + let lastLineLength = tree.raw.forEachLineLength { lineLength in position += lineLength lines.append(position) + } handleSourceLocationDirective: { lineOffset, args in + sourceLocationDirectives.append((sourceLine: lines.count + lineOffset, arguments: args)) } - var curPrefix: SourceLength = .zero - for token in tree.tokens(viewMode: .sourceAccurate) { - curPrefix = token.forEachLineLength(prefix: curPrefix, body: addLine) - } - position += curPrefix - return (lines, position) + return (lines, position + lastLineLength, sourceLocationDirectives) } fileprivate func computeLines(_ source: SyntaxText) -> ([AbsolutePosition], AbsolutePosition) { @@ -634,7 +607,7 @@ fileprivate extension RawTriviaPiece { } } -fileprivate extension Array where Element == RawTriviaPiece { +fileprivate extension RawTriviaPieceBuffer { /// Walks and passes to `body` the ``SourceLength`` for every detected line, /// with the newline character included. /// - Returns: The leftover ``SourceLength`` at the end of the walk. @@ -650,18 +623,61 @@ fileprivate extension Array where Element == RawTriviaPiece { } } -fileprivate extension TokenSyntax { +fileprivate extension RawSyntax { /// Walks and passes to `body` the ``SourceLength`` for every detected line, /// with the newline character included. /// - Returns: The leftover ``SourceLength`` at the end of the walk. func forEachLineLength( prefix: SourceLength = .zero, - body: (SourceLength) -> () + body: (SourceLength) -> (), + handleSourceLocationDirective: (_ lineOffset: Int, _ arguments: SourceLocationDirectiveArguments?) -> () ) -> SourceLength { var curPrefix = prefix - curPrefix = self.tokenView.leadingRawTriviaPieces.forEachLineLength(prefix: curPrefix, body: body) - curPrefix = self.tokenView.rawText.forEachLineLength(prefix: curPrefix, body: body) - curPrefix = self.tokenView.trailingRawTriviaPieces.forEachLineLength(prefix: curPrefix, body: body) + switch self.rawData.payload { + case .parsedToken(let dat): + curPrefix = dat.wholeText.forEachLineLength(prefix: curPrefix, body: body) + case .materializedToken(let dat): + curPrefix = dat.leadingTrivia.forEachLineLength(prefix: curPrefix, body: body) + curPrefix = dat.tokenText.forEachLineLength(prefix: curPrefix, body: body) + curPrefix = dat.trailingTrivia.forEachLineLength(prefix: curPrefix, body: body) + case .layout(let dat): + for case let node? in dat.layout where SyntaxTreeViewMode.sourceAccurate.shouldTraverse(node: node) { + curPrefix = node.forEachLineLength( + prefix: curPrefix, + body: body, + handleSourceLocationDirective: handleSourceLocationDirective + ) + } + + // Handle '#sourceLocation' directive. + if dat.kind == .poundSourceLocation { + // Count newlines in the trailing trivia. The client want to get the + // line of the _end_ of '#sourceLocation()' directive. + var lineOffset = 0 + if let lastTok = self.lastToken(viewMode: .sourceAccurate) { + switch lastTok.raw.rawData.payload { + case .parsedToken(let dat): + _ = dat.trailingTriviaText.forEachLineLength(body: { _ in lineOffset -= 1 }) + case .materializedToken(let dat): + _ = dat.trailingTrivia.forEachLineLength(body: { _ in lineOffset -= 1 }) + case .layout(_): + preconditionFailure("lastToken(viewMode:) returned non-token") + } + } + + let directive = Syntax.forRoot(self, rawNodeArena: self.arenaReference.retained) + .cast(PoundSourceLocationSyntax.self) + if let args = directive.arguments { + if let parsedArgs = try? SourceLocationDirectiveArguments(args) { + // Ignore any malformed `#sourceLocation` directives. + handleSourceLocationDirective(lineOffset, parsedArgs) + } + } else { + // `#sourceLocation()` without any arguments resets the `#sourceLocation` directive. + handleSourceLocationDirective(lineOffset, nil) + } + } + } return curPrefix } } diff --git a/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift b/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift index 7a53e412650..7790fa566fc 100644 --- a/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift +++ b/Sources/SwiftSyntax/SwiftSyntaxCompatibility.swift @@ -13,10 +13,10 @@ // This file provides compatibility aliases to keep dependents of SwiftSyntax building. // All users of the declarations in this file should transition away from them ASAP. -public extension AccessorEffectSpecifiersSyntax { +extension AccessorEffectSpecifiersSyntax { @_disfavoredOverload @available(*, deprecated, message: "use throwsClause instead of throwsSpecifier") - init( + public init( leadingTrivia: Trivia? = nil, _ unexpectedBeforeAsyncSpecifier: UnexpectedNodesSyntax? = nil, asyncSpecifier: TokenSyntax? = nil, @@ -132,9 +132,9 @@ extension ClosureSignatureSyntax.ParameterClause { } } -public extension DeclGroupSyntax { +extension DeclGroupSyntax { @available(*, deprecated, renamed: "memberBlock") - var members: MemberDeclBlockSyntax { + public var members: MemberDeclBlockSyntax { get { return memberBlock } @@ -144,15 +144,15 @@ public extension DeclGroupSyntax { } } -public extension EffectSpecifiersSyntax { +extension EffectSpecifiersSyntax { @available(*, deprecated, renamed: "unexpectedBetweenAsyncSpecifierAndThrowsClause") - var unexpectedBetweenAsyncSpecifierAndThrowsSpecifier: UnexpectedNodesSyntax? { + public var unexpectedBetweenAsyncSpecifierAndThrowsSpecifier: UnexpectedNodesSyntax? { get { unexpectedBetweenAsyncSpecifierAndThrowsClause } set { unexpectedBetweenAsyncSpecifierAndThrowsClause = newValue } } @available(*, deprecated, message: "use throwsClause.throwsSpecifier") - var throwsSpecifier: TokenSyntax? { + public var throwsSpecifier: TokenSyntax? { get { throwsClause?.throwsSpecifier } set { @@ -170,16 +170,16 @@ public extension EffectSpecifiersSyntax { } @available(*, deprecated, renamed: "unexpectedAfterThrowsClause") - var unexpectedAfterThrowsSpecifier: UnexpectedNodesSyntax? { + public var unexpectedAfterThrowsSpecifier: UnexpectedNodesSyntax? { get { unexpectedAfterThrowsClause } set { unexpectedAfterThrowsClause = newValue } } } -public extension FunctionEffectSpecifiersSyntax { +extension FunctionEffectSpecifiersSyntax { @_disfavoredOverload @available(*, deprecated, message: "use throwsClause instead of throwsSpecifier") - init( + public init( leadingTrivia: Trivia? = nil, _ unexpectedBeforeAsyncSpecifier: UnexpectedNodesSyntax? = nil, asyncSpecifier: TokenSyntax? = nil, @@ -200,9 +200,9 @@ public extension FunctionEffectSpecifiersSyntax { } } -public extension FreestandingMacroExpansionSyntax { +extension FreestandingMacroExpansionSyntax { @available(*, deprecated, renamed: "pound") - var poundToken: TokenSyntax { + public var poundToken: TokenSyntax { get { return pound } @@ -212,7 +212,7 @@ public extension FreestandingMacroExpansionSyntax { } @available(*, deprecated, renamed: "macroName") - var macro: TokenSyntax { + public var macro: TokenSyntax { get { return macroName } @@ -222,7 +222,7 @@ public extension FreestandingMacroExpansionSyntax { } @available(*, deprecated, renamed: "genericArgumentClause") - var genericArguments: GenericArgumentClauseSyntax? { + public var genericArguments: GenericArgumentClauseSyntax? { get { return genericArgumentClause } @@ -232,7 +232,7 @@ public extension FreestandingMacroExpansionSyntax { } @available(*, deprecated, renamed: "arguments") - var argumentList: LabeledExprListSyntax { + public var argumentList: LabeledExprListSyntax { get { return arguments } @@ -339,81 +339,81 @@ extension MemberAccessExprSyntax { } } -public extension SyntaxProtocol { +extension SyntaxProtocol { @available(*, deprecated, message: "Use detached computed property instead.") - func detach() -> Self { + public func detach() -> Self { return detached } } -public extension TokenKind { +extension TokenKind { @available(*, deprecated, renamed: "regexPoundDelimiter") - static func extendedRegexDelimiter(_ text: String) -> TokenKind { + public static func extendedRegexDelimiter(_ text: String) -> TokenKind { return .regexPoundDelimiter(text) } @available(*, deprecated, renamed: "floatLiteral") - static func floatingLiteral(_ text: String) -> TokenKind { + public static func floatingLiteral(_ text: String) -> TokenKind { return .floatLiteral(text) } @available(*, deprecated, renamed: "leftSquare") - static var leftSquareBracket: TokenKind { + public static var leftSquareBracket: TokenKind { return .leftSquare } @available(*, deprecated, renamed: "poundAvailable") - static var poundAvailableKeyword: TokenKind { + public static var poundAvailableKeyword: TokenKind { return .poundAvailable } @available(*, deprecated, renamed: "poundElse") - static var poundElseKeyword: TokenKind { + public static var poundElseKeyword: TokenKind { return .poundElse } @available(*, deprecated, renamed: "poundElseif") - static var poundElseifKeyword: TokenKind { + public static var poundElseifKeyword: TokenKind { return .poundElseif } @available(*, deprecated, renamed: "poundEndif") - static var poundEndifKeyword: TokenKind { + public static var poundEndifKeyword: TokenKind { return .poundEndif } @available(*, deprecated, renamed: "poundIf") - static var poundIfKeyword: TokenKind { + public static var poundIfKeyword: TokenKind { return .poundIf } @available(*, deprecated, renamed: "poundSourceLocation") - static var poundSourceLocationKeyword: TokenKind { + public static var poundSourceLocationKeyword: TokenKind { return .poundSourceLocation } @available(*, deprecated, renamed: "poundUnavailable") - static var poundUnavailableKeyword: TokenKind { + public static var poundUnavailableKeyword: TokenKind { return .poundUnavailable } @available(*, deprecated, renamed: "rawStringPoundDelimiter") - static func rawStringDelimiter(_ text: String) -> TokenKind { + public static func rawStringDelimiter(_ text: String) -> TokenKind { return .rawStringPoundDelimiter(text) } @available(*, deprecated, renamed: "rightSquare") - static var rightSquareBracket: TokenKind { + public static var rightSquareBracket: TokenKind { return .rightSquare } @available(*, deprecated, renamed: "endOfFile") - static var eof: TokenKind { .endOfFile } + public static var eof: TokenKind { .endOfFile } } -public extension TokenSyntax { +extension TokenSyntax { @available(*, deprecated, renamed: "regexPoundDelimiter") - static func extendedRegexDelimiter( + public static func extendedRegexDelimiter( _ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], @@ -428,7 +428,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "floatLiteral") - static func floatingLiteral( + public static func floatingLiteral( _ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], @@ -443,7 +443,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "leftSquareToken") - static func leftSquareBracketToken( + public static func leftSquareBracketToken( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -456,7 +456,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundAvailableToken") - static func poundAvailableKeyword( + public static func poundAvailableKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -469,7 +469,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundElseToken") - static func poundElseKeyword( + public static func poundElseKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -482,7 +482,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundElseifToken") - static func poundElseifKeyword( + public static func poundElseifKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -495,7 +495,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundEndifToken") - static func poundEndifKeyword( + public static func poundEndifKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -508,7 +508,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundIfToken") - static func poundIfKeyword( + public static func poundIfKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -521,7 +521,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundSourceLocationToken") - static func poundSourceLocationKeyword( + public static func poundSourceLocationKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -534,7 +534,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "poundUnavailableToken") - static func poundUnavailableKeyword( + public static func poundUnavailableKeyword( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -547,7 +547,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "rawStringPoundDelimiter") - static func rawStringDelimiter( + public static func rawStringDelimiter( _ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], @@ -562,7 +562,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "rightSquareToken") - static func rightSquareBracketToken( + public static func rightSquareBracketToken( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -575,7 +575,7 @@ public extension TokenSyntax { } @available(*, deprecated, renamed: "endOfFileToken") - static func eof( + public static func eof( leadingTrivia: Trivia = [], trailingTrivia: Trivia = [], presence: SourcePresence = .present @@ -588,9 +588,9 @@ public extension TokenSyntax { } } -public extension TypeEffectSpecifiersSyntax { +extension TypeEffectSpecifiersSyntax { @available(*, deprecated, message: "use throwsClause instead of throwsSpecifier") - init( + public init( leadingTrivia: Trivia? = nil, _ unexpectedBeforeAsyncSpecifier: UnexpectedNodesSyntax? = nil, asyncSpecifier: TokenSyntax? = nil, @@ -611,9 +611,9 @@ public extension TypeEffectSpecifiersSyntax { } } -public extension WildcardPatternSyntax { +extension WildcardPatternSyntax { @available(*, deprecated, message: "remove 'typeAnnotation'") - init( + public init( leadingTrivia: Trivia? = nil, _ unexpectedBeforeWildcard: UnexpectedNodesSyntax? = nil, wildcard: TokenSyntax = .wildcardToken(), @@ -632,19 +632,19 @@ public extension WildcardPatternSyntax { } @available(*, deprecated, message: "'unexpectedBetweenWildcardAndTypeAnnotation' was removed") - var unexpectedBetweenWildcardAndTypeAnnotation: UnexpectedNodesSyntax? { + public var unexpectedBetweenWildcardAndTypeAnnotation: UnexpectedNodesSyntax? { get { nil } set {} } @available(*, deprecated, message: "'typeAnnotation' was removed") - var typeAnnotation: TypeAnnotationSyntax? { + public var typeAnnotation: TypeAnnotationSyntax? { get { nil } set {} } @available(*, deprecated, renamed: "unexpectedAfterWildcard") - var unexpectedAfterTypeAnnotation: UnexpectedNodesSyntax? { + public var unexpectedAfterTypeAnnotation: UnexpectedNodesSyntax? { get { unexpectedAfterWildcard } set { unexpectedAfterWildcard = newValue } } diff --git a/Sources/SwiftSyntax/Syntax.swift b/Sources/SwiftSyntax/Syntax.swift index 4fce60526fe..f6051f85ec5 100644 --- a/Sources/SwiftSyntax/Syntax.swift +++ b/Sources/SwiftSyntax/Syntax.swift @@ -14,10 +14,13 @@ /// Each node has accessors for its known children, and allows efficient /// iteration over the children through its `children` property. public struct Syntax: SyntaxProtocol, SyntaxHashable { - fileprivate enum Info: Sendable { - case root(Root) - indirect case nonRoot(NonRoot) - + /// We need a heap indirection to store a syntax node's parent. We could use an indirect enum here but explicitly + /// modelling it using a class allows us to re-use these heap-allocated objects in `SyntaxVisitor`. + /// + /// - Note: `@unchecked Sendable` because `info` is mutable. In Swift 6 and above the variable can be declared as + /// `nonisolated(unsafe)` but that attribute doesn't exist in previous Swift versions and a checked Sendable + /// conformance generates a warning. + final class Info: @unchecked Sendable { // For root node. struct Root: Sendable { private var arena: RetainedSyntaxArena @@ -32,27 +35,54 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { var parent: Syntax var absoluteInfo: AbsoluteSyntaxInfo } + + enum InfoImpl: Sendable { + case root(Root) + case nonRoot(NonRoot) + } + + init(_ info: InfoImpl) { + self.info = info + } + + /// The actual stored information that references the parent or the tree's root. + /// + /// - Important: Must only be set to `nil` when `Syntax.Info` is used in a memory recycling pool + /// (eg. in `SyntaxVisitor`). In that case the `Syntax.Info` is considered garbage memory that can be re-used + /// later. `info` needs to be set to a real value when `Syntax.Info` is recycled from the memory recycling pool. + #if compiler(>=6.0) + nonisolated(unsafe) var info: InfoImpl! + #else + var info: InfoImpl! + #endif } - private let info: Info + /// Reference to the node's parent or, if this node is the root of a tree, a reference to the `SyntaxArena` to keep + /// the syntax tree alive. + /// + /// - Important: In almost all use cases you should not access this directly. Prefer accessors like `parent`. + /// - Important: Must only be set to `nil` when this `Syntax` node is known to get destroyed and the `Info` should be + /// stored in a memory recycling pool (eg. in `SyntaxVisitor`). After setting `info` to `nil`, this `Syntax` node + /// is considered garbage and should not be accessed anymore in any way. + var info: Info! let raw: RawSyntax private var rootInfo: Info.Root { - switch info { + switch info.info! { case .root(let info): return info case .nonRoot(let info): return info.parent.rootInfo } } private var nonRootInfo: Info.NonRoot? { - switch info { + switch info.info! { case .root(_): return nil case .nonRoot(let info): return info } } private var root: Syntax { - switch info { + switch info.info! { case .root(_): return self case .nonRoot(let info): return info.parent.root } @@ -99,13 +129,13 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { } /// "designated" memberwise initializer of `Syntax`. - private init(_ raw: RawSyntax, info: Info) { + init(_ raw: RawSyntax, info: Info) { self.raw = raw self.info = info } init(_ raw: RawSyntax, parent: Syntax, absoluteInfo: AbsoluteSyntaxInfo) { - self.init(raw, info: .nonRoot(.init(parent: parent, absoluteInfo: absoluteInfo))) + self.init(raw, info: Info(.nonRoot(.init(parent: parent, absoluteInfo: absoluteInfo)))) } /// Creates a `Syntax` with the provided raw syntax and parent. @@ -125,12 +155,12 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { /// has a chance to retain it. static func forRoot(_ raw: RawSyntax, rawNodeArena: RetainedSyntaxArena) -> Syntax { precondition(rawNodeArena == raw.arenaReference) - return Syntax(raw, info: .root(.init(arena: rawNodeArena))) + return Syntax(raw, info: Info(.root(.init(arena: rawNodeArena)))) } static func forRoot(_ raw: RawSyntax, rawNodeArena: SyntaxArena) -> Syntax { precondition(rawNodeArena == raw.arenaReference) - return Syntax(raw, info: .root(.init(arena: RetainedSyntaxArena(rawNodeArena)))) + return Syntax(raw, info: Info(.root(.init(arena: RetainedSyntaxArena(rawNodeArena))))) } /// Returns the child data at the provided index in this data's layout. @@ -165,7 +195,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. @@ -185,7 +220,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 @@ -197,8 +237,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)` @@ -206,7 +256,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 + ) } } @@ -252,17 +307,20 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable { } /// Create a ``Syntax`` node from a specialized syntax node. - public init(_ syntax: some SyntaxProtocol) { + // Inline always so the optimizer can optimize this to a member access on `syntax` without having to go through + // generics. + @inline(__always) + public init(_ syntax: __shared some SyntaxProtocol) { self = syntax._syntaxNode } /// Creates a new ``Syntax`` node from any node that conforms to ``SyntaxProtocol``. - public init(fromProtocol syntax: SyntaxProtocol) { + public init(fromProtocol syntax: __shared SyntaxProtocol) { self = syntax._syntaxNode } /// Same as ``init(fromProtocol:)`` but returns `nil` if `syntax` is `nil`. - public init?(fromProtocol syntax: SyntaxProtocol?) { + public init?(fromProtocol syntax: __shared SyntaxProtocol?) { guard let syntax = syntax else { return nil } self = syntax._syntaxNode } diff --git a/Sources/SwiftSyntax/SyntaxArena.swift b/Sources/SwiftSyntax/SyntaxArena.swift index af924ddea07..56e57327810 100644 --- a/Sources/SwiftSyntax/SyntaxArena.swift +++ b/Sources/SwiftSyntax/SyntaxArena.swift @@ -10,21 +10,10 @@ // //===----------------------------------------------------------------------===// -#if SWIFT_SYNTAX_BUILD_USING_CMAKE -// The CMake bulid of swift-syntax does not build the _AtomicBool module because swift-syntax's CMake build is -// Swift-only. Fake an `AtomicBool` type that is not actually atomic. This should be acceptable for the following -// reasons: -// - `AtomicBool` is only used for the `hasParent` assertion, so release compilers don't rely on it -// - The compiler is single-threaded so it it is safe from race conditions on `AtomicBool`. -fileprivate struct AtomicBool { - var value: Bool - - init(initialValue: Bool) { - self.value = initialValue - } -} +#if swift(>=6.0) +private import _SwiftSyntaxCShims #else -import _AtomicBool +@_implementationOnly import _SwiftSyntaxCShims #endif /// A syntax arena owns the memory for all syntax nodes within it. @@ -69,7 +58,7 @@ public class SyntaxArena { /// /// - Important: This is only intended to be used for assertions to catch /// retain cycles in syntax arenas. - fileprivate var hasParent: AtomicBool + fileprivate let hasParent: UnsafeMutablePointer #endif /// Construct a new ``SyntaxArena`` in which syntax nodes can be allocated. @@ -81,7 +70,7 @@ public class SyntaxArena { self.allocator = BumpPtrAllocator(initialSlabSize: slabSize) self.childRefs = [] #if DEBUG || SWIFTSYNTAX_ENABLE_ASSERTIONS - self.hasParent = AtomicBool(initialValue: false) + self.hasParent = swiftsyntax_atomic_bool_create(false) #endif } @@ -89,6 +78,9 @@ public class SyntaxArena { for child in childRefs { child.release() } + #if DEBUG || SWIFTSYNTAX_ENABLE_ASSERTIONS + swiftsyntax_atomic_bool_destroy(self.hasParent) + #endif } /// Allocates a buffer of `RawSyntax?` with the given count, then returns the @@ -158,7 +150,7 @@ public class SyntaxArena { #if DEBUG || SWIFTSYNTAX_ENABLE_ASSERTIONS precondition( - !self.hasParent.value, + !swiftsyntax_atomic_bool_get(self.hasParent), "an arena can't have a new child once it's owned by other arenas" ) #endif @@ -300,14 +292,14 @@ struct SyntaxArenaRef: Hashable, @unchecked Sendable { } #if DEBUG || SWIFTSYNTAX_ENABLE_ASSERTIONS - /// Accessor for ther underlying's `SyntaxArena.hasParent` + /// Accessor for the underlying's `SyntaxArena.hasParent` var hasParent: Bool { - value.hasParent.value + swiftsyntax_atomic_bool_get(value.hasParent) } /// Sets the `SyntaxArena.hasParent` on the referenced arena. func setHasParent(_ newValue: Bool) { - value.hasParent.value = newValue + swiftsyntax_atomic_bool_set(value.hasParent, newValue) } #endif diff --git a/Sources/SwiftSyntax/SyntaxArenaAllocatedBuffer.swift b/Sources/SwiftSyntax/SyntaxArenaAllocatedBuffer.swift index d8b46a38e72..03b084e6cfd 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])) } @@ -103,4 +107,8 @@ var unsafeRawBufferPointer: UnsafeRawBufferPointer { return UnsafeRawBufferPointer(buffer) } + + public func withContiguousStorageIfAvailable(_ body: (UnsafeBufferPointer) throws -> R) rethrows -> R? { + try body(buffer) + } } diff --git a/Sources/SwiftSyntax/SyntaxChildren.swift b/Sources/SwiftSyntax/SyntaxChildren.swift index db14ccb672b..5457797679a 100644 --- a/Sources/SwiftSyntax/SyntaxChildren.swift +++ b/Sources/SwiftSyntax/SyntaxChildren.swift @@ -22,8 +22,8 @@ struct SyntaxChildrenIndexData: Hashable, Comparable, Sendable { /// See `AbsoluteSyntaxPosition.indexInParent` let indexInParent: UInt32 /// Unique value for a node within its own tree. - /// See `SyntaxIdentifier.indexIntree` - let indexInTree: SyntaxIndexInTree + /// See ``SyntaxIdentifier/indexInTree`` + let indexInTree: SyntaxIdentifier.SyntaxIndexInTree static func < ( lhs: SyntaxChildrenIndexData, @@ -35,7 +35,7 @@ struct SyntaxChildrenIndexData: Hashable, Comparable, Sendable { fileprivate init( offset: UInt32, indexInParent: UInt32, - indexInTree: SyntaxIndexInTree + indexInTree: SyntaxIdentifier.SyntaxIndexInTree ) { self.offset = offset self.indexInParent = indexInParent @@ -72,7 +72,7 @@ public struct SyntaxChildrenIndex: Hashable, Comparable, ExpressibleByNilLiteral fileprivate init( offset: UInt32, indexInParent: UInt32, - indexInTree: SyntaxIndexInTree + indexInTree: SyntaxIdentifier.SyntaxIndexInTree ) { self.data = SyntaxChildrenIndexData( offset: offset, @@ -222,7 +222,7 @@ struct RawSyntaxChildren: BidirectionalCollection, Sendable { let offset = startIndex.offset + UInt32(parent.totalLength.utf8Length) let indexInParent = startIndex.indexInParent + UInt32(parentLayoutView.children.count) let indexInTree = startIndex.indexInTree.indexInTree + UInt32(parent.totalNodes) - 1 - let syntaxIndexInTree = SyntaxIndexInTree(indexInTree: indexInTree) + let syntaxIndexInTree = SyntaxIdentifier.SyntaxIndexInTree(indexInTree: indexInTree) let materialized = SyntaxChildrenIndex( offset: offset, indexInParent: indexInParent, @@ -274,7 +274,7 @@ struct RawSyntaxChildren: BidirectionalCollection, Sendable { } } - init(_ base: Syntax) { + init(_ base: __shared Syntax) { self.init(base.absoluteRaw) } } @@ -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) } } @@ -411,6 +414,8 @@ struct NonNilRawSyntaxChildren: BidirectionalCollection, Sendable { self.viewMode = viewMode } + /// - Note: Inline so we don't retain `Syntax.Info` when creating `NonNilRawSyntaxChildren` from a `Syntax`. + @inline(__always) init(_ node: Syntax, viewMode: SyntaxTreeViewMode) { self.init(node.absoluteRaw, viewMode: viewMode) } 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/SyntaxHashable.swift b/Sources/SwiftSyntax/SyntaxHashable.swift index 753b2806dbd..c4f87b65233 100644 --- a/Sources/SwiftSyntax/SyntaxHashable.swift +++ b/Sources/SwiftSyntax/SyntaxHashable.swift @@ -15,12 +15,12 @@ public protocol SyntaxHashable: Hashable { var _syntaxNode: Syntax { get } } -public extension SyntaxHashable { - func hash(into hasher: inout Hasher) { +extension SyntaxHashable { + public func hash(into hasher: inout Hasher) { return _syntaxNode.id.hash(into: &hasher) } - static func == (lhs: Self, rhs: Self) -> Bool { + public static func == (lhs: Self, rhs: Self) -> Bool { return lhs._syntaxNode.id == rhs._syntaxNode.id } } diff --git a/Sources/SwiftSyntax/SyntaxIdentifier.swift b/Sources/SwiftSyntax/SyntaxIdentifier.swift index b4cd7a2e393..55d7f52d105 100644 --- a/Sources/SwiftSyntax/SyntaxIdentifier.swift +++ b/Sources/SwiftSyntax/SyntaxIdentifier.swift @@ -10,42 +10,6 @@ // //===----------------------------------------------------------------------===// -/// Represents a unique value for a node within its own tree. -@_spi(RawSyntax) -public struct SyntaxIndexInTree: Comparable, Hashable, Sendable { - let indexInTree: UInt32 - - static let zero: SyntaxIndexInTree = SyntaxIndexInTree(indexInTree: 0) - - /// Assuming that this index points to the start of ``Raw``, so that it points - /// to the next sibling of ``Raw``. - func advancedBy(_ raw: RawSyntax?) -> SyntaxIndexInTree { - let newIndexInTree = self.indexInTree + UInt32(truncatingIfNeeded: raw?.totalNodes ?? 0) - return .init(indexInTree: newIndexInTree) - } - - /// Assuming that this index points to the next sibling of ``Raw``, reverse it - /// so that it points to the start of ``Raw``. - func reversedBy(_ raw: RawSyntax?) -> SyntaxIndexInTree { - let newIndexInTree = self.indexInTree - UInt32(truncatingIfNeeded: raw?.totalNodes ?? 0) - return .init(indexInTree: newIndexInTree) - } - - func advancedToFirstChild() -> SyntaxIndexInTree { - let newIndexInTree = self.indexInTree + 1 - return .init(indexInTree: newIndexInTree) - } - - init(indexInTree: UInt32) { - self.indexInTree = indexInTree - } - - /// Returns `true` if `lhs` occurs before `rhs` in the tree. - public static func < (lhs: SyntaxIndexInTree, rhs: SyntaxIndexInTree) -> Bool { - return lhs.indexInTree < rhs.indexInTree - } -} - /// Provides a stable and unique identity for ``Syntax`` nodes. /// /// Note that two nodes might have the same contents even if their IDs are @@ -57,7 +21,53 @@ public struct SyntaxIndexInTree: Comparable, Hashable, Sendable { /// different syntax tree. Modifying any node in the syntax tree a node is /// contained in generates a copy of that tree and thus changes the IDs of all /// nodes in the tree, not just the modified node's children. -public struct SyntaxIdentifier: Hashable, Sendable { +public struct SyntaxIdentifier: Comparable, Hashable, Sendable { + /// Represents a unique value for a node within its own tree. + /// + /// This is similar to ``SyntaxIdentifier`` but does not store the root ID of the tree. + /// It can thus be transferred across trees that are structurally equivalent, for example two copies of the same tree + /// that live in different processes. + public struct SyntaxIndexInTree: Hashable, Sendable { + /// When traversing the syntax tree using a depth-first traversal, the index at which the node will be visited. + let indexInTree: UInt32 + + /// Assuming that this index points to the start of `raw`, advance it so that it points to the next sibling of + /// `raw`. + func advancedBy(_ raw: RawSyntax?) -> SyntaxIndexInTree { + let newIndexInTree = self.indexInTree + UInt32(truncatingIfNeeded: raw?.totalNodes ?? 0) + return .init(indexInTree: newIndexInTree) + } + + /// Assuming that this index points to the next sibling of `raw`, reverse it so that it points to the start of + /// `raw`. + func reversedBy(_ raw: RawSyntax?) -> SyntaxIndexInTree { + let newIndexInTree = self.indexInTree - UInt32(truncatingIfNeeded: raw?.totalNodes ?? 0) + return .init(indexInTree: newIndexInTree) + } + + func advancedToFirstChild() -> SyntaxIndexInTree { + let newIndexInTree = self.indexInTree + 1 + return .init(indexInTree: newIndexInTree) + } + + init(indexInTree: UInt32) { + self.indexInTree = indexInTree + } + + /// Converts the ``SyntaxIdentifier/SyntaxIndexInTree`` to an opaque value that can be serialized. + /// The opaque value can be restored to a ``SyntaxIdentifier/SyntaxIndexInTree`` using ``init(fromOpaque:)``. + /// + /// - Note: The contents of the opaque value are not specified and clients should not rely on them. + public func toOpaque() -> UInt64 { + return UInt64(indexInTree) + } + + /// Creates a ``SyntaxIdentifier/SyntaxIndexInTree`` from an opaque value obtained using ``toOpaque()``. + public init(fromOpaque opaque: UInt64) { + self.indexInTree = UInt32(opaque) + } + } + /// Unique value for the root node. /// /// Multiple trees may have the same 'rootId' if their root RawSyntax is the @@ -67,23 +77,65 @@ public struct SyntaxIdentifier: Hashable, Sendable { let rootId: UInt /// Unique value for a node within its own tree. - @_spi(RawSyntax) public let indexInTree: SyntaxIndexInTree + /// Returns the `UInt` that is used as the root ID for the given raw syntax node. + private static func rootId(of raw: RawSyntax) -> UInt { + return UInt(bitPattern: raw.pointer.unsafeRawPointer) + } + func advancedBySibling(_ raw: RawSyntax?) -> SyntaxIdentifier { let newIndexInTree = indexInTree.advancedBy(raw) - return .init(rootId: self.rootId, indexInTree: newIndexInTree) + return SyntaxIdentifier(rootId: self.rootId, indexInTree: newIndexInTree) } func advancedToFirstChild() -> SyntaxIdentifier { let newIndexInTree = self.indexInTree.advancedToFirstChild() - return .init(rootId: self.rootId, indexInTree: newIndexInTree) + return SyntaxIdentifier(rootId: self.rootId, indexInTree: newIndexInTree) } static func forRoot(_ raw: RawSyntax) -> SyntaxIdentifier { - return .init( - rootId: UInt(bitPattern: raw.pointer.unsafeRawPointer), - indexInTree: .zero + return SyntaxIdentifier( + rootId: Self.rootId(of: raw), + indexInTree: SyntaxIndexInTree(indexInTree: 0) ) } + + /// Forms a ``SyntaxIdentifier`` from an ``SyntaxIdentifier/SyntaxIndexInTree`` inside a ``Syntax`` node that + /// constitutes the tree's root. + /// + /// Returns `nil` if `root` is not the root of a syntax tree or if `indexInTree` points to a node that is not within + /// the tree spanned up by `root`. + /// + /// - Warning: ``SyntaxIdentifier/SyntaxIndexInTree`` is not stable with regard to insertion or deletions of nodes + /// into a syntax tree. There are only two scenarios where it is valid to share ``SyntaxIndexInTree`` between syntax + /// trees with different nodes: + /// (1) If two trees are guaranteed to be exactly the same eg. because they were parsed using the same version of + /// `SwiftParser` from the same source code. + /// (2) If a tree was mutated by only replacing tokens with other tokens. No nodes must have been inserted or + /// removed during the process, including tokens that are marked as ``SourcePresence/missing``. + public static func fromIndexInTree( + _ indexInTree: SyntaxIndexInTree, + relativeToRoot root: some SyntaxProtocol + ) -> SyntaxIdentifier? { + guard !root.hasParent else { + return nil + } + guard indexInTree.indexInTree < SyntaxIndexInTree(indexInTree: 0).advancedBy(root.raw).indexInTree else { + return nil + } + + return SyntaxIdentifier(rootId: Self.rootId(of: root.raw), indexInTree: indexInTree) + } + + /// A ``SyntaxIdentifier`` compares less than another ``SyntaxIdentifier`` if the node at that identifier occurs first + /// during a depth-first traversal of the tree. This implies that nodes with an earlier ``AbsolutePosition`` also + /// have a lower ``SyntaxIdentifier``. + public static func < (lhs: SyntaxIdentifier, rhs: SyntaxIdentifier) -> Bool { + guard lhs.rootId == rhs.rootId else { + // Nodes in different trees are not comparable. + return false + } + return lhs.indexInTree.indexInTree < rhs.indexInTree.indexInTree + } } diff --git a/Sources/SwiftSyntax/SyntaxNodeFactory.swift b/Sources/SwiftSyntax/SyntaxNodeFactory.swift new file mode 100644 index 00000000000..9246603e892 --- /dev/null +++ b/Sources/SwiftSyntax/SyntaxNodeFactory.swift @@ -0,0 +1,85 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +/// Reusable 'Syntax.Info' storage. +private struct SyntaxInfoRepository { + private final class _Buffer: ManagedBuffer { + deinit { + self.withUnsafeMutablePointers { headerPtr, elementPtr in + _ = elementPtr.deinitialize(count: headerPtr.pointee) + } + } + } + + /// Fixed capacity which is enough for most use cases. + static var capacity: Int { 64 } + + private let buffer: _Buffer + + init() { + let buffer = _Buffer.create(minimumCapacity: Self.capacity, makingHeaderWith: { _ in 0 }) + self.buffer = buffer as! _Buffer + } + + /// Take the 'Syntax.Info' object from the address. + func push(_ info: UnsafeMutablePointer) { + buffer.withUnsafeMutablePointers { headerPtr, elementPtr in + guard headerPtr.pointee < Self.capacity else { + return + } + assert(info.pointee != nil, "tried to push 'nil' info") + elementPtr.advanced(by: headerPtr.pointee).moveInitialize(from: info, count: 1) + info.initialize(to: nil) + headerPtr.pointee += 1 + } + } + + /// Vend a 'Swift.Info' object if available. + func pop() -> Syntax.Info? { + return buffer.withUnsafeMutablePointers { headerPtr, elementPtr in + guard headerPtr.pointee > 0 else { + return nil + } + headerPtr.pointee -= 1 + return elementPtr.advanced(by: headerPtr.pointee).move() + } + } +} + +/// 'Syntax' object factory. This may hold some stocks of recycled 'Syntax.Info'. +struct SyntaxNodeFactory { + private let syntaxInfoRepo: SyntaxInfoRepository = SyntaxInfoRepository() + + /// Create a 'Syntax' instance using the supplied info. + /// + /// If this factory has a recycled 'Syntax.Info', use one of them. Otherwise, just create a instance by allocating a new one. + @inline(__always) + func create(parent: Syntax, raw: RawSyntax, absoluteInfo: AbsoluteSyntaxInfo) -> Syntax { + if let info = syntaxInfoRepo.pop() { + info.info = .nonRoot(.init(parent: parent, absoluteInfo: absoluteInfo)) + return Syntax(raw, info: info) + } else { + return Syntax(raw, parent: parent, absoluteInfo: absoluteInfo) + } + } + + /// Dispose a 'Syntax' object. + /// + /// 'node.info' is collected for future reuse. 'node' is not usable after calling this. + @inline(__always) + func dispose(_ node: inout Syntax) { + if isKnownUniquelyReferenced(&node.info) { + node.info.unsafelyUnwrapped.info = nil + syntaxInfoRepo.push(&node.info) + } + } +} diff --git a/Sources/SwiftSyntax/SyntaxProtocol.swift b/Sources/SwiftSyntax/SyntaxProtocol.swift index 2afa57e1fb8..0c8e72efcca 100644 --- a/Sources/SwiftSyntax/SyntaxProtocol.swift +++ b/Sources/SwiftSyntax/SyntaxProtocol.swift @@ -24,7 +24,7 @@ public protocol SyntaxProtocol: CustomStringConvertible, /// Converts the given specialized node to this type. Returns `nil` if the /// conversion is not possible. - init?(_ node: some SyntaxProtocol) + init?(_ node: __shared some SyntaxProtocol) /// The statically allowed structure of the syntax node. static var structure: SyntaxNodeStructure { get } @@ -42,11 +42,11 @@ extension SyntaxProtocol { // MARK: Casting // Casting functions to specialized syntax nodes. -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Initializes a new instance of the conforming type from a given specialized syntax node. /// /// Returns `nil` if the conversion isn't possible, or if the provided node is `nil`. - init?(_ node: S?) { + public init?(_ node: S?) { guard let node = node else { return nil } @@ -56,7 +56,7 @@ public extension SyntaxProtocol { /// Checks if the current syntax node can be cast to a given specialized syntax type. /// /// - Returns: `true` if the node can be cast, `false` otherwise. - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return self.as(syntaxType) != nil } @@ -67,7 +67,7 @@ public extension SyntaxProtocol { /// - Note: This method overloads the general `is` method and is marked deprecated to produce a warning /// informing the user that the upcast will always succeed. @available(*, deprecated, message: "This cast will always succeed") - func `is`(_ syntaxType: Syntax.Type) -> Bool { + public func `is`(_ syntaxType: Syntax.Type) -> Bool { return true } @@ -78,14 +78,14 @@ public extension SyntaxProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always succeed. @available(*, deprecated, message: "This cast will always succeed") - func `is`(_ syntaxType: Self.Type) -> Bool { + public func `is`(_ syntaxType: Self.Type) -> Bool { return true } /// Attempts to cast the current syntax node to a given specialized syntax type. /// /// - Returns: An instance of the specialized type, or `nil` if the cast fails. - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return S.init(self) } @@ -96,7 +96,7 @@ public extension SyntaxProtocol { /// - Note: This method overloads the general `as` method and is marked deprecated to produce a warning /// informing the user the upcast should be performed using the base node's initializer. @available(*, deprecated, message: "Use `Syntax.init` for upcasting.") - func `as`(_ syntaxType: Syntax.Type) -> Syntax? { + public func `as`(_ syntaxType: Syntax.Type) -> Syntax? { return Syntax(self) } @@ -107,7 +107,7 @@ public extension SyntaxProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always succeed. @available(*, deprecated, message: "This cast will always succeed") - func `as`(_ syntaxType: Self.Type) -> Self? { + public func `as`(_ syntaxType: Self.Type) -> Self? { return self } @@ -115,7 +115,7 @@ public extension SyntaxProtocol { /// /// - Returns: An instance of the specialized type. /// - Warning: This function will crash if the cast is not possible. Use `as` to safely attempt a cast. - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { return self.as(S.self)! } @@ -126,7 +126,7 @@ public extension SyntaxProtocol { /// - Note: This method overloads the general `as` method and is marked deprecated to produce a warning /// informing the user the upcast should be performed using the base node's initializer. @available(*, deprecated, message: "Use `Syntax.init` for upcasting.") - func cast(_ syntaxType: Syntax.Type) -> Syntax { + public func cast(_ syntaxType: Syntax.Type) -> Syntax { return Syntax(self) } @@ -137,17 +137,17 @@ public extension SyntaxProtocol { /// - Note: This method overloads the general `cast` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always succeed. @available(*, deprecated, message: "This cast will always succeed") - func cast(_ syntaxType: Self.Type) -> Self { + public func cast(_ syntaxType: Self.Type) -> Self { return self } } // MARK: Modifying -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Returns a new syntax node that has the child at `keyPath` replaced by /// `value`. - func with(_ keyPath: WritableKeyPath, _ value: T) -> Self { + public func with(_ keyPath: WritableKeyPath, _ value: T) -> Self { var copy = self copy[keyPath: keyPath] = value return copy @@ -155,7 +155,7 @@ public extension SyntaxProtocol { /// Return this subtree with this node as the root, ie. detach this node /// from its parent. - var detached: Self { + public var detached: Self { // Make sure `self` (and thus the arena of `self.raw`) can’t get deallocated // before the detached node can be created. return withExtendedLifetime(self) { @@ -188,15 +188,15 @@ extension SyntaxProtocol { // MARK: Children / parent -public extension SyntaxProtocol { +extension SyntaxProtocol { /// A sequence over the children of this node. - func children(viewMode: SyntaxTreeViewMode) -> SyntaxChildren { + public func children(viewMode: SyntaxTreeViewMode) -> SyntaxChildren { return SyntaxChildren(_syntaxNode, viewMode: viewMode) } /// The index of this node in a ``SyntaxChildren`` collection. @available(*, deprecated, message: "Use index(of:) on the collection that contains this node") - var index: SyntaxChildrenIndex { + public var index: SyntaxChildrenIndex { return indexInParent } @@ -206,12 +206,12 @@ public extension SyntaxProtocol { } /// The parent of this syntax node, or `nil` if this node is the root. - var parent: Syntax? { + public var parent: Syntax? { return Syntax(self).parent } /// The root of the tree in which this node resides. - var root: Syntax { + public var root: Syntax { var this = _syntaxNode while let parent = this.parent { this = parent @@ -220,11 +220,11 @@ public extension SyntaxProtocol { } /// Whether or not this node has a parent. - var hasParent: Bool { + public var hasParent: Bool { return parent != nil } - var keyPathInParent: AnyKeyPath? { + public var keyPathInParent: AnyKeyPath? { guard let parent = self.parent else { return nil } @@ -235,17 +235,17 @@ public extension SyntaxProtocol { } @available(*, deprecated, message: "Use previousToken(viewMode:) instead") - var previousToken: TokenSyntax? { + public var previousToken: TokenSyntax? { return self.previousToken(viewMode: .sourceAccurate) } } // MARK: Accessing tokens -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Recursively walks through the tree to find the token semantically before /// this node. - func previousToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { + public func previousToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { guard let parent = self.parent else { return nil } @@ -264,13 +264,13 @@ public extension SyntaxProtocol { } @available(*, deprecated, message: "Use nextToken(viewMode:) instead") - var nextToken: TokenSyntax? { + public var nextToken: TokenSyntax? { return self.nextToken(viewMode: .sourceAccurate) } /// Recursively walks through the tree to find the next token semantically /// after this node. - func nextToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { + public func nextToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { guard let parent = self.parent else { return nil } @@ -286,12 +286,12 @@ public extension SyntaxProtocol { } @available(*, deprecated, message: "Use firstToken(viewMode: .sourceAccurate) instead") - var firstToken: TokenSyntax? { + public var firstToken: TokenSyntax? { return self.firstToken(viewMode: .sourceAccurate) } /// Returns the first token node that is part of this syntax node. - func firstToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { + public func firstToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { guard viewMode.shouldTraverse(node: raw) else { return nil } if let token = _syntaxNode.as(TokenSyntax.self) { return token @@ -306,12 +306,12 @@ public extension SyntaxProtocol { } @available(*, deprecated, message: "Use lastToken(viewMode: .sourceAccurate) instead") - var lastToken: TokenSyntax? { + public var lastToken: TokenSyntax? { return self.lastToken(viewMode: .sourceAccurate) } /// Returns the last token node that is part of this syntax node. - func lastToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { + public func lastToken(viewMode: SyntaxTreeViewMode) -> TokenSyntax? { guard viewMode.shouldTraverse(node: raw) else { return nil } if let token = _syntaxNode.as(TokenSyntax.self) { return token @@ -326,13 +326,13 @@ public extension SyntaxProtocol { } /// Sequence of tokens that are part of this Syntax node. - func tokens(viewMode: SyntaxTreeViewMode) -> TokenSequence { + public func tokens(viewMode: SyntaxTreeViewMode) -> TokenSequence { return TokenSequence(_syntaxNode, viewMode: viewMode) } /// Find the syntax token at the given absolute position within this /// syntax node or any of its children. - func token(at position: AbsolutePosition) -> TokenSyntax? { + public func token(at position: AbsolutePosition) -> TokenSyntax? { // If the position isn't within this node at all, return early. guard position >= self.position && position < self.endPosition else { return nil @@ -352,63 +352,85 @@ public extension SyntaxProtocol { fatalError("Children of syntax node do not cover all positions in it") } + + /// If the node with the given `syntaxIdentifier` is a (recursive) child of this node, return the node with that + /// identifier. + /// + /// If the identifier references a node from a different tree (ie. one that has a different root ID in the + /// ``SyntaxIdentifier``) or if no node with the given identifier is a child of this syntax node, returns `nil`. + public func node(at syntaxIdentifier: SyntaxIdentifier) -> Syntax? { + guard self.id <= syntaxIdentifier && syntaxIdentifier < self.id.advancedBySibling(self.raw) else { + // The syntax identifier is not part of this tree. + return nil + } + if self.id == syntaxIdentifier { + return Syntax(self) + } + for child in children(viewMode: .all) { + if let node = child.node(at: syntaxIdentifier) { + return node + } + } + + preconditionFailure("syntaxIdentifier is covered by this node but not any of its children?") + } } // MARK: Recursive flags -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Whether the tree contained by this layout has any /// - missing nodes or /// - unexpected nodes or /// - tokens with a ``TokenDiagnostic`` of severity ``TokenDiagnostic/Severity-swift.enum/error``. - var hasError: Bool { + public var hasError: Bool { return raw.hasError } /// Whether the tree contained by this layout has any tokens with a /// ``TokenDiagnostic`` of severity `warning`. - var hasWarning: Bool { + public var hasWarning: Bool { return raw.recursiveFlags.contains(.hasWarning) } /// Whether this tree contains a missing token or unexpected node. - var hasSequenceExpr: Bool { + public var hasSequenceExpr: Bool { return raw.recursiveFlags.contains(.hasSequenceExpr) } - var hasMaximumNestingLevelOverflow: Bool { + public var hasMaximumNestingLevelOverflow: Bool { return raw.recursiveFlags.contains(.hasMaximumNestingLevelOverflow) } } // MARK: Position / length / range -public extension SyntaxProtocol { +extension SyntaxProtocol { /// The absolute position of the starting point of this node. If the first token /// is with leading trivia, the position points to the start of the leading /// trivia. - var position: AbsolutePosition { + public var position: AbsolutePosition { return Syntax(self).position } /// The absolute position of the starting point of this node, skipping any /// leading trivia attached to the first token syntax. - var positionAfterSkippingLeadingTrivia: AbsolutePosition { + public var positionAfterSkippingLeadingTrivia: AbsolutePosition { return Syntax(self).positionAfterSkippingLeadingTrivia } /// The end position of this node's content, before any trailing trivia. - var endPositionBeforeTrailingTrivia: AbsolutePosition { + public var endPositionBeforeTrailingTrivia: AbsolutePosition { return Syntax(self).endPositionBeforeTrailingTrivia } /// The end position of this node, including its trivia. - var endPosition: AbsolutePosition { + public var endPosition: AbsolutePosition { return Syntax(self).endPosition } /// The length of this node including all of its trivia. - var totalLength: SourceLength { + public var totalLength: SourceLength { return raw.totalLength } @@ -417,12 +439,12 @@ public extension SyntaxProtocol { /// /// - Note: If this node consists of multiple tokens, only the first token’s /// leading and the last token’s trailing trivia will be trimmed. - var trimmedLength: SourceLength { + public var trimmedLength: SourceLength { return raw.trimmedLength } /// The byte source range of this node including leading and trailing trivia. - var totalByteRange: ByteSourceRange { + public var totalByteRange: ByteSourceRange { return ByteSourceRange(offset: position.utf8Offset, length: totalLength.utf8Length) } @@ -430,7 +452,7 @@ public extension SyntaxProtocol { /// /// - Note: If this node consists of multiple tokens, only the first token’s /// leading and the last token’s trailing trivia will be trimmed. - var trimmedByteRange: ByteSourceRange { + public var trimmedByteRange: ByteSourceRange { return ByteSourceRange( offset: positionAfterSkippingLeadingTrivia.utf8Offset, length: trimmedLength.utf8Length @@ -438,31 +460,31 @@ public extension SyntaxProtocol { } @available(*, deprecated, renamed: "trimmedLength") - var contentLength: SourceLength { + public var contentLength: SourceLength { return trimmedLength } @available(*, deprecated, renamed: "totalByteRange") - var byteRange: ByteSourceRange { + public var byteRange: ByteSourceRange { return ByteSourceRange(offset: position.utf8Offset, length: totalLength.utf8Length) } /// The textual byte length of this node including leading and trailing trivia. @available(*, deprecated, message: "Use totalLength.utf8Length") - var byteSize: Int { + public var byteSize: Int { return totalLength.utf8Length } /// The textual byte length of this node excluding leading and trailing trivia. @available(*, deprecated, message: "Use trimmedLength.utf8Length") - var byteSizeAfterTrimmingTrivia: Int { + public var byteSizeAfterTrimmingTrivia: Int { return trimmedLength.utf8Length } } // MARK: Trivia -public extension SyntaxProtocol { +extension SyntaxProtocol { /// The leading trivia of this syntax node. /// /// Trivia is always attached to tokens, not to layout nodes. This will return the leading trivia of the first token @@ -473,7 +495,7 @@ public extension SyntaxProtocol { /// ``` /// node.syntaxTextBytes.prefix(self.leadingTriviaLength.utf8Length) /// ``` - var leadingTrivia: Trivia { + public var leadingTrivia: Trivia { get { return raw.formLeadingTrivia() } @@ -492,7 +514,7 @@ public extension SyntaxProtocol { /// ``` /// node.syntaxTextBytes[(node.byteSize - node.trailingTriviaLength.utf8Length)...] /// ``` - var trailingTrivia: Trivia { + public var trailingTrivia: Trivia { get { return raw.formTrailingTrivia() } @@ -502,12 +524,12 @@ public extension SyntaxProtocol { } /// The length this node's leading trivia takes up spelled out in source. - var leadingTriviaLength: SourceLength { + public var leadingTriviaLength: SourceLength { return raw.leadingTriviaLength } /// The length this node's trailing trivia takes up spelled out in source. - var trailingTriviaLength: SourceLength { + public var trailingTriviaLength: SourceLength { return raw.trailingTriviaLength } } @@ -515,40 +537,40 @@ public extension SyntaxProtocol { // MARK: Content /// Provides the source-accurate text for a node -public extension SyntaxProtocol { +extension SyntaxProtocol { /// A source-accurate description of this node. /// /// Note that the resulting String cannot represent invalid UTF-8 that /// occurs within the syntax nodes. Use `syntaxTextBytes` for a /// byte-accurate representation of this node in the presence of /// invalid UTF-8. - var description: String { + public var description: String { return Syntax(self).raw.description } /// Retrieve the syntax text as an array of bytes that models the input /// source even in the presence of invalid UTF-8. - var syntaxTextBytes: [UInt8] { + public var syntaxTextBytes: [UInt8] { return Syntax(self).raw.syntaxTextBytes } /// Prints the raw value of this node to the provided stream. /// - Parameter stream: The stream to which to print the raw tree. - func write(to target: inout Target) + public func write(to target: inout Target) where Target: TextOutputStream { Syntax(self).raw.write(to: &target) } /// A copy of this node without the leading trivia of the first token in the /// node and the trailing trivia of the last token in the node. - var trimmed: Self { + public var trimmed: Self { // TODO: Should only need one new node here return self.with(\.leadingTrivia, []).with(\.trailingTrivia, []) } /// A copy of this node with pieces that match `matching` trimmed from the /// leading trivia of the first token and trailing trivia of the last token. - func trimmed(matching filter: (TriviaPiece) -> Bool) -> Self { + public func trimmed(matching filter: (TriviaPiece) -> Bool) -> Self { // TODO: Should only need one new node here return self.with( \.leadingTrivia, @@ -561,7 +583,7 @@ public extension SyntaxProtocol { /// The description of this node with leading whitespace of the first token /// and trailing whitespace of the last token removed. - var trimmedDescription: String { + public var trimmedDescription: String { // TODO: We shouldn't need to create to copies just to get the trimmed // description. return self.trimmed.description @@ -570,7 +592,7 @@ public extension SyntaxProtocol { /// The description of this node with pieces that match `matching` removed /// from the leading trivia of the first token and trailing trivia of the /// last token. - func trimmedDescription(matching filter: (TriviaPiece) -> Bool) -> String { + public func trimmedDescription(matching filter: (TriviaPiece) -> Bool) -> String { // TODO: We shouldn't need to create to copies just to get the trimmed // description. return self.trimmed(matching: filter).description @@ -579,16 +601,16 @@ public extension SyntaxProtocol { // MARK: Miscellaneous -public extension SyntaxProtocol { +extension SyntaxProtocol { /// When isImplicit is true, the syntax node doesn't include any /// underlying tokens, e.g. an empty CodeBlockItemList. @available(*, deprecated, message: "Check children(viewMode: .all).isEmpty instead") - var isImplicit: Bool { + public var isImplicit: Bool { return raw.isEmpty } /// Returns a value representing the unique identity of the node. - var id: SyntaxIdentifier { + public var id: SyntaxIdentifier { return Syntax(self).id } } @@ -596,13 +618,13 @@ public extension SyntaxProtocol { // MARK: Debug description /// Provides debug descriptions for a node -public extension SyntaxProtocol { +extension SyntaxProtocol { /// A simple description of this node (ie. its type). - var debugDescription: String { + public var debugDescription: String { debugDescription() } - var customMirror: Mirror { + public var customMirror: Mirror { // Suppress printing of children when doing `po node` in the debugger. // `debugDescription` already prints them in a nicer way. return Mirror(self, children: [:]) @@ -618,7 +640,7 @@ public extension SyntaxProtocol { /// the dump. /// - indentLevel: The starting indent level, 0 by default. Each level is 2 /// spaces. - func debugDescription( + public func debugDescription( includeTrivia: Bool = false, converter: SourceLocationConverter? = nil, mark: SyntaxProtocol? = nil, @@ -701,7 +723,7 @@ public extension SyntaxProtocol { /// possible types a child node might have. public protocol SyntaxChildChoices: SyntaxProtocol {} -public extension SyntaxChildChoices { +extension SyntaxChildChoices { /// Checks if the current ``SyntaxChildChoices`` instance can be cast to a given specialized syntax type. /// @@ -709,7 +731,7 @@ public extension SyntaxChildChoices { /// /// - Note: This method is marked as deprecated because it is advised not to use it for unrelated casts. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return self.as(syntaxType) != nil } @@ -719,7 +741,7 @@ public extension SyntaxChildChoices { /// /// - Note: This method is marked as deprecated because it is advised not to use it for unrelated casts. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return S.init(self) } @@ -731,7 +753,7 @@ public extension SyntaxChildChoices { /// /// - Note: This method is marked as deprecated because it is advised not to use it for unrelated casts. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { return self.as(S.self)! } } 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..9dfcf11ffde 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) } } @@ -151,6 +153,16 @@ public struct TokenSyntax: SyntaxProtocol, SyntaxHashable { } } + /// An identifier created from `self`. + public var identifier: Identifier? { + switch self.tokenKind { + case .identifier, .dollarIdentifier: + return Identifier(self) + default: + return nil + } + } + /// A token by itself has no structure, so we represent its structure by an /// empty layout node. /// diff --git a/Sources/SwiftSyntax/generated/ChildNameForKeyPath.swift b/Sources/SwiftSyntax/generated/ChildNameForKeyPath.swift index a738f6b9979..b328be7cf7d 100644 --- a/Sources/SwiftSyntax/generated/ChildNameForKeyPath.swift +++ b/Sources/SwiftSyntax/generated/ChildNameForKeyPath.swift @@ -351,45 +351,45 @@ public func childName(_ keyPath: AnyKeyPath) -> String? { return "label" case \BreakStmtSyntax.unexpectedAfterLabel: return "unexpectedAfterLabel" - case \CanImportExprSyntax.unexpectedBeforeCanImportKeyword: + case \_CanImportExprSyntax.unexpectedBeforeCanImportKeyword: return "unexpectedBeforeCanImportKeyword" - case \CanImportExprSyntax.canImportKeyword: + case \_CanImportExprSyntax.canImportKeyword: return "canImportKeyword" - case \CanImportExprSyntax.unexpectedBetweenCanImportKeywordAndLeftParen: + case \_CanImportExprSyntax.unexpectedBetweenCanImportKeywordAndLeftParen: return "unexpectedBetweenCanImportKeywordAndLeftParen" - case \CanImportExprSyntax.leftParen: + case \_CanImportExprSyntax.leftParen: return "leftParen" - case \CanImportExprSyntax.unexpectedBetweenLeftParenAndImportPath: + case \_CanImportExprSyntax.unexpectedBetweenLeftParenAndImportPath: return "unexpectedBetweenLeftParenAndImportPath" - case \CanImportExprSyntax.importPath: + case \_CanImportExprSyntax.importPath: return "importPath" - case \CanImportExprSyntax.unexpectedBetweenImportPathAndVersionInfo: + case \_CanImportExprSyntax.unexpectedBetweenImportPathAndVersionInfo: return "unexpectedBetweenImportPathAndVersionInfo" - case \CanImportExprSyntax.versionInfo: + case \_CanImportExprSyntax.versionInfo: return "versionInfo" - case \CanImportExprSyntax.unexpectedBetweenVersionInfoAndRightParen: + case \_CanImportExprSyntax.unexpectedBetweenVersionInfoAndRightParen: return "unexpectedBetweenVersionInfoAndRightParen" - case \CanImportExprSyntax.rightParen: + case \_CanImportExprSyntax.rightParen: return "rightParen" - case \CanImportExprSyntax.unexpectedAfterRightParen: + case \_CanImportExprSyntax.unexpectedAfterRightParen: return "unexpectedAfterRightParen" - case \CanImportVersionInfoSyntax.unexpectedBeforeComma: + case \_CanImportVersionInfoSyntax.unexpectedBeforeComma: return "unexpectedBeforeComma" - case \CanImportVersionInfoSyntax.comma: + case \_CanImportVersionInfoSyntax.comma: return "comma" - case \CanImportVersionInfoSyntax.unexpectedBetweenCommaAndLabel: + case \_CanImportVersionInfoSyntax.unexpectedBetweenCommaAndLabel: return "unexpectedBetweenCommaAndLabel" - case \CanImportVersionInfoSyntax.label: + case \_CanImportVersionInfoSyntax.label: return "label" - case \CanImportVersionInfoSyntax.unexpectedBetweenLabelAndColon: + case \_CanImportVersionInfoSyntax.unexpectedBetweenLabelAndColon: return "unexpectedBetweenLabelAndColon" - case \CanImportVersionInfoSyntax.colon: + case \_CanImportVersionInfoSyntax.colon: return "colon" - case \CanImportVersionInfoSyntax.unexpectedBetweenColonAndVersion: + case \_CanImportVersionInfoSyntax.unexpectedBetweenColonAndVersion: return "unexpectedBetweenColonAndVersion" - case \CanImportVersionInfoSyntax.version: + case \_CanImportVersionInfoSyntax.version: return "version" - case \CanImportVersionInfoSyntax.unexpectedAfterVersion: + case \_CanImportVersionInfoSyntax.unexpectedAfterVersion: return "unexpectedAfterVersion" case \CatchClauseSyntax.unexpectedBeforeCatchKeyword: return "unexpectedBeforeCatchKeyword" @@ -2009,30 +2009,28 @@ public func childName(_ keyPath: AnyKeyPath) -> String? { return "trailingComma" case \LifetimeSpecifierArgumentSyntax.unexpectedAfterTrailingComma: return "unexpectedAfterTrailingComma" - case \LifetimeSpecifierArgumentsSyntax.unexpectedBeforeLeftParen: - return "unexpectedBeforeLeftParen" - case \LifetimeSpecifierArgumentsSyntax.leftParen: + case \LifetimeTypeSpecifierSyntax.unexpectedBeforeDependsOnKeyword: + return "unexpectedBeforeDependsOnKeyword" + case \LifetimeTypeSpecifierSyntax.dependsOnKeyword: + return "dependsOnKeyword" + case \LifetimeTypeSpecifierSyntax.unexpectedBetweenDependsOnKeywordAndLeftParen: + return "unexpectedBetweenDependsOnKeywordAndLeftParen" + case \LifetimeTypeSpecifierSyntax.leftParen: return "leftParen" - case \LifetimeSpecifierArgumentsSyntax.unexpectedBetweenLeftParenAndArguments: - return "unexpectedBetweenLeftParenAndArguments" - case \LifetimeSpecifierArgumentsSyntax.arguments: + case \LifetimeTypeSpecifierSyntax.unexpectedBetweenLeftParenAndScopedKeyword: + return "unexpectedBetweenLeftParenAndScopedKeyword" + case \LifetimeTypeSpecifierSyntax.scopedKeyword: + return "scopedKeyword" + case \LifetimeTypeSpecifierSyntax.unexpectedBetweenScopedKeywordAndArguments: + return "unexpectedBetweenScopedKeywordAndArguments" + case \LifetimeTypeSpecifierSyntax.arguments: return "arguments" - case \LifetimeSpecifierArgumentsSyntax.unexpectedBetweenArgumentsAndRightParen: + case \LifetimeTypeSpecifierSyntax.unexpectedBetweenArgumentsAndRightParen: return "unexpectedBetweenArgumentsAndRightParen" - case \LifetimeSpecifierArgumentsSyntax.rightParen: + case \LifetimeTypeSpecifierSyntax.rightParen: return "rightParen" - case \LifetimeSpecifierArgumentsSyntax.unexpectedAfterRightParen: + case \LifetimeTypeSpecifierSyntax.unexpectedAfterRightParen: return "unexpectedAfterRightParen" - case \LifetimeTypeSpecifierSyntax.unexpectedBeforeSpecifier: - return "unexpectedBeforeSpecifier" - case \LifetimeTypeSpecifierSyntax.specifier: - return "specifier" - case \LifetimeTypeSpecifierSyntax.unexpectedBetweenSpecifierAndArguments: - return "unexpectedBetweenSpecifierAndArguments" - case \LifetimeTypeSpecifierSyntax.arguments: - return "arguments" - case \LifetimeTypeSpecifierSyntax.unexpectedAfterArguments: - return "unexpectedAfterArguments" case \MacroDeclSyntax.unexpectedBeforeAttributes: return "unexpectedBeforeAttributes" case \MacroDeclSyntax.attributes: diff --git a/Sources/SwiftSyntax/generated/Keyword.swift b/Sources/SwiftSyntax/generated/Keyword.swift index c331f2f5716..07eaa698102 100644 --- a/Sources/SwiftSyntax/generated/Keyword.swift +++ b/Sources/SwiftSyntax/generated/Keyword.swift @@ -20,19 +20,16 @@ public enum Keyword: UInt8, Hashable, Sendable { case _alignment case _backDeploy case _borrow - @_spi(ExperimentalLanguageFeatures) case _borrowing case _BridgeObject case _cdecl case _Class case _compilerInitialized case _const + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) - case _consume - @_spi(ExperimentalLanguageFeatures) + #endif case _consuming - @_spi(ExperimentalLanguageFeatures) - case _copy case _documentation case _dynamicReplacement case _effects @@ -43,9 +40,9 @@ public enum Keyword: UInt8, Hashable, Sendable { case _local case _modify case _move + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) - case _mutate - @_spi(ExperimentalLanguageFeatures) + #endif case _mutating case _NativeClass case _NativeRefCountedObject @@ -110,6 +107,10 @@ public enum Keyword: UInt8, Hashable, Sendable { case `default` case `defer` case `deinit` + #if compiler(>=5.8) + @_spi(ExperimentalLanguageFeatures) + #endif + case dependsOn case deprecated case derivative case didSet @@ -191,9 +192,13 @@ public enum Keyword: UInt8, Hashable, Sendable { case renamed case `repeat` case required + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _resultDependsOn + #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) + #endif case _resultDependsOnSelf case `rethrows` case retroactive @@ -201,7 +206,12 @@ public enum Keyword: UInt8, Hashable, Sendable { case reverse case right case safe + #if compiler(>=5.8) + @_spi(ExperimentalLanguageFeatures) + #endif + case scoped case `self` + case sending case `Self` case Sendable case set @@ -219,8 +229,6 @@ public enum Keyword: UInt8, Hashable, Sendable { case then case `throw` case `throws` - @_spi(ExperimentalLanguageFeatures) - case transferring case transpose case `true` case `try` @@ -343,8 +351,6 @@ public enum Keyword: UInt8, Hashable, Sendable { } case 5: switch text { - case "_copy": - self = ._copy case "_move": self = ._move case "_read": @@ -428,6 +434,8 @@ public enum Keyword: UInt8, Hashable, Sendable { self = .repeat case "return": self = .return + case "scoped": + self = .scoped case "static": self = .static case "struct": @@ -455,8 +463,6 @@ public enum Keyword: UInt8, Hashable, Sendable { self = ._linear case "_modify": self = ._modify - case "_mutate": - self = ._mutate case "consume": self = .consume case "default": @@ -483,6 +489,8 @@ public enum Keyword: UInt8, Hashable, Sendable { self = .renamed case "reverse": self = .reverse + case "sending": + self = .sending case "unowned": self = .unowned case "willSet": @@ -494,8 +502,6 @@ public enum Keyword: UInt8, Hashable, Sendable { switch text { case "__shared": self = .__shared - case "_consume": - self = ._consume case "_effects": self = ._effects case "_forward": @@ -563,6 +569,8 @@ public enum Keyword: UInt8, Hashable, Sendable { self = .canImport case "consuming": self = .consuming + case "dependsOn": + self = .dependsOn case "extension": self = .extension case "lowerThan": @@ -664,8 +672,6 @@ public enum Keyword: UInt8, Hashable, Sendable { self = .freestanding case "noDerivative": self = .noDerivative - case "transferring": - self = .transferring default: return nil } @@ -826,9 +832,7 @@ public enum Keyword: UInt8, Hashable, Sendable { "_Class", "_compilerInitialized", "_const", - "_consume", "_consuming", - "_copy", "_documentation", "_dynamicReplacement", "_effects", @@ -839,7 +843,6 @@ public enum Keyword: UInt8, Hashable, Sendable { "_local", "_modify", "_move", - "_mutate", "_mutating", "_NativeClass", "_NativeRefCountedObject", @@ -904,6 +907,7 @@ public enum Keyword: UInt8, Hashable, Sendable { "default", "defer", "deinit", + "dependsOn", "deprecated", "derivative", "didSet", @@ -993,7 +997,9 @@ public enum Keyword: UInt8, Hashable, Sendable { "reverse", "right", "safe", + "scoped", "self", + "sending", "Self", "Sendable", "set", @@ -1011,7 +1017,6 @@ public enum Keyword: UInt8, Hashable, Sendable { "then", "throw", "throws", - "transferring", "transpose", "true", "try", diff --git a/Sources/SwiftSyntax/generated/RenamedChildrenCompatibility.swift b/Sources/SwiftSyntax/generated/RenamedChildrenCompatibility.swift index 8046f48d3a2..c798061a9e6 100644 --- a/Sources/SwiftSyntax/generated/RenamedChildrenCompatibility.swift +++ b/Sources/SwiftSyntax/generated/RenamedChildrenCompatibility.swift @@ -1025,7 +1025,7 @@ extension BooleanLiteralExprSyntax { } } -extension CanImportVersionInfoSyntax { +extension _CanImportVersionInfoSyntax { @available(*, deprecated, renamed: "unexpectedBetweenColonAndVersion") public var unexpectedBetweenColonAndVersionTuple: UnexpectedNodesSyntax? { get { @@ -1056,7 +1056,7 @@ extension CanImportVersionInfoSyntax { } } - @available(*, deprecated, renamed: "CanImportVersionInfoSyntax(leadingTrivia:_:comma:_:label:_:colon:_:version:_:trailingTrivia:)") + @available(*, deprecated, renamed: "_CanImportVersionInfoSyntax(leadingTrivia:_:comma:_:label:_:colon:_:version:_:trailingTrivia:)") @_disfavoredOverload public init( leadingTrivia: Trivia? = nil, diff --git a/Sources/SwiftSyntax/generated/RenamedNodesCompatibility.swift b/Sources/SwiftSyntax/generated/RenamedNodesCompatibility.swift index 9fc7d663ee4..1b0f9b09fbf 100644 --- a/Sources/SwiftSyntax/generated/RenamedNodesCompatibility.swift +++ b/Sources/SwiftSyntax/generated/RenamedNodesCompatibility.swift @@ -45,6 +45,12 @@ public typealias AvailabilityVersionRestrictionListEntrySyntax = PlatformVersion @available(*, deprecated, renamed: "BackDeployedAttributeArgumentsSyntax") public typealias BackDeployedAttributeSpecListSyntax = BackDeployedAttributeArgumentsSyntax +@available(*, deprecated, message: "'canImport' directives are now represented as a `FunctionCallExpr`") +public typealias CanImportExprSyntax = _CanImportExprSyntax + +@available(*, deprecated, message: "'canImport' directives are now represented as a `FunctionCallExpr`") +public typealias CanImportVersionInfoSyntax = _CanImportVersionInfoSyntax + @available(*, deprecated, renamed: "SwitchCaseItemSyntax") public typealias CaseItemSyntax = SwitchCaseItemSyntax @@ -213,272 +219,349 @@ public typealias YieldExprListElementSyntax = YieldedExpressionSyntax @available(*, deprecated, renamed: "YieldedExpressionsClauseSyntax") public typealias YieldListSyntax = YieldedExpressionsClauseSyntax -public extension SyntaxKind { - static var accessPath: Self { +extension SyntaxKind { + @available(*, deprecated, renamed: "ImportPathComponentListSyntax") + public static var accessPath: Self { return .importPathComponentList } - static var accessPathComponent: Self { + @available(*, deprecated, renamed: "ImportPathComponentSyntax") + public static var accessPathComponent: Self { return .importPathComponent } - static var accessorList: Self { + @available(*, deprecated, renamed: "AccessorDeclListSyntax") + public static var accessorList: Self { return .accessorDeclList } - static var accessorParameter: Self { + @available(*, deprecated, renamed: "AccessorParametersSyntax") + public static var accessorParameter: Self { return .accessorParameters } - static var associatedtypeDecl: Self { + @available(*, deprecated, renamed: "AssociatedTypeDeclSyntax") + public static var associatedtypeDecl: Self { return .associatedTypeDecl } - static var availabilityEntry: Self { + @available(*, deprecated, renamed: "SpecializeAvailabilityArgumentSyntax") + public static var availabilityEntry: Self { return .specializeAvailabilityArgument } - static var availabilitySpecList: Self { + @available(*, deprecated, renamed: "AvailabilityArgumentListSyntax") + public static var availabilitySpecList: Self { return .availabilityArgumentList } - static var availabilityVersionRestriction: Self { + @available(*, deprecated, renamed: "PlatformVersionSyntax") + public static var availabilityVersionRestriction: Self { return .platformVersion } - static var availabilityVersionRestrictionList: Self { + @available(*, deprecated, renamed: "PlatformVersionItemListSyntax") + public static var availabilityVersionRestrictionList: Self { return .platformVersionItemList } - static var availabilityVersionRestrictionListEntry: Self { + @available(*, deprecated, renamed: "PlatformVersionItemSyntax") + public static var availabilityVersionRestrictionListEntry: Self { return .platformVersionItem } - static var backDeployedAttributeSpecList: Self { + @available(*, deprecated, renamed: "BackDeployedAttributeArgumentsSyntax") + public static var backDeployedAttributeSpecList: Self { return .backDeployedAttributeArguments } - static var caseItem: Self { + @available(*, deprecated, message: "'canImport' directives are now represented as a `FunctionCallExpr`") + public static var canImportExpr: Self { + return ._canImportExpr + } + + @available(*, deprecated, message: "'canImport' directives are now represented as a `FunctionCallExpr`") + public static var canImportVersionInfo: Self { + return ._canImportVersionInfo + } + + @available(*, deprecated, renamed: "SwitchCaseItemSyntax") + public static var caseItem: Self { return .switchCaseItem } - static var caseItemList: Self { + @available(*, deprecated, renamed: "SwitchCaseItemListSyntax") + public static var caseItemList: Self { return .switchCaseItemList } - static var closureCaptureItem: Self { + @available(*, deprecated, renamed: "ClosureCaptureSyntax") + public static var closureCaptureItem: Self { return .closureCapture } - static var closureCaptureItemList: Self { + @available(*, deprecated, renamed: "ClosureCaptureListSyntax") + public static var closureCaptureItemList: Self { return .closureCaptureList } - static var closureCaptureItemSpecifier: Self { + @available(*, deprecated, renamed: "ClosureCaptureSpecifierSyntax") + public static var closureCaptureItemSpecifier: Self { return .closureCaptureSpecifier } - static var closureCaptureSignature: Self { + @available(*, deprecated, renamed: "ClosureCaptureClauseSyntax") + public static var closureCaptureSignature: Self { return .closureCaptureClause } - static var closureParam: Self { + @available(*, deprecated, renamed: "ClosureShorthandParameterSyntax") + public static var closureParam: Self { return .closureShorthandParameter } - static var closureParamList: Self { + @available(*, deprecated, renamed: "ClosureShorthandParameterListSyntax") + public static var closureParamList: Self { return .closureShorthandParameterList } - static var constrainedSugarType: Self { + @available(*, deprecated, renamed: "SomeOrAnyTypeSyntax") + public static var constrainedSugarType: Self { return .someOrAnyType } - static var deinitEffectSpecifiers: Self { + @available(*, deprecated, renamed: "DeinitializerEffectSpecifiersSyntax") + public static var deinitEffectSpecifiers: Self { return .deinitializerEffectSpecifiers } - static var derivativeRegistrationAttributeArguments: Self { + @available(*, deprecated, renamed: "DerivativeAttributeArgumentsSyntax") + public static var derivativeRegistrationAttributeArguments: Self { return .derivativeAttributeArguments } - static var designatedTypeElement: Self { + @available(*, deprecated, renamed: "DesignatedTypeSyntax") + public static var designatedTypeElement: Self { return .designatedType } - static var differentiabilityParam: Self { + @available(*, deprecated, renamed: "DifferentiabilityArgumentSyntax") + public static var differentiabilityParam: Self { return .differentiabilityArgument } - static var differentiabilityParamList: Self { + @available(*, deprecated, renamed: "DifferentiabilityArgumentListSyntax") + public static var differentiabilityParamList: Self { return .differentiabilityArgumentList } - static var differentiabilityParams: Self { + @available(*, deprecated, renamed: "DifferentiabilityArgumentsSyntax") + public static var differentiabilityParams: Self { return .differentiabilityArguments } - static var differentiabilityParamsClause: Self { + @available(*, deprecated, renamed: "DifferentiabilityWithRespectToArgumentSyntax") + public static var differentiabilityParamsClause: Self { return .differentiabilityWithRespectToArgument } - static var documentationAttributeArguments: Self { + @available(*, deprecated, renamed: "DocumentationAttributeArgumentListSyntax") + public static var documentationAttributeArguments: Self { return .documentationAttributeArgumentList } - static var dynamicReplacementArguments: Self { + @available(*, deprecated, renamed: "DynamicReplacementAttributeArgumentsSyntax") + public static var dynamicReplacementArguments: Self { return .dynamicReplacementAttributeArguments } - static var effectsArguments: Self { + @available(*, deprecated, renamed: "EffectsAttributeArgumentListSyntax") + public static var effectsArguments: Self { return .effectsAttributeArgumentList } - static var enumCaseAssociatedValue: Self { + @available(*, deprecated, renamed: "EnumCaseParameterClauseSyntax") + public static var enumCaseAssociatedValue: Self { return .enumCaseParameterClause } - static var fallthroughStmt: Self { + @available(*, deprecated, renamed: "FallThroughStmtSyntax") + public static var fallthroughStmt: Self { return .fallThroughStmt } - static var forInStmt: Self { + @available(*, deprecated, renamed: "ForStmtSyntax") + public static var forInStmt: Self { return .forStmt } - static var forcedValueExpr: Self { + @available(*, deprecated, renamed: "ForceUnwrapExprSyntax") + public static var forcedValueExpr: Self { return .forceUnwrapExpr } - static var identifierExpr: Self { + @available(*, deprecated, renamed: "DeclReferenceExprSyntax") + public static var identifierExpr: Self { return .declReferenceExpr } - static var labeledSpecializeEntry: Self { + @available(*, deprecated, renamed: "LabeledSpecializeArgumentSyntax") + public static var labeledSpecializeEntry: Self { return .labeledSpecializeArgument } - static var memberDeclBlock: Self { + @available(*, deprecated, renamed: "MemberBlockSyntax") + public static var memberDeclBlock: Self { return .memberBlock } - static var memberDeclList: Self { + @available(*, deprecated, renamed: "MemberBlockItemListSyntax") + public static var memberDeclList: Self { return .memberBlockItemList } - static var memberDeclListItem: Self { + @available(*, deprecated, renamed: "MemberBlockItemSyntax") + public static var memberDeclListItem: Self { return .memberBlockItem } - static var memberTypeIdentifier: Self { + @available(*, deprecated, renamed: "MemberTypeSyntax") + public static var memberTypeIdentifier: Self { return .memberType } - static var modifierList: Self { + @available(*, deprecated, renamed: "DeclModifierListSyntax") + public static var modifierList: Self { return .declModifierList } - static var moveExpr: Self { + @available(*, deprecated, renamed: "ConsumeExprSyntax") + public static var moveExpr: Self { return .consumeExpr } - static var objCSelector: Self { + @available(*, deprecated, renamed: "ObjCSelectorPieceListSyntax") + public static var objCSelector: Self { return .objCSelectorPieceList } - static var originallyDefinedInArguments: Self { + @available(*, deprecated, renamed: "OriginallyDefinedInAttributeArgumentsSyntax") + public static var originallyDefinedInArguments: Self { return .originallyDefinedInAttributeArguments } - static var packReferenceType: Self { + @available(*, deprecated, renamed: "PackElementTypeSyntax") + public static var packReferenceType: Self { return .packElementType } - static var parameterClause: Self { + @available(*, deprecated, renamed: "FunctionParameterClauseSyntax") + public static var parameterClause: Self { return .functionParameterClause } - static var postfixUnaryExpr: Self { + @available(*, deprecated, renamed: "PostfixOperatorExprSyntax") + public static var postfixUnaryExpr: Self { return .postfixOperatorExpr } - static var poundSourceLocationArgs: Self { + @available(*, deprecated, renamed: "PoundSourceLocationArgumentsSyntax") + public static var poundSourceLocationArgs: Self { return .poundSourceLocationArguments } - static var precedenceGroupNameElement: Self { + @available(*, deprecated, renamed: "PrecedenceGroupNameSyntax") + public static var precedenceGroupNameElement: Self { return .precedenceGroupName } - static var repeatWhileStmt: Self { + @available(*, deprecated, renamed: "RepeatStmtSyntax") + public static var repeatWhileStmt: Self { return .repeatStmt } - static var simpleTypeIdentifier: Self { + @available(*, deprecated, renamed: "IdentifierTypeSyntax") + public static var simpleTypeIdentifier: Self { return .identifierType } - static var specializeAttributeSpecList: Self { + @available(*, deprecated, renamed: "SpecializeAttributeArgumentListSyntax") + public static var specializeAttributeSpecList: Self { return .specializeAttributeArgumentList } - static var specializeExpr: Self { + @available(*, deprecated, renamed: "GenericSpecializationExprSyntax") + public static var specializeExpr: Self { return .genericSpecializationExpr } - static var stringLiteralSegments: Self { + @available(*, deprecated, renamed: "StringLiteralSegmentListSyntax") + public static var stringLiteralSegments: Self { return .stringLiteralSegmentList } - static var subscriptExpr: Self { + @available(*, deprecated, renamed: "SubscriptCallExprSyntax") + public static var subscriptExpr: Self { return .subscriptCallExpr } - static var superRefExpr: Self { + @available(*, deprecated, renamed: "SuperExprSyntax") + public static var superRefExpr: Self { return .superExpr } - static var targetFunctionEntry: Self { + @available(*, deprecated, renamed: "SpecializeTargetFunctionArgumentSyntax") + public static var targetFunctionEntry: Self { return .specializeTargetFunctionArgument } - static var tupleExprElement: Self { + @available(*, deprecated, renamed: "LabeledExprSyntax") + public static var tupleExprElement: Self { return .labeledExpr } - static var tupleExprElementList: Self { + @available(*, deprecated, renamed: "LabeledExprListSyntax") + public static var tupleExprElementList: Self { return .labeledExprList } - static var typeInheritanceClause: Self { + @available(*, deprecated, renamed: "InheritanceClauseSyntax") + public static var typeInheritanceClause: Self { return .inheritanceClause } - static var typeSpecifier: Self { + @available(*, deprecated, renamed: "SimpleTypeSpecifierSyntax") + public static var typeSpecifier: Self { return .simpleTypeSpecifier } - static var typealiasDecl: Self { + @available(*, deprecated, renamed: "TypeAliasDeclSyntax") + public static var typealiasDecl: Self { return .typeAliasDecl } - static var unavailableFromAsyncArguments: Self { + @available(*, deprecated, renamed: "UnavailableFromAsyncAttributeArgumentsSyntax") + public static var unavailableFromAsyncArguments: Self { return .unavailableFromAsyncAttributeArguments } - static var unresolvedPatternExpr: Self { + @available(*, deprecated, renamed: "PatternExprSyntax") + public static var unresolvedPatternExpr: Self { return .patternExpr } - static var yieldExprList: Self { + @available(*, deprecated, renamed: "YieldedExpressionListSyntax") + public static var yieldExprList: Self { return .yieldedExpressionList } - static var yieldExprListElement: Self { + @available(*, deprecated, renamed: "YieldedExpressionSyntax") + public static var yieldExprListElement: Self { return .yieldedExpression } - static var yieldList: Self { + @available(*, deprecated, renamed: "YieldedExpressionsClauseSyntax") + public static var yieldList: Self { return .yieldedExpressionsClause } } diff --git a/Sources/SwiftSyntax/generated/SyntaxAnyVisitor.swift b/Sources/SwiftSyntax/generated/SyntaxAnyVisitor.swift index 5581f94333a..694fee15c35 100644 --- a/Sources/SwiftSyntax/generated/SyntaxAnyVisitor.swift +++ b/Sources/SwiftSyntax/generated/SyntaxAnyVisitor.swift @@ -272,19 +272,19 @@ open class SyntaxAnyVisitor: SyntaxVisitor { visitAnyPost(node._syntaxNode) } - override open func visit(_ node: CanImportExprSyntax) -> SyntaxVisitorContinueKind { + override open func visit(_ node: _CanImportExprSyntax) -> SyntaxVisitorContinueKind { return visitAny(node._syntaxNode) } - override open func visitPost(_ node: CanImportExprSyntax) { + override open func visitPost(_ node: _CanImportExprSyntax) { visitAnyPost(node._syntaxNode) } - override open func visit(_ node: CanImportVersionInfoSyntax) -> SyntaxVisitorContinueKind { + override open func visit(_ node: _CanImportVersionInfoSyntax) -> SyntaxVisitorContinueKind { return visitAny(node._syntaxNode) } - override open func visitPost(_ node: CanImportVersionInfoSyntax) { + override open func visitPost(_ node: _CanImportVersionInfoSyntax) { visitAnyPost(node._syntaxNode) } @@ -1370,20 +1370,6 @@ open class SyntaxAnyVisitor: SyntaxVisitor { visitAnyPost(node._syntaxNode) } - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif - override open func visit(_ node: LifetimeSpecifierArgumentsSyntax) -> SyntaxVisitorContinueKind { - return visitAny(node._syntaxNode) - } - - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif - override open func visitPost(_ node: LifetimeSpecifierArgumentsSyntax) { - visitAnyPost(node._syntaxNode) - } - #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) #endif diff --git a/Sources/SwiftSyntax/generated/SyntaxBaseNodes.swift b/Sources/SwiftSyntax/generated/SyntaxBaseNodes.swift index 7ff75ce92c4..f0952b03ded 100644 --- a/Sources/SwiftSyntax/generated/SyntaxBaseNodes.swift +++ b/Sources/SwiftSyntax/generated/SyntaxBaseNodes.swift @@ -135,12 +135,12 @@ extension DeclSyntaxProtocol { } } -public extension Syntax { +extension Syntax { /// Check whether the non-type erased version of this syntax node conforms to /// DeclSyntaxProtocol. /// /// - Note: This will incur an existential conversion. - func isProtocol(_: DeclSyntaxProtocol.Protocol) -> Bool { + public func isProtocol(_: DeclSyntaxProtocol.Protocol) -> Bool { return self.asProtocol(DeclSyntaxProtocol.self) != nil } @@ -148,7 +148,7 @@ public extension Syntax { /// DeclSyntaxProtocol. Otherwise return nil. /// /// - Note: This will incur an existential conversion. - func asProtocol(_: DeclSyntaxProtocol.Protocol) -> DeclSyntaxProtocol? { + public func asProtocol(_: DeclSyntaxProtocol.Protocol) -> DeclSyntaxProtocol? { return self.asProtocol(SyntaxProtocol.self) as? DeclSyntaxProtocol } } @@ -183,7 +183,7 @@ public struct DeclSyntax: DeclSyntaxProtocol, SyntaxHashable { public let _syntaxNode: Syntax /// Create a ``DeclSyntax`` node from a specialized syntax node. - public init(_ syntax: some DeclSyntaxProtocol) { + public init(_ syntax: __shared some DeclSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -191,14 +191,14 @@ public struct DeclSyntax: DeclSyntaxProtocol, SyntaxHashable { } /// Create a ``DeclSyntax`` node from a specialized optional syntax node. - public init?(_ syntax: (some DeclSyntaxProtocol)?) { + public init?(_ syntax: __shared (some DeclSyntaxProtocol)?) { guard let syntax = syntax else { return nil } self.init(syntax) } - public init(fromProtocol syntax: DeclSyntaxProtocol) { + public init(fromProtocol syntax: __shared DeclSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -206,14 +206,14 @@ public struct DeclSyntax: DeclSyntaxProtocol, SyntaxHashable { } /// Create a ``DeclSyntax`` node from a specialized optional syntax node. - public init?(fromProtocol syntax: DeclSyntaxProtocol?) { + public init?(fromProtocol syntax: __shared DeclSyntaxProtocol?) { guard let syntax = syntax else { return nil } self.init(fromProtocol: syntax) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { switch node.raw.kind { case .accessorDecl, .actorDecl, .associatedTypeDecl, .classDecl, .deinitializerDecl, .editorPlaceholderDecl, .enumCaseDecl, .enumDecl, .extensionDecl, .functionDecl, .ifConfigDecl, .importDecl, .initializerDecl, .macroDecl, .macroExpansionDecl, .missingDecl, .operatorDecl, .poundSourceLocation, .precedenceGroupDecl, .protocolDecl, .structDecl, .subscriptDecl, .typeAliasDecl, .variableDecl: self._syntaxNode = node._syntaxNode @@ -275,7 +275,7 @@ public struct DeclSyntax: DeclSyntaxProtocol, SyntaxHashable { /// deprecated to prevent incorrect casting. public protocol _LeafDeclSyntaxNodeProtocol: DeclSyntaxProtocol {} -public extension _LeafDeclSyntaxNodeProtocol { +extension _LeafDeclSyntaxNodeProtocol { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -283,7 +283,7 @@ public extension _LeafDeclSyntaxNodeProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -295,7 +295,7 @@ public extension _LeafDeclSyntaxNodeProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -308,7 +308,7 @@ public extension _LeafDeclSyntaxNodeProtocol { /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } @@ -436,12 +436,12 @@ extension ExprSyntaxProtocol { } } -public extension Syntax { +extension Syntax { /// Check whether the non-type erased version of this syntax node conforms to /// ExprSyntaxProtocol. /// /// - Note: This will incur an existential conversion. - func isProtocol(_: ExprSyntaxProtocol.Protocol) -> Bool { + public func isProtocol(_: ExprSyntaxProtocol.Protocol) -> Bool { return self.asProtocol(ExprSyntaxProtocol.self) != nil } @@ -449,7 +449,7 @@ public extension Syntax { /// ExprSyntaxProtocol. Otherwise return nil. /// /// - Note: This will incur an existential conversion. - func asProtocol(_: ExprSyntaxProtocol.Protocol) -> ExprSyntaxProtocol? { + public func asProtocol(_: ExprSyntaxProtocol.Protocol) -> ExprSyntaxProtocol? { return self.asProtocol(SyntaxProtocol.self) as? ExprSyntaxProtocol } } @@ -464,8 +464,6 @@ public extension Syntax { /// - ``BinaryOperatorExprSyntax`` /// - ``BooleanLiteralExprSyntax`` /// - ``BorrowExprSyntax`` -/// - ``CanImportExprSyntax`` -/// - ``CanImportVersionInfoSyntax`` /// - ``ClosureExprSyntax`` /// - ``ConsumeExprSyntax`` /// - ``CopyExprSyntax`` @@ -512,7 +510,7 @@ public struct ExprSyntax: ExprSyntaxProtocol, SyntaxHashable { public let _syntaxNode: Syntax /// Create a ``ExprSyntax`` node from a specialized syntax node. - public init(_ syntax: some ExprSyntaxProtocol) { + public init(_ syntax: __shared some ExprSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -520,14 +518,14 @@ public struct ExprSyntax: ExprSyntaxProtocol, SyntaxHashable { } /// Create a ``ExprSyntax`` node from a specialized optional syntax node. - public init?(_ syntax: (some ExprSyntaxProtocol)?) { + public init?(_ syntax: __shared (some ExprSyntaxProtocol)?) { guard let syntax = syntax else { return nil } self.init(syntax) } - public init(fromProtocol syntax: ExprSyntaxProtocol) { + public init(fromProtocol syntax: __shared ExprSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -535,16 +533,16 @@ public struct ExprSyntax: ExprSyntaxProtocol, SyntaxHashable { } /// Create a ``ExprSyntax`` node from a specialized optional syntax node. - public init?(fromProtocol syntax: ExprSyntaxProtocol?) { + public init?(fromProtocol syntax: __shared ExprSyntaxProtocol?) { guard let syntax = syntax else { return nil } self.init(fromProtocol: syntax) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { switch node.raw.kind { - case .arrayExpr, .arrowExpr, .asExpr, .assignmentExpr, .awaitExpr, .binaryOperatorExpr, .booleanLiteralExpr, .borrowExpr, .canImportExpr, .canImportVersionInfo, .closureExpr, .consumeExpr, .copyExpr, .declReferenceExpr, .dictionaryExpr, .discardAssignmentExpr, .doExpr, .editorPlaceholderExpr, .floatLiteralExpr, .forceUnwrapExpr, .functionCallExpr, .genericSpecializationExpr, .ifExpr, .inOutExpr, .infixOperatorExpr, .integerLiteralExpr, .isExpr, .keyPathExpr, .macroExpansionExpr, .memberAccessExpr, .missingExpr, .nilLiteralExpr, .optionalChainingExpr, .packElementExpr, .packExpansionExpr, .patternExpr, .postfixIfConfigExpr, .postfixOperatorExpr, .prefixOperatorExpr, .regexLiteralExpr, .sequenceExpr, .simpleStringLiteralExpr, .stringLiteralExpr, .subscriptCallExpr, .superExpr, .switchExpr, .ternaryExpr, .tryExpr, .tupleExpr, .typeExpr, .unresolvedAsExpr, .unresolvedIsExpr, .unresolvedTernaryExpr: + case .arrayExpr, .arrowExpr, .asExpr, .assignmentExpr, .awaitExpr, .binaryOperatorExpr, .booleanLiteralExpr, .borrowExpr, ._canImportExpr, ._canImportVersionInfo, .closureExpr, .consumeExpr, .copyExpr, .declReferenceExpr, .dictionaryExpr, .discardAssignmentExpr, .doExpr, .editorPlaceholderExpr, .floatLiteralExpr, .forceUnwrapExpr, .functionCallExpr, .genericSpecializationExpr, .ifExpr, .inOutExpr, .infixOperatorExpr, .integerLiteralExpr, .isExpr, .keyPathExpr, .macroExpansionExpr, .memberAccessExpr, .missingExpr, .nilLiteralExpr, .optionalChainingExpr, .packElementExpr, .packExpansionExpr, .patternExpr, .postfixIfConfigExpr, .postfixOperatorExpr, .prefixOperatorExpr, .regexLiteralExpr, .sequenceExpr, .simpleStringLiteralExpr, .stringLiteralExpr, .subscriptCallExpr, .superExpr, .switchExpr, .ternaryExpr, .tryExpr, .tupleExpr, .typeExpr, .unresolvedAsExpr, .unresolvedIsExpr, .unresolvedTernaryExpr: self._syntaxNode = node._syntaxNode default: return nil @@ -577,8 +575,8 @@ public struct ExprSyntax: ExprSyntaxProtocol, SyntaxHashable { .node(BinaryOperatorExprSyntax.self), .node(BooleanLiteralExprSyntax.self), .node(BorrowExprSyntax.self), - .node(CanImportExprSyntax.self), - .node(CanImportVersionInfoSyntax.self), + .node(_CanImportExprSyntax.self), + .node(_CanImportVersionInfoSyntax.self), .node(ClosureExprSyntax.self), .node(ConsumeExprSyntax.self), .node(CopyExprSyntax.self), @@ -633,7 +631,7 @@ public struct ExprSyntax: ExprSyntaxProtocol, SyntaxHashable { /// deprecated to prevent incorrect casting. public protocol _LeafExprSyntaxNodeProtocol: ExprSyntaxProtocol {} -public extension _LeafExprSyntaxNodeProtocol { +extension _LeafExprSyntaxNodeProtocol { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -641,7 +639,7 @@ public extension _LeafExprSyntaxNodeProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -653,7 +651,7 @@ public extension _LeafExprSyntaxNodeProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -666,7 +664,7 @@ public extension _LeafExprSyntaxNodeProtocol { /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } @@ -794,12 +792,12 @@ extension PatternSyntaxProtocol { } } -public extension Syntax { +extension Syntax { /// Check whether the non-type erased version of this syntax node conforms to /// PatternSyntaxProtocol. /// /// - Note: This will incur an existential conversion. - func isProtocol(_: PatternSyntaxProtocol.Protocol) -> Bool { + public func isProtocol(_: PatternSyntaxProtocol.Protocol) -> Bool { return self.asProtocol(PatternSyntaxProtocol.self) != nil } @@ -807,7 +805,7 @@ public extension Syntax { /// PatternSyntaxProtocol. Otherwise return nil. /// /// - Note: This will incur an existential conversion. - func asProtocol(_: PatternSyntaxProtocol.Protocol) -> PatternSyntaxProtocol? { + public func asProtocol(_: PatternSyntaxProtocol.Protocol) -> PatternSyntaxProtocol? { return self.asProtocol(SyntaxProtocol.self) as? PatternSyntaxProtocol } } @@ -825,7 +823,7 @@ public struct PatternSyntax: PatternSyntaxProtocol, SyntaxHashable { public let _syntaxNode: Syntax /// Create a ``PatternSyntax`` node from a specialized syntax node. - public init(_ syntax: some PatternSyntaxProtocol) { + public init(_ syntax: __shared some PatternSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -833,14 +831,14 @@ public struct PatternSyntax: PatternSyntaxProtocol, SyntaxHashable { } /// Create a ``PatternSyntax`` node from a specialized optional syntax node. - public init?(_ syntax: (some PatternSyntaxProtocol)?) { + public init?(_ syntax: __shared (some PatternSyntaxProtocol)?) { guard let syntax = syntax else { return nil } self.init(syntax) } - public init(fromProtocol syntax: PatternSyntaxProtocol) { + public init(fromProtocol syntax: __shared PatternSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -848,14 +846,14 @@ public struct PatternSyntax: PatternSyntaxProtocol, SyntaxHashable { } /// Create a ``PatternSyntax`` node from a specialized optional syntax node. - public init?(fromProtocol syntax: PatternSyntaxProtocol?) { + public init?(fromProtocol syntax: __shared PatternSyntaxProtocol?) { guard let syntax = syntax else { return nil } self.init(fromProtocol: syntax) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { switch node.raw.kind { case .expressionPattern, .identifierPattern, .isTypePattern, .missingPattern, .tuplePattern, .valueBindingPattern, .wildcardPattern: self._syntaxNode = node._syntaxNode @@ -900,7 +898,7 @@ public struct PatternSyntax: PatternSyntaxProtocol, SyntaxHashable { /// deprecated to prevent incorrect casting. public protocol _LeafPatternSyntaxNodeProtocol: PatternSyntaxProtocol {} -public extension _LeafPatternSyntaxNodeProtocol { +extension _LeafPatternSyntaxNodeProtocol { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -908,7 +906,7 @@ public extension _LeafPatternSyntaxNodeProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -920,7 +918,7 @@ public extension _LeafPatternSyntaxNodeProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -933,7 +931,7 @@ public extension _LeafPatternSyntaxNodeProtocol { /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } @@ -1061,12 +1059,12 @@ extension StmtSyntaxProtocol { } } -public extension Syntax { +extension Syntax { /// Check whether the non-type erased version of this syntax node conforms to /// StmtSyntaxProtocol. /// /// - Note: This will incur an existential conversion. - func isProtocol(_: StmtSyntaxProtocol.Protocol) -> Bool { + public func isProtocol(_: StmtSyntaxProtocol.Protocol) -> Bool { return self.asProtocol(StmtSyntaxProtocol.self) != nil } @@ -1074,7 +1072,7 @@ public extension Syntax { /// StmtSyntaxProtocol. Otherwise return nil. /// /// - Note: This will incur an existential conversion. - func asProtocol(_: StmtSyntaxProtocol.Protocol) -> StmtSyntaxProtocol? { + public func asProtocol(_: StmtSyntaxProtocol.Protocol) -> StmtSyntaxProtocol? { return self.asProtocol(SyntaxProtocol.self) as? StmtSyntaxProtocol } } @@ -1101,7 +1099,7 @@ public struct StmtSyntax: StmtSyntaxProtocol, SyntaxHashable { public let _syntaxNode: Syntax /// Create a ``StmtSyntax`` node from a specialized syntax node. - public init(_ syntax: some StmtSyntaxProtocol) { + public init(_ syntax: __shared some StmtSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -1109,14 +1107,14 @@ public struct StmtSyntax: StmtSyntaxProtocol, SyntaxHashable { } /// Create a ``StmtSyntax`` node from a specialized optional syntax node. - public init?(_ syntax: (some StmtSyntaxProtocol)?) { + public init?(_ syntax: __shared (some StmtSyntaxProtocol)?) { guard let syntax = syntax else { return nil } self.init(syntax) } - public init(fromProtocol syntax: StmtSyntaxProtocol) { + public init(fromProtocol syntax: __shared StmtSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -1124,14 +1122,14 @@ public struct StmtSyntax: StmtSyntaxProtocol, SyntaxHashable { } /// Create a ``StmtSyntax`` node from a specialized optional syntax node. - public init?(fromProtocol syntax: StmtSyntaxProtocol?) { + public init?(fromProtocol syntax: __shared StmtSyntaxProtocol?) { guard let syntax = syntax else { return nil } self.init(fromProtocol: syntax) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { switch node.raw.kind { case .breakStmt, .continueStmt, .deferStmt, .discardStmt, .doStmt, .expressionStmt, .fallThroughStmt, .forStmt, .guardStmt, .labeledStmt, .missingStmt, .repeatStmt, .returnStmt, .thenStmt, .throwStmt, .whileStmt, .yieldStmt: self._syntaxNode = node._syntaxNode @@ -1186,7 +1184,7 @@ public struct StmtSyntax: StmtSyntaxProtocol, SyntaxHashable { /// deprecated to prevent incorrect casting. public protocol _LeafStmtSyntaxNodeProtocol: StmtSyntaxProtocol {} -public extension _LeafStmtSyntaxNodeProtocol { +extension _LeafStmtSyntaxNodeProtocol { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -1194,7 +1192,7 @@ public extension _LeafStmtSyntaxNodeProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -1206,7 +1204,7 @@ public extension _LeafStmtSyntaxNodeProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -1219,7 +1217,7 @@ public extension _LeafStmtSyntaxNodeProtocol { /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } @@ -1347,12 +1345,12 @@ extension TypeSyntaxProtocol { } } -public extension Syntax { +extension Syntax { /// Check whether the non-type erased version of this syntax node conforms to /// TypeSyntaxProtocol. /// /// - Note: This will incur an existential conversion. - func isProtocol(_: TypeSyntaxProtocol.Protocol) -> Bool { + public func isProtocol(_: TypeSyntaxProtocol.Protocol) -> Bool { return self.asProtocol(TypeSyntaxProtocol.self) != nil } @@ -1360,7 +1358,7 @@ public extension Syntax { /// TypeSyntaxProtocol. Otherwise return nil. /// /// - Note: This will incur an existential conversion. - func asProtocol(_: TypeSyntaxProtocol.Protocol) -> TypeSyntaxProtocol? { + public func asProtocol(_: TypeSyntaxProtocol.Protocol) -> TypeSyntaxProtocol? { return self.asProtocol(SyntaxProtocol.self) as? TypeSyntaxProtocol } } @@ -1389,7 +1387,7 @@ public struct TypeSyntax: TypeSyntaxProtocol, SyntaxHashable { public let _syntaxNode: Syntax /// Create a ``TypeSyntax`` node from a specialized syntax node. - public init(_ syntax: some TypeSyntaxProtocol) { + public init(_ syntax: __shared some TypeSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -1397,14 +1395,14 @@ public struct TypeSyntax: TypeSyntaxProtocol, SyntaxHashable { } /// Create a ``TypeSyntax`` node from a specialized optional syntax node. - public init?(_ syntax: (some TypeSyntaxProtocol)?) { + public init?(_ syntax: __shared (some TypeSyntaxProtocol)?) { guard let syntax = syntax else { return nil } self.init(syntax) } - public init(fromProtocol syntax: TypeSyntaxProtocol) { + public init(fromProtocol syntax: __shared TypeSyntaxProtocol) { // We know this cast is going to succeed. Go through init(_: SyntaxData) // to do a sanity check and verify the kind matches in debug builds and get // maximum performance in release builds. @@ -1412,14 +1410,14 @@ public struct TypeSyntax: TypeSyntaxProtocol, SyntaxHashable { } /// Create a ``TypeSyntax`` node from a specialized optional syntax node. - public init?(fromProtocol syntax: TypeSyntaxProtocol?) { + public init?(fromProtocol syntax: __shared TypeSyntaxProtocol?) { guard let syntax = syntax else { return nil } self.init(fromProtocol: syntax) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { switch node.raw.kind { case .arrayType, .attributedType, .classRestrictionType, .compositionType, .dictionaryType, .functionType, .identifierType, .implicitlyUnwrappedOptionalType, .memberType, .metatypeType, .missingType, .namedOpaqueReturnType, .optionalType, .packElementType, .packExpansionType, .someOrAnyType, .suppressedType, .tupleType: self._syntaxNode = node._syntaxNode @@ -1475,7 +1473,7 @@ public struct TypeSyntax: TypeSyntaxProtocol, SyntaxHashable { /// deprecated to prevent incorrect casting. public protocol _LeafTypeSyntaxNodeProtocol: TypeSyntaxProtocol {} -public extension _LeafTypeSyntaxNodeProtocol { +extension _LeafTypeSyntaxNodeProtocol { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -1483,7 +1481,7 @@ public extension _LeafTypeSyntaxNodeProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -1495,7 +1493,7 @@ public extension _LeafTypeSyntaxNodeProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -1508,7 +1506,7 @@ public extension _LeafTypeSyntaxNodeProtocol { /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } @@ -1546,8 +1544,8 @@ extension Syntax { .node(BooleanLiteralExprSyntax.self), .node(BorrowExprSyntax.self), .node(BreakStmtSyntax.self), - .node(CanImportExprSyntax.self), - .node(CanImportVersionInfoSyntax.self), + .node(_CanImportExprSyntax.self), + .node(_CanImportVersionInfoSyntax.self), .node(CatchClauseListSyntax.self), .node(CatchClauseSyntax.self), .node(CatchItemListSyntax.self), @@ -1681,7 +1679,6 @@ extension Syntax { .node(LayoutRequirementSyntax.self), .node(LifetimeSpecifierArgumentListSyntax.self), .node(LifetimeSpecifierArgumentSyntax.self), - .node(LifetimeSpecifierArgumentsSyntax.self), .node(LifetimeTypeSpecifierSyntax.self), .node(MacroDeclSyntax.self), .node(MacroExpansionDeclSyntax.self), @@ -1814,7 +1811,7 @@ extension Syntax { /// deprecated to prevent incorrect casting. public protocol _LeafSyntaxNodeProtocol: SyntaxProtocol {} -public extension _LeafSyntaxNodeProtocol { +extension _LeafSyntaxNodeProtocol { /// Checks if the current leaf syntax node can be cast to a different specified type. /// /// - Returns: `false` since the leaf node cannot be cast to a different specified type. @@ -1822,7 +1819,7 @@ public extension _LeafSyntaxNodeProtocol { /// - Note: This method overloads the general `is` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `is`(_ syntaxType: S.Type) -> Bool { + public func `is`(_ syntaxType: S.Type) -> Bool { return false } @@ -1834,7 +1831,7 @@ public extension _LeafSyntaxNodeProtocol { /// - Note: This method overloads the general `as` method and is marked as deprecated to produce a warning, /// informing the user that the cast will always fail. @available(*, deprecated, message: "This cast will always fail") - func `as`(_ syntaxType: S.Type) -> S? { + public func `as`(_ syntaxType: S.Type) -> S? { return nil } @@ -1847,7 +1844,7 @@ public extension _LeafSyntaxNodeProtocol { /// informing the user that the cast will always fail. /// - Warning: Invoking this method will lead to a fatal error. @available(*, deprecated, message: "This cast will always fail") - func cast(_ syntaxType: S.Type) -> S { + public func cast(_ syntaxType: S.Type) -> S { fatalError("\(Self.self) cannot be cast to \(S.self)") } } diff --git a/Sources/SwiftSyntax/generated/SyntaxEnum.swift b/Sources/SwiftSyntax/generated/SyntaxEnum.swift index ddffa06852c..fef31916caa 100644 --- a/Sources/SwiftSyntax/generated/SyntaxEnum.swift +++ b/Sources/SwiftSyntax/generated/SyntaxEnum.swift @@ -42,8 +42,8 @@ public enum SyntaxEnum: Sendable { case booleanLiteralExpr(BooleanLiteralExprSyntax) case borrowExpr(BorrowExprSyntax) case breakStmt(BreakStmtSyntax) - case canImportExpr(CanImportExprSyntax) - case canImportVersionInfo(CanImportVersionInfoSyntax) + case _canImportExpr(_CanImportExprSyntax) + case _canImportVersionInfo(_CanImportVersionInfoSyntax) case catchClauseList(CatchClauseListSyntax) case catchClause(CatchClauseSyntax) case catchItemList(CatchItemListSyntax) @@ -189,10 +189,6 @@ public enum SyntaxEnum: Sendable { #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) #endif - case lifetimeSpecifierArguments(LifetimeSpecifierArgumentsSyntax) - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif case lifetimeTypeSpecifier(LifetimeTypeSpecifierSyntax) case macroDecl(MacroDeclSyntax) case macroExpansionDecl(MacroExpansionDeclSyntax) @@ -319,9 +315,9 @@ public enum SyntaxEnum: Sendable { case yieldedExpressionsClause(YieldedExpressionsClauseSyntax) } -public extension Syntax { +extension Syntax { /// Get an enum that can be used to exhaustively switch over all syntax nodes. - func `as`(_: SyntaxEnum.Type) -> SyntaxEnum { + public func `as`(_: SyntaxEnum.Type) -> SyntaxEnum { switch raw.kind { case .token: return .token(TokenSyntax(self)!) @@ -379,10 +375,10 @@ public extension Syntax { return .borrowExpr(BorrowExprSyntax(self)!) case .breakStmt: return .breakStmt(BreakStmtSyntax(self)!) - case .canImportExpr: - return .canImportExpr(CanImportExprSyntax(self)!) - case .canImportVersionInfo: - return .canImportVersionInfo(CanImportVersionInfoSyntax(self)!) + case ._canImportExpr: + return ._canImportExpr(_CanImportExprSyntax(self)!) + case ._canImportVersionInfo: + return ._canImportVersionInfo(_CanImportVersionInfoSyntax(self)!) case .catchClauseList: return .catchClauseList(CatchClauseListSyntax(self)!) case .catchClause: @@ -649,8 +645,6 @@ public extension Syntax { return .lifetimeSpecifierArgumentList(LifetimeSpecifierArgumentListSyntax(self)!) case .lifetimeSpecifierArgument: return .lifetimeSpecifierArgument(LifetimeSpecifierArgumentSyntax(self)!) - case .lifetimeSpecifierArguments: - return .lifetimeSpecifierArguments(LifetimeSpecifierArgumentsSyntax(self)!) case .lifetimeTypeSpecifier: return .lifetimeTypeSpecifier(LifetimeTypeSpecifierSyntax(self)!) case .macroDecl: @@ -925,9 +919,9 @@ public enum DeclSyntaxEnum { case variableDecl(VariableDeclSyntax) } -public extension DeclSyntax { +extension DeclSyntax { /// Get an enum that can be used to exhaustively switch over all Decl syntax nodes. - func `as`(_: DeclSyntaxEnum.Type) -> DeclSyntaxEnum { + public func `as`(_: DeclSyntaxEnum.Type) -> DeclSyntaxEnum { switch raw.kind { case .accessorDecl: return .accessorDecl(AccessorDeclSyntax(self)!) @@ -993,8 +987,8 @@ public enum ExprSyntaxEnum { case binaryOperatorExpr(BinaryOperatorExprSyntax) case booleanLiteralExpr(BooleanLiteralExprSyntax) case borrowExpr(BorrowExprSyntax) - case canImportExpr(CanImportExprSyntax) - case canImportVersionInfo(CanImportVersionInfoSyntax) + case _canImportExpr(_CanImportExprSyntax) + case _canImportVersionInfo(_CanImportVersionInfoSyntax) case closureExpr(ClosureExprSyntax) case consumeExpr(ConsumeExprSyntax) case copyExpr(CopyExprSyntax) @@ -1043,9 +1037,9 @@ public enum ExprSyntaxEnum { case unresolvedTernaryExpr(UnresolvedTernaryExprSyntax) } -public extension ExprSyntax { +extension ExprSyntax { /// Get an enum that can be used to exhaustively switch over all Expr syntax nodes. - func `as`(_: ExprSyntaxEnum.Type) -> ExprSyntaxEnum { + public func `as`(_: ExprSyntaxEnum.Type) -> ExprSyntaxEnum { switch raw.kind { case .arrayExpr: return .arrayExpr(ArrayExprSyntax(self)!) @@ -1063,10 +1057,10 @@ public extension ExprSyntax { return .booleanLiteralExpr(BooleanLiteralExprSyntax(self)!) case .borrowExpr: return .borrowExpr(BorrowExprSyntax(self)!) - case .canImportExpr: - return .canImportExpr(CanImportExprSyntax(self)!) - case .canImportVersionInfo: - return .canImportVersionInfo(CanImportVersionInfoSyntax(self)!) + case ._canImportExpr: + return ._canImportExpr(_CanImportExprSyntax(self)!) + case ._canImportVersionInfo: + return ._canImportVersionInfo(_CanImportVersionInfoSyntax(self)!) case .closureExpr: return .closureExpr(ClosureExprSyntax(self)!) case .consumeExpr: @@ -1170,9 +1164,9 @@ public enum PatternSyntaxEnum { case wildcardPattern(WildcardPatternSyntax) } -public extension PatternSyntax { +extension PatternSyntax { /// Get an enum that can be used to exhaustively switch over all Pattern syntax nodes. - func `as`(_: PatternSyntaxEnum.Type) -> PatternSyntaxEnum { + public func `as`(_: PatternSyntaxEnum.Type) -> PatternSyntaxEnum { switch raw.kind { case .expressionPattern: return .expressionPattern(ExpressionPatternSyntax(self)!) @@ -1218,9 +1212,9 @@ public enum StmtSyntaxEnum { case yieldStmt(YieldStmtSyntax) } -public extension StmtSyntax { +extension StmtSyntax { /// Get an enum that can be used to exhaustively switch over all Stmt syntax nodes. - func `as`(_: StmtSyntaxEnum.Type) -> StmtSyntaxEnum { + public func `as`(_: StmtSyntaxEnum.Type) -> StmtSyntaxEnum { switch raw.kind { case .breakStmt: return .breakStmt(BreakStmtSyntax(self)!) @@ -1284,9 +1278,9 @@ public enum TypeSyntaxEnum { case tupleType(TupleTypeSyntax) } -public extension TypeSyntax { +extension TypeSyntax { /// Get an enum that can be used to exhaustively switch over all Type syntax nodes. - func `as`(_: TypeSyntaxEnum.Type) -> TypeSyntaxEnum { + public func `as`(_: TypeSyntaxEnum.Type) -> TypeSyntaxEnum { switch raw.kind { case .arrayType: return .arrayType(ArrayTypeSyntax(self)!) diff --git a/Sources/SwiftSyntax/generated/SyntaxKind.swift b/Sources/SwiftSyntax/generated/SyntaxKind.swift index 103e0304705..b8e5d120a01 100644 --- a/Sources/SwiftSyntax/generated/SyntaxKind.swift +++ b/Sources/SwiftSyntax/generated/SyntaxKind.swift @@ -42,8 +42,8 @@ public enum SyntaxKind: Sendable { case booleanLiteralExpr case borrowExpr case breakStmt - case canImportExpr - case canImportVersionInfo + case _canImportExpr + case _canImportVersionInfo case catchClauseList case catchClause case catchItemList @@ -189,10 +189,6 @@ public enum SyntaxKind: Sendable { #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) #endif - case lifetimeSpecifierArguments - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif case lifetimeTypeSpecifier case macroDecl case macroExpansionDecl @@ -504,10 +500,10 @@ public enum SyntaxKind: Sendable { return BorrowExprSyntax.self case .breakStmt: return BreakStmtSyntax.self - case .canImportExpr: - return CanImportExprSyntax.self - case .canImportVersionInfo: - return CanImportVersionInfoSyntax.self + case ._canImportExpr: + return _CanImportExprSyntax.self + case ._canImportVersionInfo: + return _CanImportVersionInfoSyntax.self case .catchClauseList: return CatchClauseListSyntax.self case .catchClause: @@ -774,8 +770,6 @@ public enum SyntaxKind: Sendable { return LifetimeSpecifierArgumentListSyntax.self case .lifetimeSpecifierArgument: return LifetimeSpecifierArgumentSyntax.self - case .lifetimeSpecifierArguments: - return LifetimeSpecifierArgumentsSyntax.self case .lifetimeTypeSpecifier: return LifetimeTypeSpecifierSyntax.self case .macroDecl: diff --git a/Sources/SwiftSyntax/generated/SyntaxRewriter.swift b/Sources/SwiftSyntax/generated/SyntaxRewriter.swift index e9f55427e02..184d50f712f 100644 --- a/Sources/SwiftSyntax/generated/SyntaxRewriter.swift +++ b/Sources/SwiftSyntax/generated/SyntaxRewriter.swift @@ -24,13 +24,17 @@ open class SyntaxRewriter { public let viewMode: SyntaxTreeViewMode + /// 'Syntax' object factory recycling 'Syntax.Info' instances. + private let nodeFactory: SyntaxNodeFactory = SyntaxNodeFactory() + public init(viewMode: SyntaxTreeViewMode = .sourceAccurate) { self.viewMode = viewMode } /// Rewrite `node`, keeping its parent unless `detach` is `true`. public func rewrite(_ node: some SyntaxProtocol, detach: Bool = false) -> Syntax { - let rewritten = self.dispatchVisit(Syntax(node)) + var rewritten = Syntax(node) + self.dispatchVisit(&rewritten) if detach { return rewritten } @@ -73,599 +77,603 @@ open class SyntaxRewriter { /// - Returns: the rewritten node @available(*, deprecated, renamed: "rewrite(_:detach:)") public func visit(_ node: Syntax) -> Syntax { - return dispatchVisit(node) + var rewritten = node + dispatchVisit(&rewritten) + return rewritten } public func visit(_ node: T) -> T { - return dispatchVisit(Syntax(node)).cast(T.self) + var rewritten = Syntax(node) + dispatchVisit(&rewritten) + return rewritten.cast(T.self) } /// Visit a ``AccessorBlockSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AccessorBlockSyntax) -> AccessorBlockSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AccessorBlockSyntax.self) } /// Visit a ``AccessorDeclListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AccessorDeclListSyntax) -> AccessorDeclListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AccessorDeclListSyntax.self) } /// Visit a ``AccessorDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AccessorDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(AccessorDeclSyntax.self)) } /// Visit a ``AccessorEffectSpecifiersSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AccessorEffectSpecifiersSyntax) -> AccessorEffectSpecifiersSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AccessorEffectSpecifiersSyntax.self) } /// Visit a ``AccessorParametersSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AccessorParametersSyntax) -> AccessorParametersSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AccessorParametersSyntax.self) } /// Visit a ``ActorDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ActorDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(ActorDeclSyntax.self)) } /// Visit a ``ArrayElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ArrayElementListSyntax) -> ArrayElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ArrayElementListSyntax.self) } /// Visit a ``ArrayElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ArrayElementSyntax) -> ArrayElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ArrayElementSyntax.self) } /// Visit a ``ArrayExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ArrayExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(ArrayExprSyntax.self)) } /// Visit a ``ArrayTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ArrayTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(ArrayTypeSyntax.self)) } /// Visit a ``ArrowExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ArrowExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(ArrowExprSyntax.self)) } /// Visit a ``AsExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AsExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(AsExprSyntax.self)) } /// Visit a ``AssignmentExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AssignmentExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(AssignmentExprSyntax.self)) } /// Visit a ``AssociatedTypeDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AssociatedTypeDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(AssociatedTypeDeclSyntax.self)) } /// Visit a ``AttributeListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AttributeListSyntax) -> AttributeListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AttributeListSyntax.self) } /// Visit a ``AttributeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AttributeSyntax) -> AttributeSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AttributeSyntax.self) } /// Visit a ``AttributedTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AttributedTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(AttributedTypeSyntax.self)) } /// Visit a ``AvailabilityArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AvailabilityArgumentListSyntax) -> AvailabilityArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AvailabilityArgumentListSyntax.self) } /// Visit a ``AvailabilityArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AvailabilityArgumentSyntax) -> AvailabilityArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AvailabilityArgumentSyntax.self) } /// Visit a ``AvailabilityConditionSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AvailabilityConditionSyntax) -> AvailabilityConditionSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AvailabilityConditionSyntax.self) } /// Visit a ``AvailabilityLabeledArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AvailabilityLabeledArgumentSyntax) -> AvailabilityLabeledArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(AvailabilityLabeledArgumentSyntax.self) } /// Visit a ``AwaitExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: AwaitExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(AwaitExprSyntax.self)) } /// Visit a ``BackDeployedAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: BackDeployedAttributeArgumentsSyntax) -> BackDeployedAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(BackDeployedAttributeArgumentsSyntax.self) } /// Visit a ``BinaryOperatorExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: BinaryOperatorExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(BinaryOperatorExprSyntax.self)) } /// Visit a ``BooleanLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: BooleanLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(BooleanLiteralExprSyntax.self)) } /// Visit a ``BorrowExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: BorrowExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(BorrowExprSyntax.self)) } /// Visit a ``BreakStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: BreakStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(BreakStmtSyntax.self)) } - /// Visit a ``CanImportExprSyntax``. + /// Visit a `_CanImportExprSyntax`. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node - open func visit(_ node: CanImportExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + open func visit(_ node: _CanImportExprSyntax) -> ExprSyntax { + return ExprSyntax(visitChildren(node._syntaxNode).cast(_CanImportExprSyntax.self)) } - /// Visit a ``CanImportVersionInfoSyntax``. + /// Visit a `_CanImportVersionInfoSyntax`. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node - open func visit(_ node: CanImportVersionInfoSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + open func visit(_ node: _CanImportVersionInfoSyntax) -> ExprSyntax { + return ExprSyntax(visitChildren(node._syntaxNode).cast(_CanImportVersionInfoSyntax.self)) } /// Visit a ``CatchClauseListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CatchClauseListSyntax) -> CatchClauseListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CatchClauseListSyntax.self) } /// Visit a ``CatchClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CatchClauseSyntax) -> CatchClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CatchClauseSyntax.self) } /// Visit a ``CatchItemListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CatchItemListSyntax) -> CatchItemListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CatchItemListSyntax.self) } /// Visit a ``CatchItemSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CatchItemSyntax) -> CatchItemSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CatchItemSyntax.self) } /// Visit a ``ClassDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClassDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(ClassDeclSyntax.self)) } /// Visit a ``ClassRestrictionTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClassRestrictionTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(ClassRestrictionTypeSyntax.self)) } /// Visit a ``ClosureCaptureClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureCaptureClauseSyntax) -> ClosureCaptureClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureCaptureClauseSyntax.self) } /// Visit a ``ClosureCaptureListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureCaptureListSyntax) -> ClosureCaptureListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureCaptureListSyntax.self) } /// Visit a ``ClosureCaptureSpecifierSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureCaptureSpecifierSyntax) -> ClosureCaptureSpecifierSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureCaptureSpecifierSyntax.self) } /// Visit a ``ClosureCaptureSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureCaptureSyntax) -> ClosureCaptureSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureCaptureSyntax.self) } /// Visit a ``ClosureExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(ClosureExprSyntax.self)) } /// Visit a ``ClosureParameterClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureParameterClauseSyntax) -> ClosureParameterClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureParameterClauseSyntax.self) } /// Visit a ``ClosureParameterListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureParameterListSyntax) -> ClosureParameterListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureParameterListSyntax.self) } /// Visit a ``ClosureParameterSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureParameterSyntax) -> ClosureParameterSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureParameterSyntax.self) } /// Visit a ``ClosureShorthandParameterListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureShorthandParameterListSyntax) -> ClosureShorthandParameterListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureShorthandParameterListSyntax.self) } /// Visit a ``ClosureShorthandParameterSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureShorthandParameterSyntax) -> ClosureShorthandParameterSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureShorthandParameterSyntax.self) } /// Visit a ``ClosureSignatureSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ClosureSignatureSyntax) -> ClosureSignatureSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ClosureSignatureSyntax.self) } /// Visit a ``CodeBlockItemListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CodeBlockItemListSyntax) -> CodeBlockItemListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CodeBlockItemListSyntax.self) } /// Visit a ``CodeBlockItemSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CodeBlockItemSyntax) -> CodeBlockItemSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CodeBlockItemSyntax.self) } /// Visit a ``CodeBlockSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CodeBlockSyntax) -> CodeBlockSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CodeBlockSyntax.self) } /// Visit a ``CompositionTypeElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CompositionTypeElementListSyntax) -> CompositionTypeElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CompositionTypeElementListSyntax.self) } /// Visit a ``CompositionTypeElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CompositionTypeElementSyntax) -> CompositionTypeElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(CompositionTypeElementSyntax.self) } /// Visit a ``CompositionTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CompositionTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(CompositionTypeSyntax.self)) } /// Visit a ``ConditionElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ConditionElementListSyntax) -> ConditionElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ConditionElementListSyntax.self) } /// Visit a ``ConditionElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ConditionElementSyntax) -> ConditionElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ConditionElementSyntax.self) } /// Visit a ``ConformanceRequirementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ConformanceRequirementSyntax) -> ConformanceRequirementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ConformanceRequirementSyntax.self) } /// Visit a ``ConsumeExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ConsumeExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(ConsumeExprSyntax.self)) } /// Visit a ``ContinueStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ContinueStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(ContinueStmtSyntax.self)) } /// Visit a ``ConventionAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ConventionAttributeArgumentsSyntax) -> ConventionAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ConventionAttributeArgumentsSyntax.self) } /// Visit a ``ConventionWitnessMethodAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ConventionWitnessMethodAttributeArgumentsSyntax) -> ConventionWitnessMethodAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ConventionWitnessMethodAttributeArgumentsSyntax.self) } /// Visit a ``CopyExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: CopyExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(CopyExprSyntax.self)) } /// Visit a ``DeclModifierDetailSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclModifierDetailSyntax) -> DeclModifierDetailSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeclModifierDetailSyntax.self) } /// Visit a ``DeclModifierListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclModifierListSyntax) -> DeclModifierListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeclModifierListSyntax.self) } /// Visit a ``DeclModifierSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclModifierSyntax) -> DeclModifierSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeclModifierSyntax.self) } /// Visit a ``DeclNameArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclNameArgumentListSyntax) -> DeclNameArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeclNameArgumentListSyntax.self) } /// Visit a ``DeclNameArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclNameArgumentSyntax) -> DeclNameArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeclNameArgumentSyntax.self) } /// Visit a ``DeclNameArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclNameArgumentsSyntax) -> DeclNameArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeclNameArgumentsSyntax.self) } /// Visit a ``DeclReferenceExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeclReferenceExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(DeclReferenceExprSyntax.self)) } /// Visit a ``DeferStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeferStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(DeferStmtSyntax.self)) } /// Visit a ``DeinitializerDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeinitializerDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(DeinitializerDeclSyntax.self)) } /// Visit a ``DeinitializerEffectSpecifiersSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DeinitializerEffectSpecifiersSyntax) -> DeinitializerEffectSpecifiersSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DeinitializerEffectSpecifiersSyntax.self) } /// Visit a ``DerivativeAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DerivativeAttributeArgumentsSyntax) -> DerivativeAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DerivativeAttributeArgumentsSyntax.self) } /// Visit a ``DesignatedTypeListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DesignatedTypeListSyntax) -> DesignatedTypeListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DesignatedTypeListSyntax.self) } /// Visit a ``DesignatedTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DesignatedTypeSyntax) -> DesignatedTypeSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DesignatedTypeSyntax.self) } /// Visit a ``DictionaryElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DictionaryElementListSyntax) -> DictionaryElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DictionaryElementListSyntax.self) } /// Visit a ``DictionaryElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DictionaryElementSyntax) -> DictionaryElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DictionaryElementSyntax.self) } /// Visit a ``DictionaryExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DictionaryExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(DictionaryExprSyntax.self)) } /// Visit a ``DictionaryTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DictionaryTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(DictionaryTypeSyntax.self)) } /// Visit a ``DifferentiabilityArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DifferentiabilityArgumentListSyntax) -> DifferentiabilityArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DifferentiabilityArgumentListSyntax.self) } /// Visit a ``DifferentiabilityArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DifferentiabilityArgumentSyntax) -> DifferentiabilityArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DifferentiabilityArgumentSyntax.self) } /// Visit a ``DifferentiabilityArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DifferentiabilityArgumentsSyntax) -> DifferentiabilityArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DifferentiabilityArgumentsSyntax.self) } /// Visit a ``DifferentiabilityWithRespectToArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DifferentiabilityWithRespectToArgumentSyntax) -> DifferentiabilityWithRespectToArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DifferentiabilityWithRespectToArgumentSyntax.self) } /// Visit a ``DifferentiableAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DifferentiableAttributeArgumentsSyntax) -> DifferentiableAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DifferentiableAttributeArgumentsSyntax.self) } /// Visit a ``DiscardAssignmentExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DiscardAssignmentExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(DiscardAssignmentExprSyntax.self)) } /// Visit a ``DiscardStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DiscardStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(DiscardStmtSyntax.self)) } /// Visit a `DoExprSyntax`. @@ -675,532 +683,532 @@ open class SyntaxRewriter { @_spi(ExperimentalLanguageFeatures) #endif open func visit(_ node: DoExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(DoExprSyntax.self)) } /// Visit a ``DoStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DoStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(DoStmtSyntax.self)) } /// Visit a ``DocumentationAttributeArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DocumentationAttributeArgumentListSyntax) -> DocumentationAttributeArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DocumentationAttributeArgumentListSyntax.self) } /// Visit a ``DocumentationAttributeArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DocumentationAttributeArgumentSyntax) -> DocumentationAttributeArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DocumentationAttributeArgumentSyntax.self) } /// Visit a ``DynamicReplacementAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: DynamicReplacementAttributeArgumentsSyntax) -> DynamicReplacementAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(DynamicReplacementAttributeArgumentsSyntax.self) } /// Visit a ``EditorPlaceholderDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EditorPlaceholderDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(EditorPlaceholderDeclSyntax.self)) } /// Visit a ``EditorPlaceholderExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EditorPlaceholderExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(EditorPlaceholderExprSyntax.self)) } /// Visit a ``EffectsAttributeArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EffectsAttributeArgumentListSyntax) -> EffectsAttributeArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(EffectsAttributeArgumentListSyntax.self) } /// Visit a ``EnumCaseDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumCaseDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(EnumCaseDeclSyntax.self)) } /// Visit a ``EnumCaseElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumCaseElementListSyntax) -> EnumCaseElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(EnumCaseElementListSyntax.self) } /// Visit a ``EnumCaseElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumCaseElementSyntax) -> EnumCaseElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(EnumCaseElementSyntax.self) } /// Visit a ``EnumCaseParameterClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumCaseParameterClauseSyntax) -> EnumCaseParameterClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(EnumCaseParameterClauseSyntax.self) } /// Visit a ``EnumCaseParameterListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumCaseParameterListSyntax) -> EnumCaseParameterListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(EnumCaseParameterListSyntax.self) } /// Visit a ``EnumCaseParameterSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumCaseParameterSyntax) -> EnumCaseParameterSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(EnumCaseParameterSyntax.self) } /// Visit a ``EnumDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: EnumDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(EnumDeclSyntax.self)) } /// Visit a ``ExposeAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ExposeAttributeArgumentsSyntax) -> ExposeAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ExposeAttributeArgumentsSyntax.self) } /// Visit a ``ExprListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ExprListSyntax) -> ExprListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ExprListSyntax.self) } /// Visit a ``ExpressionPatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ExpressionPatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(ExpressionPatternSyntax.self)) } /// Visit a ``ExpressionSegmentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ExpressionSegmentSyntax) -> ExpressionSegmentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ExpressionSegmentSyntax.self) } /// Visit a ``ExpressionStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ExpressionStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(ExpressionStmtSyntax.self)) } /// Visit a ``ExtensionDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ExtensionDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(ExtensionDeclSyntax.self)) } /// Visit a ``FallThroughStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FallThroughStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(FallThroughStmtSyntax.self)) } /// Visit a ``FloatLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FloatLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(FloatLiteralExprSyntax.self)) } /// Visit a ``ForStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ForStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(ForStmtSyntax.self)) } /// Visit a ``ForceUnwrapExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ForceUnwrapExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(ForceUnwrapExprSyntax.self)) } /// Visit a ``FunctionCallExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(FunctionCallExprSyntax.self)) } /// Visit a ``FunctionDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(FunctionDeclSyntax.self)) } /// Visit a ``FunctionEffectSpecifiersSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionEffectSpecifiersSyntax) -> FunctionEffectSpecifiersSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(FunctionEffectSpecifiersSyntax.self) } /// Visit a ``FunctionParameterClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionParameterClauseSyntax) -> FunctionParameterClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(FunctionParameterClauseSyntax.self) } /// Visit a ``FunctionParameterListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionParameterListSyntax) -> FunctionParameterListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(FunctionParameterListSyntax.self) } /// Visit a ``FunctionParameterSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionParameterSyntax) -> FunctionParameterSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(FunctionParameterSyntax.self) } /// Visit a ``FunctionSignatureSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionSignatureSyntax) -> FunctionSignatureSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(FunctionSignatureSyntax.self) } /// Visit a ``FunctionTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: FunctionTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(FunctionTypeSyntax.self)) } /// Visit a ``GenericArgumentClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericArgumentClauseSyntax) -> GenericArgumentClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericArgumentClauseSyntax.self) } /// Visit a ``GenericArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericArgumentListSyntax) -> GenericArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericArgumentListSyntax.self) } /// Visit a ``GenericArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericArgumentSyntax) -> GenericArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericArgumentSyntax.self) } /// Visit a ``GenericParameterClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericParameterClauseSyntax) -> GenericParameterClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericParameterClauseSyntax.self) } /// Visit a ``GenericParameterListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericParameterListSyntax) -> GenericParameterListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericParameterListSyntax.self) } /// Visit a ``GenericParameterSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericParameterSyntax) -> GenericParameterSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericParameterSyntax.self) } /// Visit a ``GenericRequirementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericRequirementListSyntax) -> GenericRequirementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericRequirementListSyntax.self) } /// Visit a ``GenericRequirementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericRequirementSyntax) -> GenericRequirementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericRequirementSyntax.self) } /// Visit a ``GenericSpecializationExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericSpecializationExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(GenericSpecializationExprSyntax.self)) } /// Visit a ``GenericWhereClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GenericWhereClauseSyntax) -> GenericWhereClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(GenericWhereClauseSyntax.self) } /// Visit a ``GuardStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: GuardStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(GuardStmtSyntax.self)) } /// Visit a ``IdentifierPatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IdentifierPatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(IdentifierPatternSyntax.self)) } /// Visit a ``IdentifierTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IdentifierTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(IdentifierTypeSyntax.self)) } /// Visit a ``IfConfigClauseListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IfConfigClauseListSyntax) -> IfConfigClauseListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(IfConfigClauseListSyntax.self) } /// Visit a ``IfConfigClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IfConfigClauseSyntax) -> IfConfigClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(IfConfigClauseSyntax.self) } /// Visit a ``IfConfigDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IfConfigDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(IfConfigDeclSyntax.self)) } /// Visit a ``IfExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IfExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(IfExprSyntax.self)) } /// Visit a ``ImplementsAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ImplementsAttributeArgumentsSyntax) -> ImplementsAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ImplementsAttributeArgumentsSyntax.self) } /// Visit a ``ImplicitlyUnwrappedOptionalTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ImplicitlyUnwrappedOptionalTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(ImplicitlyUnwrappedOptionalTypeSyntax.self)) } /// Visit a ``ImportDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ImportDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(ImportDeclSyntax.self)) } /// Visit a ``ImportPathComponentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ImportPathComponentListSyntax) -> ImportPathComponentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ImportPathComponentListSyntax.self) } /// Visit a ``ImportPathComponentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ImportPathComponentSyntax) -> ImportPathComponentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ImportPathComponentSyntax.self) } /// Visit a ``InOutExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InOutExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(InOutExprSyntax.self)) } /// Visit a ``InfixOperatorExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InfixOperatorExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(InfixOperatorExprSyntax.self)) } /// Visit a ``InheritanceClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InheritanceClauseSyntax) -> InheritanceClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(InheritanceClauseSyntax.self) } /// Visit a ``InheritedTypeListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InheritedTypeListSyntax) -> InheritedTypeListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(InheritedTypeListSyntax.self) } /// Visit a ``InheritedTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InheritedTypeSyntax) -> InheritedTypeSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(InheritedTypeSyntax.self) } /// Visit a ``InitializerClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InitializerClauseSyntax) -> InitializerClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(InitializerClauseSyntax.self) } /// Visit a ``InitializerDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: InitializerDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(InitializerDeclSyntax.self)) } /// Visit a ``IntegerLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IntegerLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(IntegerLiteralExprSyntax.self)) } /// Visit a ``IsExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IsExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(IsExprSyntax.self)) } /// Visit a ``IsTypePatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: IsTypePatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(IsTypePatternSyntax.self)) } /// Visit a ``KeyPathComponentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: KeyPathComponentListSyntax) -> KeyPathComponentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(KeyPathComponentListSyntax.self) } /// Visit a ``KeyPathComponentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: KeyPathComponentSyntax) -> KeyPathComponentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(KeyPathComponentSyntax.self) } /// Visit a ``KeyPathExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: KeyPathExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(KeyPathExprSyntax.self)) } /// Visit a ``KeyPathOptionalComponentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: KeyPathOptionalComponentSyntax) -> KeyPathOptionalComponentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(KeyPathOptionalComponentSyntax.self) } /// Visit a ``KeyPathPropertyComponentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: KeyPathPropertyComponentSyntax) -> KeyPathPropertyComponentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(KeyPathPropertyComponentSyntax.self) } /// Visit a ``KeyPathSubscriptComponentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: KeyPathSubscriptComponentSyntax) -> KeyPathSubscriptComponentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(KeyPathSubscriptComponentSyntax.self) } /// Visit a ``LabeledExprListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: LabeledExprListSyntax) -> LabeledExprListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LabeledExprListSyntax.self) } /// Visit a ``LabeledExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: LabeledExprSyntax) -> LabeledExprSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LabeledExprSyntax.self) } /// Visit a ``LabeledSpecializeArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: LabeledSpecializeArgumentSyntax) -> LabeledSpecializeArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LabeledSpecializeArgumentSyntax.self) } /// Visit a ``LabeledStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: LabeledStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(LabeledStmtSyntax.self)) } /// Visit a ``LayoutRequirementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: LayoutRequirementSyntax) -> LayoutRequirementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LayoutRequirementSyntax.self) } /// Visit a `LifetimeSpecifierArgumentListSyntax`. @@ -1210,7 +1218,7 @@ open class SyntaxRewriter { @_spi(ExperimentalLanguageFeatures) #endif open func visit(_ node: LifetimeSpecifierArgumentListSyntax) -> LifetimeSpecifierArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LifetimeSpecifierArgumentListSyntax.self) } /// Visit a `LifetimeSpecifierArgumentSyntax`. @@ -1220,17 +1228,7 @@ open class SyntaxRewriter { @_spi(ExperimentalLanguageFeatures) #endif open func visit(_ node: LifetimeSpecifierArgumentSyntax) -> LifetimeSpecifierArgumentSyntax { - return visitChildren(node) - } - - /// Visit a `LifetimeSpecifierArgumentsSyntax`. - /// - Parameter node: the node that is being visited - /// - Returns: the rewritten node - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif - open func visit(_ node: LifetimeSpecifierArgumentsSyntax) -> LifetimeSpecifierArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LifetimeSpecifierArgumentSyntax.self) } /// Visit a `LifetimeTypeSpecifierSyntax`. @@ -1240,602 +1238,602 @@ open class SyntaxRewriter { @_spi(ExperimentalLanguageFeatures) #endif open func visit(_ node: LifetimeTypeSpecifierSyntax) -> LifetimeTypeSpecifierSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(LifetimeTypeSpecifierSyntax.self) } /// Visit a ``MacroDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MacroDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(MacroDeclSyntax.self)) } /// Visit a ``MacroExpansionDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MacroExpansionDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(MacroExpansionDeclSyntax.self)) } /// Visit a ``MacroExpansionExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MacroExpansionExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(MacroExpansionExprSyntax.self)) } /// Visit a ``MatchingPatternConditionSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MatchingPatternConditionSyntax) -> MatchingPatternConditionSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(MatchingPatternConditionSyntax.self) } /// Visit a ``MemberAccessExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MemberAccessExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(MemberAccessExprSyntax.self)) } /// Visit a ``MemberBlockItemListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MemberBlockItemListSyntax) -> MemberBlockItemListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(MemberBlockItemListSyntax.self) } /// Visit a ``MemberBlockItemSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MemberBlockItemSyntax) -> MemberBlockItemSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(MemberBlockItemSyntax.self) } /// Visit a ``MemberBlockSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MemberBlockSyntax) -> MemberBlockSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(MemberBlockSyntax.self) } /// Visit a ``MemberTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MemberTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(MemberTypeSyntax.self)) } /// Visit a ``MetatypeTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MetatypeTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(MetatypeTypeSyntax.self)) } /// Visit a ``MissingDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MissingDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(MissingDeclSyntax.self)) } /// Visit a ``MissingExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MissingExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(MissingExprSyntax.self)) } /// Visit a ``MissingPatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MissingPatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(MissingPatternSyntax.self)) } /// Visit a ``MissingStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MissingStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(MissingStmtSyntax.self)) } /// Visit a ``MissingSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MissingSyntax) -> Syntax { - return Syntax(visitChildren(node)) + return Syntax(visitChildren(node._syntaxNode).cast(MissingSyntax.self)) } /// Visit a ``MissingTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MissingTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(MissingTypeSyntax.self)) } /// Visit a ``MultipleTrailingClosureElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MultipleTrailingClosureElementListSyntax) -> MultipleTrailingClosureElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(MultipleTrailingClosureElementListSyntax.self) } /// Visit a ``MultipleTrailingClosureElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: MultipleTrailingClosureElementSyntax) -> MultipleTrailingClosureElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(MultipleTrailingClosureElementSyntax.self) } /// Visit a ``NamedOpaqueReturnTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: NamedOpaqueReturnTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(NamedOpaqueReturnTypeSyntax.self)) } /// Visit a ``NilLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: NilLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(NilLiteralExprSyntax.self)) } /// Visit a ``ObjCSelectorPieceListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ObjCSelectorPieceListSyntax) -> ObjCSelectorPieceListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ObjCSelectorPieceListSyntax.self) } /// Visit a ``ObjCSelectorPieceSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ObjCSelectorPieceSyntax) -> ObjCSelectorPieceSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ObjCSelectorPieceSyntax.self) } /// Visit a ``OpaqueReturnTypeOfAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OpaqueReturnTypeOfAttributeArgumentsSyntax) -> OpaqueReturnTypeOfAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(OpaqueReturnTypeOfAttributeArgumentsSyntax.self) } /// Visit a ``OperatorDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OperatorDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(OperatorDeclSyntax.self)) } /// Visit a ``OperatorPrecedenceAndTypesSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OperatorPrecedenceAndTypesSyntax) -> OperatorPrecedenceAndTypesSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(OperatorPrecedenceAndTypesSyntax.self) } /// Visit a ``OptionalBindingConditionSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OptionalBindingConditionSyntax) -> OptionalBindingConditionSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(OptionalBindingConditionSyntax.self) } /// Visit a ``OptionalChainingExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OptionalChainingExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(OptionalChainingExprSyntax.self)) } /// Visit a ``OptionalTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OptionalTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(OptionalTypeSyntax.self)) } /// Visit a ``OriginallyDefinedInAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: OriginallyDefinedInAttributeArgumentsSyntax) -> OriginallyDefinedInAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(OriginallyDefinedInAttributeArgumentsSyntax.self) } /// Visit a ``PackElementExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PackElementExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(PackElementExprSyntax.self)) } /// Visit a ``PackElementTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PackElementTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(PackElementTypeSyntax.self)) } /// Visit a ``PackExpansionExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PackExpansionExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(PackExpansionExprSyntax.self)) } /// Visit a ``PackExpansionTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PackExpansionTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(PackExpansionTypeSyntax.self)) } /// Visit a ``PatternBindingListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PatternBindingListSyntax) -> PatternBindingListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PatternBindingListSyntax.self) } /// Visit a ``PatternBindingSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PatternBindingSyntax) -> PatternBindingSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PatternBindingSyntax.self) } /// Visit a ``PatternExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PatternExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(PatternExprSyntax.self)) } /// Visit a ``PlatformVersionItemListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PlatformVersionItemListSyntax) -> PlatformVersionItemListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PlatformVersionItemListSyntax.self) } /// Visit a ``PlatformVersionItemSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PlatformVersionItemSyntax) -> PlatformVersionItemSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PlatformVersionItemSyntax.self) } /// Visit a ``PlatformVersionSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PlatformVersionSyntax) -> PlatformVersionSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PlatformVersionSyntax.self) } /// Visit a ``PostfixIfConfigExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PostfixIfConfigExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(PostfixIfConfigExprSyntax.self)) } /// Visit a ``PostfixOperatorExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PostfixOperatorExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(PostfixOperatorExprSyntax.self)) } /// Visit a ``PoundSourceLocationArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PoundSourceLocationArgumentsSyntax) -> PoundSourceLocationArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PoundSourceLocationArgumentsSyntax.self) } /// Visit a ``PoundSourceLocationSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PoundSourceLocationSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(PoundSourceLocationSyntax.self)) } /// Visit a ``PrecedenceGroupAssignmentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupAssignmentSyntax) -> PrecedenceGroupAssignmentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrecedenceGroupAssignmentSyntax.self) } /// Visit a ``PrecedenceGroupAssociativitySyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupAssociativitySyntax) -> PrecedenceGroupAssociativitySyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrecedenceGroupAssociativitySyntax.self) } /// Visit a ``PrecedenceGroupAttributeListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupAttributeListSyntax) -> PrecedenceGroupAttributeListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrecedenceGroupAttributeListSyntax.self) } /// Visit a ``PrecedenceGroupDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(PrecedenceGroupDeclSyntax.self)) } /// Visit a ``PrecedenceGroupNameListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupNameListSyntax) -> PrecedenceGroupNameListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrecedenceGroupNameListSyntax.self) } /// Visit a ``PrecedenceGroupNameSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupNameSyntax) -> PrecedenceGroupNameSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrecedenceGroupNameSyntax.self) } /// Visit a ``PrecedenceGroupRelationSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrecedenceGroupRelationSyntax) -> PrecedenceGroupRelationSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrecedenceGroupRelationSyntax.self) } /// Visit a ``PrefixOperatorExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrefixOperatorExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(PrefixOperatorExprSyntax.self)) } /// Visit a ``PrimaryAssociatedTypeClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrimaryAssociatedTypeClauseSyntax) -> PrimaryAssociatedTypeClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrimaryAssociatedTypeClauseSyntax.self) } /// Visit a ``PrimaryAssociatedTypeListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrimaryAssociatedTypeListSyntax) -> PrimaryAssociatedTypeListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrimaryAssociatedTypeListSyntax.self) } /// Visit a ``PrimaryAssociatedTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: PrimaryAssociatedTypeSyntax) -> PrimaryAssociatedTypeSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(PrimaryAssociatedTypeSyntax.self) } /// Visit a ``ProtocolDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ProtocolDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(ProtocolDeclSyntax.self)) } /// Visit a ``RegexLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: RegexLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(RegexLiteralExprSyntax.self)) } /// Visit a ``RepeatStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: RepeatStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(RepeatStmtSyntax.self)) } /// Visit a ``ReturnClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ReturnClauseSyntax) -> ReturnClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ReturnClauseSyntax.self) } /// Visit a ``ReturnStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ReturnStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(ReturnStmtSyntax.self)) } /// Visit a ``SameTypeRequirementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SameTypeRequirementSyntax) -> SameTypeRequirementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SameTypeRequirementSyntax.self) } /// Visit a ``SequenceExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SequenceExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(SequenceExprSyntax.self)) } /// Visit a ``SimpleStringLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SimpleStringLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(SimpleStringLiteralExprSyntax.self)) } /// Visit a ``SimpleStringLiteralSegmentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SimpleStringLiteralSegmentListSyntax) -> SimpleStringLiteralSegmentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SimpleStringLiteralSegmentListSyntax.self) } /// Visit a ``SimpleTypeSpecifierSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SimpleTypeSpecifierSyntax) -> SimpleTypeSpecifierSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SimpleTypeSpecifierSyntax.self) } /// Visit a ``SomeOrAnyTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SomeOrAnyTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(SomeOrAnyTypeSyntax.self)) } /// Visit a ``SourceFileSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SourceFileSyntax) -> SourceFileSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SourceFileSyntax.self) } /// Visit a ``SpecializeAttributeArgumentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SpecializeAttributeArgumentListSyntax) -> SpecializeAttributeArgumentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SpecializeAttributeArgumentListSyntax.self) } /// Visit a ``SpecializeAvailabilityArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SpecializeAvailabilityArgumentSyntax) -> SpecializeAvailabilityArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SpecializeAvailabilityArgumentSyntax.self) } /// Visit a ``SpecializeTargetFunctionArgumentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SpecializeTargetFunctionArgumentSyntax) -> SpecializeTargetFunctionArgumentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SpecializeTargetFunctionArgumentSyntax.self) } /// Visit a ``StringLiteralExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: StringLiteralExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(StringLiteralExprSyntax.self)) } /// Visit a ``StringLiteralSegmentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: StringLiteralSegmentListSyntax) -> StringLiteralSegmentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(StringLiteralSegmentListSyntax.self) } /// Visit a ``StringSegmentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: StringSegmentSyntax) -> StringSegmentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(StringSegmentSyntax.self) } /// Visit a ``StructDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: StructDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(StructDeclSyntax.self)) } /// Visit a ``SubscriptCallExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SubscriptCallExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(SubscriptCallExprSyntax.self)) } /// Visit a ``SubscriptDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SubscriptDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(SubscriptDeclSyntax.self)) } /// Visit a ``SuperExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SuperExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(SuperExprSyntax.self)) } /// Visit a ``SuppressedTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SuppressedTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(SuppressedTypeSyntax.self)) } /// Visit a ``SwitchCaseItemListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchCaseItemListSyntax) -> SwitchCaseItemListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SwitchCaseItemListSyntax.self) } /// Visit a ``SwitchCaseItemSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchCaseItemSyntax) -> SwitchCaseItemSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SwitchCaseItemSyntax.self) } /// Visit a ``SwitchCaseLabelSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchCaseLabelSyntax) -> SwitchCaseLabelSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SwitchCaseLabelSyntax.self) } /// Visit a ``SwitchCaseListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchCaseListSyntax) -> SwitchCaseListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SwitchCaseListSyntax.self) } /// Visit a ``SwitchCaseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchCaseSyntax) -> SwitchCaseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SwitchCaseSyntax.self) } /// Visit a ``SwitchDefaultLabelSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchDefaultLabelSyntax) -> SwitchDefaultLabelSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(SwitchDefaultLabelSyntax.self) } /// Visit a ``SwitchExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: SwitchExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(SwitchExprSyntax.self)) } /// Visit a ``TernaryExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TernaryExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(TernaryExprSyntax.self)) } /// Visit a `ThenStmtSyntax`. @@ -1845,299 +1843,304 @@ open class SyntaxRewriter { @_spi(ExperimentalLanguageFeatures) #endif open func visit(_ node: ThenStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(ThenStmtSyntax.self)) } /// Visit a ``ThrowStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ThrowStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(ThrowStmtSyntax.self)) } /// Visit a ``ThrowsClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ThrowsClauseSyntax) -> ThrowsClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(ThrowsClauseSyntax.self) } /// Visit a ``TryExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TryExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(TryExprSyntax.self)) } /// Visit a ``TupleExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TupleExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(TupleExprSyntax.self)) } /// Visit a ``TuplePatternElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TuplePatternElementListSyntax) -> TuplePatternElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TuplePatternElementListSyntax.self) } /// Visit a ``TuplePatternElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TuplePatternElementSyntax) -> TuplePatternElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TuplePatternElementSyntax.self) } /// Visit a ``TuplePatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TuplePatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(TuplePatternSyntax.self)) } /// Visit a ``TupleTypeElementListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TupleTypeElementListSyntax) -> TupleTypeElementListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TupleTypeElementListSyntax.self) } /// Visit a ``TupleTypeElementSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TupleTypeElementSyntax) -> TupleTypeElementSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TupleTypeElementSyntax.self) } /// Visit a ``TupleTypeSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TupleTypeSyntax) -> TypeSyntax { - return TypeSyntax(visitChildren(node)) + return TypeSyntax(visitChildren(node._syntaxNode).cast(TupleTypeSyntax.self)) } /// Visit a ``TypeAliasDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TypeAliasDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(TypeAliasDeclSyntax.self)) } /// Visit a ``TypeAnnotationSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TypeAnnotationSyntax) -> TypeAnnotationSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TypeAnnotationSyntax.self) } /// Visit a ``TypeEffectSpecifiersSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TypeEffectSpecifiersSyntax) -> TypeEffectSpecifiersSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TypeEffectSpecifiersSyntax.self) } /// Visit a ``TypeExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TypeExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(TypeExprSyntax.self)) } /// Visit a ``TypeInitializerClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TypeInitializerClauseSyntax) -> TypeInitializerClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TypeInitializerClauseSyntax.self) } /// Visit a ``TypeSpecifierListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: TypeSpecifierListSyntax) -> TypeSpecifierListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(TypeSpecifierListSyntax.self) } /// Visit a ``UnavailableFromAsyncAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: UnavailableFromAsyncAttributeArgumentsSyntax) -> UnavailableFromAsyncAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(UnavailableFromAsyncAttributeArgumentsSyntax.self) } /// Visit a ``UnderscorePrivateAttributeArgumentsSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: UnderscorePrivateAttributeArgumentsSyntax) -> UnderscorePrivateAttributeArgumentsSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(UnderscorePrivateAttributeArgumentsSyntax.self) } /// Visit a ``UnexpectedNodesSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: UnexpectedNodesSyntax) -> UnexpectedNodesSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(UnexpectedNodesSyntax.self) } /// Visit a ``UnresolvedAsExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: UnresolvedAsExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(UnresolvedAsExprSyntax.self)) } /// Visit a ``UnresolvedIsExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: UnresolvedIsExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(UnresolvedIsExprSyntax.self)) } /// Visit a ``UnresolvedTernaryExprSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: UnresolvedTernaryExprSyntax) -> ExprSyntax { - return ExprSyntax(visitChildren(node)) + return ExprSyntax(visitChildren(node._syntaxNode).cast(UnresolvedTernaryExprSyntax.self)) } /// Visit a ``ValueBindingPatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: ValueBindingPatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(ValueBindingPatternSyntax.self)) } /// Visit a ``VariableDeclSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: VariableDeclSyntax) -> DeclSyntax { - return DeclSyntax(visitChildren(node)) + return DeclSyntax(visitChildren(node._syntaxNode).cast(VariableDeclSyntax.self)) } /// Visit a ``VersionComponentListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: VersionComponentListSyntax) -> VersionComponentListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(VersionComponentListSyntax.self) } /// Visit a ``VersionComponentSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: VersionComponentSyntax) -> VersionComponentSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(VersionComponentSyntax.self) } /// Visit a ``VersionTupleSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: VersionTupleSyntax) -> VersionTupleSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(VersionTupleSyntax.self) } /// Visit a ``WhereClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: WhereClauseSyntax) -> WhereClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(WhereClauseSyntax.self) } /// Visit a ``WhileStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: WhileStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(WhileStmtSyntax.self)) } /// Visit a ``WildcardPatternSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: WildcardPatternSyntax) -> PatternSyntax { - return PatternSyntax(visitChildren(node)) + return PatternSyntax(visitChildren(node._syntaxNode).cast(WildcardPatternSyntax.self)) } /// Visit a ``YieldStmtSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: YieldStmtSyntax) -> StmtSyntax { - return StmtSyntax(visitChildren(node)) + return StmtSyntax(visitChildren(node._syntaxNode).cast(YieldStmtSyntax.self)) } /// Visit a ``YieldedExpressionListSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: YieldedExpressionListSyntax) -> YieldedExpressionListSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(YieldedExpressionListSyntax.self) } /// Visit a ``YieldedExpressionSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: YieldedExpressionSyntax) -> YieldedExpressionSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(YieldedExpressionSyntax.self) } /// Visit a ``YieldedExpressionsClauseSyntax``. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node open func visit(_ node: YieldedExpressionsClauseSyntax) -> YieldedExpressionsClauseSyntax { - return visitChildren(node) + return visitChildren(node._syntaxNode).cast(YieldedExpressionsClauseSyntax.self) } /// Visit any DeclSyntax node. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node public func visit(_ node: DeclSyntax) -> DeclSyntax { - return dispatchVisit(Syntax(node)).cast(DeclSyntax.self) + var node: Syntax = Syntax(node) + dispatchVisit(&node) + return node.cast(DeclSyntax.self) } /// Visit any ExprSyntax node. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node public func visit(_ node: ExprSyntax) -> ExprSyntax { - return dispatchVisit(Syntax(node)).cast(ExprSyntax.self) + var node: Syntax = Syntax(node) + dispatchVisit(&node) + return node.cast(ExprSyntax.self) } /// Visit any PatternSyntax node. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node public func visit(_ node: PatternSyntax) -> PatternSyntax { - return dispatchVisit(Syntax(node)).cast(PatternSyntax.self) + var node: Syntax = Syntax(node) + dispatchVisit(&node) + return node.cast(PatternSyntax.self) } /// Visit any StmtSyntax node. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node public func visit(_ node: StmtSyntax) -> StmtSyntax { - return dispatchVisit(Syntax(node)).cast(StmtSyntax.self) + var node: Syntax = Syntax(node) + dispatchVisit(&node) + return node.cast(StmtSyntax.self) } /// Visit any TypeSyntax node. /// - Parameter node: the node that is being visited /// - Returns: the rewritten node public func visit(_ node: TypeSyntax) -> TypeSyntax { - return dispatchVisit(Syntax(node)).cast(TypeSyntax.self) + var node: Syntax = Syntax(node) + dispatchVisit(&node) + return node.cast(TypeSyntax.self) } /// Interpret `node` as a node of type `nodeType`, visit it, calling /// the `visit` to transform the node. + @inline(__always) private func visitImpl( - _ node: Syntax, + _ node: inout Syntax, _ nodeType: NodeType.Type, _ visit: (NodeType) -> some SyntaxProtocol - ) -> Syntax { - let castedNode = node.cast(NodeType.self) - // Accessing _syntaxNode directly is faster than calling Syntax(node) - visitPre(node) - defer { - visitPost(node) - } - if let newNode = visitAny(node) { - return newNode - } - return Syntax(visit(castedNode)) + ) { + let origNode = node + visitPre(origNode) + node = visitAny(origNode) ?? Syntax(visit(origNode.cast(NodeType.self))) + visitPost(origNode) } // SwiftSyntax requires a lot of stack space in debug builds for syntax tree @@ -2164,1733 +2167,1725 @@ open class SyntaxRewriter { /// that determines the correct visitation function will be popped of the /// stack before the function is being called, making the switch's stack /// space transient instead of having it linger in the call stack. - private func visitationFunc(for node: Syntax) -> ((Syntax) -> Syntax) { + private func visitationFunc(for node: Syntax) -> ((inout Syntax) -> Void) { switch node.raw.kind { case .token: return { - self.visitImpl($0, TokenSyntax.self, self.visit) + self.visitImpl(&$0, TokenSyntax.self, self.visit) } case .accessorBlock: return { - self.visitImpl($0, AccessorBlockSyntax.self, self.visit) + self.visitImpl(&$0, AccessorBlockSyntax.self, self.visit) } case .accessorDeclList: return { - self.visitImpl($0, AccessorDeclListSyntax.self, self.visit) + self.visitImpl(&$0, AccessorDeclListSyntax.self, self.visit) } case .accessorDecl: return { - self.visitImpl($0, AccessorDeclSyntax.self, self.visit) + self.visitImpl(&$0, AccessorDeclSyntax.self, self.visit) } case .accessorEffectSpecifiers: return { - self.visitImpl($0, AccessorEffectSpecifiersSyntax.self, self.visit) + self.visitImpl(&$0, AccessorEffectSpecifiersSyntax.self, self.visit) } case .accessorParameters: return { - self.visitImpl($0, AccessorParametersSyntax.self, self.visit) + self.visitImpl(&$0, AccessorParametersSyntax.self, self.visit) } case .actorDecl: return { - self.visitImpl($0, ActorDeclSyntax.self, self.visit) + self.visitImpl(&$0, ActorDeclSyntax.self, self.visit) } case .arrayElementList: return { - self.visitImpl($0, ArrayElementListSyntax.self, self.visit) + self.visitImpl(&$0, ArrayElementListSyntax.self, self.visit) } case .arrayElement: return { - self.visitImpl($0, ArrayElementSyntax.self, self.visit) + self.visitImpl(&$0, ArrayElementSyntax.self, self.visit) } case .arrayExpr: return { - self.visitImpl($0, ArrayExprSyntax.self, self.visit) + self.visitImpl(&$0, ArrayExprSyntax.self, self.visit) } case .arrayType: return { - self.visitImpl($0, ArrayTypeSyntax.self, self.visit) + self.visitImpl(&$0, ArrayTypeSyntax.self, self.visit) } case .arrowExpr: return { - self.visitImpl($0, ArrowExprSyntax.self, self.visit) + self.visitImpl(&$0, ArrowExprSyntax.self, self.visit) } case .asExpr: return { - self.visitImpl($0, AsExprSyntax.self, self.visit) + self.visitImpl(&$0, AsExprSyntax.self, self.visit) } case .assignmentExpr: return { - self.visitImpl($0, AssignmentExprSyntax.self, self.visit) + self.visitImpl(&$0, AssignmentExprSyntax.self, self.visit) } case .associatedTypeDecl: return { - self.visitImpl($0, AssociatedTypeDeclSyntax.self, self.visit) + self.visitImpl(&$0, AssociatedTypeDeclSyntax.self, self.visit) } case .attributeList: return { - self.visitImpl($0, AttributeListSyntax.self, self.visit) + self.visitImpl(&$0, AttributeListSyntax.self, self.visit) } case .attribute: return { - self.visitImpl($0, AttributeSyntax.self, self.visit) + self.visitImpl(&$0, AttributeSyntax.self, self.visit) } case .attributedType: return { - self.visitImpl($0, AttributedTypeSyntax.self, self.visit) + self.visitImpl(&$0, AttributedTypeSyntax.self, self.visit) } case .availabilityArgumentList: return { - self.visitImpl($0, AvailabilityArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, AvailabilityArgumentListSyntax.self, self.visit) } case .availabilityArgument: return { - self.visitImpl($0, AvailabilityArgumentSyntax.self, self.visit) + self.visitImpl(&$0, AvailabilityArgumentSyntax.self, self.visit) } case .availabilityCondition: return { - self.visitImpl($0, AvailabilityConditionSyntax.self, self.visit) + self.visitImpl(&$0, AvailabilityConditionSyntax.self, self.visit) } case .availabilityLabeledArgument: return { - self.visitImpl($0, AvailabilityLabeledArgumentSyntax.self, self.visit) + self.visitImpl(&$0, AvailabilityLabeledArgumentSyntax.self, self.visit) } case .awaitExpr: return { - self.visitImpl($0, AwaitExprSyntax.self, self.visit) + self.visitImpl(&$0, AwaitExprSyntax.self, self.visit) } case .backDeployedAttributeArguments: return { - self.visitImpl($0, BackDeployedAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, BackDeployedAttributeArgumentsSyntax.self, self.visit) } case .binaryOperatorExpr: return { - self.visitImpl($0, BinaryOperatorExprSyntax.self, self.visit) + self.visitImpl(&$0, BinaryOperatorExprSyntax.self, self.visit) } case .booleanLiteralExpr: return { - self.visitImpl($0, BooleanLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, BooleanLiteralExprSyntax.self, self.visit) } case .borrowExpr: return { - self.visitImpl($0, BorrowExprSyntax.self, self.visit) + self.visitImpl(&$0, BorrowExprSyntax.self, self.visit) } case .breakStmt: return { - self.visitImpl($0, BreakStmtSyntax.self, self.visit) + self.visitImpl(&$0, BreakStmtSyntax.self, self.visit) } - case .canImportExpr: + case ._canImportExpr: return { - self.visitImpl($0, CanImportExprSyntax.self, self.visit) + self.visitImpl(&$0, _CanImportExprSyntax.self, self.visit) } - case .canImportVersionInfo: + case ._canImportVersionInfo: return { - self.visitImpl($0, CanImportVersionInfoSyntax.self, self.visit) + self.visitImpl(&$0, _CanImportVersionInfoSyntax.self, self.visit) } case .catchClauseList: return { - self.visitImpl($0, CatchClauseListSyntax.self, self.visit) + self.visitImpl(&$0, CatchClauseListSyntax.self, self.visit) } case .catchClause: return { - self.visitImpl($0, CatchClauseSyntax.self, self.visit) + self.visitImpl(&$0, CatchClauseSyntax.self, self.visit) } case .catchItemList: return { - self.visitImpl($0, CatchItemListSyntax.self, self.visit) + self.visitImpl(&$0, CatchItemListSyntax.self, self.visit) } case .catchItem: return { - self.visitImpl($0, CatchItemSyntax.self, self.visit) + self.visitImpl(&$0, CatchItemSyntax.self, self.visit) } case .classDecl: return { - self.visitImpl($0, ClassDeclSyntax.self, self.visit) + self.visitImpl(&$0, ClassDeclSyntax.self, self.visit) } case .classRestrictionType: return { - self.visitImpl($0, ClassRestrictionTypeSyntax.self, self.visit) + self.visitImpl(&$0, ClassRestrictionTypeSyntax.self, self.visit) } case .closureCaptureClause: return { - self.visitImpl($0, ClosureCaptureClauseSyntax.self, self.visit) + self.visitImpl(&$0, ClosureCaptureClauseSyntax.self, self.visit) } case .closureCaptureList: return { - self.visitImpl($0, ClosureCaptureListSyntax.self, self.visit) + self.visitImpl(&$0, ClosureCaptureListSyntax.self, self.visit) } case .closureCaptureSpecifier: return { - self.visitImpl($0, ClosureCaptureSpecifierSyntax.self, self.visit) + self.visitImpl(&$0, ClosureCaptureSpecifierSyntax.self, self.visit) } case .closureCapture: return { - self.visitImpl($0, ClosureCaptureSyntax.self, self.visit) + self.visitImpl(&$0, ClosureCaptureSyntax.self, self.visit) } case .closureExpr: return { - self.visitImpl($0, ClosureExprSyntax.self, self.visit) + self.visitImpl(&$0, ClosureExprSyntax.self, self.visit) } case .closureParameterClause: return { - self.visitImpl($0, ClosureParameterClauseSyntax.self, self.visit) + self.visitImpl(&$0, ClosureParameterClauseSyntax.self, self.visit) } case .closureParameterList: return { - self.visitImpl($0, ClosureParameterListSyntax.self, self.visit) + self.visitImpl(&$0, ClosureParameterListSyntax.self, self.visit) } case .closureParameter: return { - self.visitImpl($0, ClosureParameterSyntax.self, self.visit) + self.visitImpl(&$0, ClosureParameterSyntax.self, self.visit) } case .closureShorthandParameterList: return { - self.visitImpl($0, ClosureShorthandParameterListSyntax.self, self.visit) + self.visitImpl(&$0, ClosureShorthandParameterListSyntax.self, self.visit) } case .closureShorthandParameter: return { - self.visitImpl($0, ClosureShorthandParameterSyntax.self, self.visit) + self.visitImpl(&$0, ClosureShorthandParameterSyntax.self, self.visit) } case .closureSignature: return { - self.visitImpl($0, ClosureSignatureSyntax.self, self.visit) + self.visitImpl(&$0, ClosureSignatureSyntax.self, self.visit) } case .codeBlockItemList: return { - self.visitImpl($0, CodeBlockItemListSyntax.self, self.visit) + self.visitImpl(&$0, CodeBlockItemListSyntax.self, self.visit) } case .codeBlockItem: return { - self.visitImpl($0, CodeBlockItemSyntax.self, self.visit) + self.visitImpl(&$0, CodeBlockItemSyntax.self, self.visit) } case .codeBlock: return { - self.visitImpl($0, CodeBlockSyntax.self, self.visit) + self.visitImpl(&$0, CodeBlockSyntax.self, self.visit) } case .compositionTypeElementList: return { - self.visitImpl($0, CompositionTypeElementListSyntax.self, self.visit) + self.visitImpl(&$0, CompositionTypeElementListSyntax.self, self.visit) } case .compositionTypeElement: return { - self.visitImpl($0, CompositionTypeElementSyntax.self, self.visit) + self.visitImpl(&$0, CompositionTypeElementSyntax.self, self.visit) } case .compositionType: return { - self.visitImpl($0, CompositionTypeSyntax.self, self.visit) + self.visitImpl(&$0, CompositionTypeSyntax.self, self.visit) } case .conditionElementList: return { - self.visitImpl($0, ConditionElementListSyntax.self, self.visit) + self.visitImpl(&$0, ConditionElementListSyntax.self, self.visit) } case .conditionElement: return { - self.visitImpl($0, ConditionElementSyntax.self, self.visit) + self.visitImpl(&$0, ConditionElementSyntax.self, self.visit) } case .conformanceRequirement: return { - self.visitImpl($0, ConformanceRequirementSyntax.self, self.visit) + self.visitImpl(&$0, ConformanceRequirementSyntax.self, self.visit) } case .consumeExpr: return { - self.visitImpl($0, ConsumeExprSyntax.self, self.visit) + self.visitImpl(&$0, ConsumeExprSyntax.self, self.visit) } case .continueStmt: return { - self.visitImpl($0, ContinueStmtSyntax.self, self.visit) + self.visitImpl(&$0, ContinueStmtSyntax.self, self.visit) } case .conventionAttributeArguments: return { - self.visitImpl($0, ConventionAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, ConventionAttributeArgumentsSyntax.self, self.visit) } case .conventionWitnessMethodAttributeArguments: return { - self.visitImpl($0, ConventionWitnessMethodAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, ConventionWitnessMethodAttributeArgumentsSyntax.self, self.visit) } case .copyExpr: return { - self.visitImpl($0, CopyExprSyntax.self, self.visit) + self.visitImpl(&$0, CopyExprSyntax.self, self.visit) } case .declModifierDetail: return { - self.visitImpl($0, DeclModifierDetailSyntax.self, self.visit) + self.visitImpl(&$0, DeclModifierDetailSyntax.self, self.visit) } case .declModifierList: return { - self.visitImpl($0, DeclModifierListSyntax.self, self.visit) + self.visitImpl(&$0, DeclModifierListSyntax.self, self.visit) } case .declModifier: return { - self.visitImpl($0, DeclModifierSyntax.self, self.visit) + self.visitImpl(&$0, DeclModifierSyntax.self, self.visit) } case .declNameArgumentList: return { - self.visitImpl($0, DeclNameArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, DeclNameArgumentListSyntax.self, self.visit) } case .declNameArgument: return { - self.visitImpl($0, DeclNameArgumentSyntax.self, self.visit) + self.visitImpl(&$0, DeclNameArgumentSyntax.self, self.visit) } case .declNameArguments: return { - self.visitImpl($0, DeclNameArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, DeclNameArgumentsSyntax.self, self.visit) } case .declReferenceExpr: return { - self.visitImpl($0, DeclReferenceExprSyntax.self, self.visit) + self.visitImpl(&$0, DeclReferenceExprSyntax.self, self.visit) } case .deferStmt: return { - self.visitImpl($0, DeferStmtSyntax.self, self.visit) + self.visitImpl(&$0, DeferStmtSyntax.self, self.visit) } case .deinitializerDecl: return { - self.visitImpl($0, DeinitializerDeclSyntax.self, self.visit) + self.visitImpl(&$0, DeinitializerDeclSyntax.self, self.visit) } case .deinitializerEffectSpecifiers: return { - self.visitImpl($0, DeinitializerEffectSpecifiersSyntax.self, self.visit) + self.visitImpl(&$0, DeinitializerEffectSpecifiersSyntax.self, self.visit) } case .derivativeAttributeArguments: return { - self.visitImpl($0, DerivativeAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, DerivativeAttributeArgumentsSyntax.self, self.visit) } case .designatedTypeList: return { - self.visitImpl($0, DesignatedTypeListSyntax.self, self.visit) + self.visitImpl(&$0, DesignatedTypeListSyntax.self, self.visit) } case .designatedType: return { - self.visitImpl($0, DesignatedTypeSyntax.self, self.visit) + self.visitImpl(&$0, DesignatedTypeSyntax.self, self.visit) } case .dictionaryElementList: return { - self.visitImpl($0, DictionaryElementListSyntax.self, self.visit) + self.visitImpl(&$0, DictionaryElementListSyntax.self, self.visit) } case .dictionaryElement: return { - self.visitImpl($0, DictionaryElementSyntax.self, self.visit) + self.visitImpl(&$0, DictionaryElementSyntax.self, self.visit) } case .dictionaryExpr: return { - self.visitImpl($0, DictionaryExprSyntax.self, self.visit) + self.visitImpl(&$0, DictionaryExprSyntax.self, self.visit) } case .dictionaryType: return { - self.visitImpl($0, DictionaryTypeSyntax.self, self.visit) + self.visitImpl(&$0, DictionaryTypeSyntax.self, self.visit) } case .differentiabilityArgumentList: return { - self.visitImpl($0, DifferentiabilityArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, DifferentiabilityArgumentListSyntax.self, self.visit) } case .differentiabilityArgument: return { - self.visitImpl($0, DifferentiabilityArgumentSyntax.self, self.visit) + self.visitImpl(&$0, DifferentiabilityArgumentSyntax.self, self.visit) } case .differentiabilityArguments: return { - self.visitImpl($0, DifferentiabilityArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, DifferentiabilityArgumentsSyntax.self, self.visit) } case .differentiabilityWithRespectToArgument: return { - self.visitImpl($0, DifferentiabilityWithRespectToArgumentSyntax.self, self.visit) + self.visitImpl(&$0, DifferentiabilityWithRespectToArgumentSyntax.self, self.visit) } case .differentiableAttributeArguments: return { - self.visitImpl($0, DifferentiableAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, DifferentiableAttributeArgumentsSyntax.self, self.visit) } case .discardAssignmentExpr: return { - self.visitImpl($0, DiscardAssignmentExprSyntax.self, self.visit) + self.visitImpl(&$0, DiscardAssignmentExprSyntax.self, self.visit) } case .discardStmt: return { - self.visitImpl($0, DiscardStmtSyntax.self, self.visit) + self.visitImpl(&$0, DiscardStmtSyntax.self, self.visit) } case .doExpr: return { - self.visitImpl($0, DoExprSyntax.self, self.visit) + self.visitImpl(&$0, DoExprSyntax.self, self.visit) } case .doStmt: return { - self.visitImpl($0, DoStmtSyntax.self, self.visit) + self.visitImpl(&$0, DoStmtSyntax.self, self.visit) } case .documentationAttributeArgumentList: return { - self.visitImpl($0, DocumentationAttributeArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, DocumentationAttributeArgumentListSyntax.self, self.visit) } case .documentationAttributeArgument: return { - self.visitImpl($0, DocumentationAttributeArgumentSyntax.self, self.visit) + self.visitImpl(&$0, DocumentationAttributeArgumentSyntax.self, self.visit) } case .dynamicReplacementAttributeArguments: return { - self.visitImpl($0, DynamicReplacementAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, DynamicReplacementAttributeArgumentsSyntax.self, self.visit) } case .editorPlaceholderDecl: return { - self.visitImpl($0, EditorPlaceholderDeclSyntax.self, self.visit) + self.visitImpl(&$0, EditorPlaceholderDeclSyntax.self, self.visit) } case .editorPlaceholderExpr: return { - self.visitImpl($0, EditorPlaceholderExprSyntax.self, self.visit) + self.visitImpl(&$0, EditorPlaceholderExprSyntax.self, self.visit) } case .effectsAttributeArgumentList: return { - self.visitImpl($0, EffectsAttributeArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, EffectsAttributeArgumentListSyntax.self, self.visit) } case .enumCaseDecl: return { - self.visitImpl($0, EnumCaseDeclSyntax.self, self.visit) + self.visitImpl(&$0, EnumCaseDeclSyntax.self, self.visit) } case .enumCaseElementList: return { - self.visitImpl($0, EnumCaseElementListSyntax.self, self.visit) + self.visitImpl(&$0, EnumCaseElementListSyntax.self, self.visit) } case .enumCaseElement: return { - self.visitImpl($0, EnumCaseElementSyntax.self, self.visit) + self.visitImpl(&$0, EnumCaseElementSyntax.self, self.visit) } case .enumCaseParameterClause: return { - self.visitImpl($0, EnumCaseParameterClauseSyntax.self, self.visit) + self.visitImpl(&$0, EnumCaseParameterClauseSyntax.self, self.visit) } case .enumCaseParameterList: return { - self.visitImpl($0, EnumCaseParameterListSyntax.self, self.visit) + self.visitImpl(&$0, EnumCaseParameterListSyntax.self, self.visit) } case .enumCaseParameter: return { - self.visitImpl($0, EnumCaseParameterSyntax.self, self.visit) + self.visitImpl(&$0, EnumCaseParameterSyntax.self, self.visit) } case .enumDecl: return { - self.visitImpl($0, EnumDeclSyntax.self, self.visit) + self.visitImpl(&$0, EnumDeclSyntax.self, self.visit) } case .exposeAttributeArguments: return { - self.visitImpl($0, ExposeAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, ExposeAttributeArgumentsSyntax.self, self.visit) } case .exprList: return { - self.visitImpl($0, ExprListSyntax.self, self.visit) + self.visitImpl(&$0, ExprListSyntax.self, self.visit) } case .expressionPattern: return { - self.visitImpl($0, ExpressionPatternSyntax.self, self.visit) + self.visitImpl(&$0, ExpressionPatternSyntax.self, self.visit) } case .expressionSegment: return { - self.visitImpl($0, ExpressionSegmentSyntax.self, self.visit) + self.visitImpl(&$0, ExpressionSegmentSyntax.self, self.visit) } case .expressionStmt: return { - self.visitImpl($0, ExpressionStmtSyntax.self, self.visit) + self.visitImpl(&$0, ExpressionStmtSyntax.self, self.visit) } case .extensionDecl: return { - self.visitImpl($0, ExtensionDeclSyntax.self, self.visit) + self.visitImpl(&$0, ExtensionDeclSyntax.self, self.visit) } case .fallThroughStmt: return { - self.visitImpl($0, FallThroughStmtSyntax.self, self.visit) + self.visitImpl(&$0, FallThroughStmtSyntax.self, self.visit) } case .floatLiteralExpr: return { - self.visitImpl($0, FloatLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, FloatLiteralExprSyntax.self, self.visit) } case .forStmt: return { - self.visitImpl($0, ForStmtSyntax.self, self.visit) + self.visitImpl(&$0, ForStmtSyntax.self, self.visit) } case .forceUnwrapExpr: return { - self.visitImpl($0, ForceUnwrapExprSyntax.self, self.visit) + self.visitImpl(&$0, ForceUnwrapExprSyntax.self, self.visit) } case .functionCallExpr: return { - self.visitImpl($0, FunctionCallExprSyntax.self, self.visit) + self.visitImpl(&$0, FunctionCallExprSyntax.self, self.visit) } case .functionDecl: return { - self.visitImpl($0, FunctionDeclSyntax.self, self.visit) + self.visitImpl(&$0, FunctionDeclSyntax.self, self.visit) } case .functionEffectSpecifiers: return { - self.visitImpl($0, FunctionEffectSpecifiersSyntax.self, self.visit) + self.visitImpl(&$0, FunctionEffectSpecifiersSyntax.self, self.visit) } case .functionParameterClause: return { - self.visitImpl($0, FunctionParameterClauseSyntax.self, self.visit) + self.visitImpl(&$0, FunctionParameterClauseSyntax.self, self.visit) } case .functionParameterList: return { - self.visitImpl($0, FunctionParameterListSyntax.self, self.visit) + self.visitImpl(&$0, FunctionParameterListSyntax.self, self.visit) } case .functionParameter: return { - self.visitImpl($0, FunctionParameterSyntax.self, self.visit) + self.visitImpl(&$0, FunctionParameterSyntax.self, self.visit) } case .functionSignature: return { - self.visitImpl($0, FunctionSignatureSyntax.self, self.visit) + self.visitImpl(&$0, FunctionSignatureSyntax.self, self.visit) } case .functionType: return { - self.visitImpl($0, FunctionTypeSyntax.self, self.visit) + self.visitImpl(&$0, FunctionTypeSyntax.self, self.visit) } case .genericArgumentClause: return { - self.visitImpl($0, GenericArgumentClauseSyntax.self, self.visit) + self.visitImpl(&$0, GenericArgumentClauseSyntax.self, self.visit) } case .genericArgumentList: return { - self.visitImpl($0, GenericArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, GenericArgumentListSyntax.self, self.visit) } case .genericArgument: return { - self.visitImpl($0, GenericArgumentSyntax.self, self.visit) + self.visitImpl(&$0, GenericArgumentSyntax.self, self.visit) } case .genericParameterClause: return { - self.visitImpl($0, GenericParameterClauseSyntax.self, self.visit) + self.visitImpl(&$0, GenericParameterClauseSyntax.self, self.visit) } case .genericParameterList: return { - self.visitImpl($0, GenericParameterListSyntax.self, self.visit) + self.visitImpl(&$0, GenericParameterListSyntax.self, self.visit) } case .genericParameter: return { - self.visitImpl($0, GenericParameterSyntax.self, self.visit) + self.visitImpl(&$0, GenericParameterSyntax.self, self.visit) } case .genericRequirementList: return { - self.visitImpl($0, GenericRequirementListSyntax.self, self.visit) + self.visitImpl(&$0, GenericRequirementListSyntax.self, self.visit) } case .genericRequirement: return { - self.visitImpl($0, GenericRequirementSyntax.self, self.visit) + self.visitImpl(&$0, GenericRequirementSyntax.self, self.visit) } case .genericSpecializationExpr: return { - self.visitImpl($0, GenericSpecializationExprSyntax.self, self.visit) + self.visitImpl(&$0, GenericSpecializationExprSyntax.self, self.visit) } case .genericWhereClause: return { - self.visitImpl($0, GenericWhereClauseSyntax.self, self.visit) + self.visitImpl(&$0, GenericWhereClauseSyntax.self, self.visit) } case .guardStmt: return { - self.visitImpl($0, GuardStmtSyntax.self, self.visit) + self.visitImpl(&$0, GuardStmtSyntax.self, self.visit) } case .identifierPattern: return { - self.visitImpl($0, IdentifierPatternSyntax.self, self.visit) + self.visitImpl(&$0, IdentifierPatternSyntax.self, self.visit) } case .identifierType: return { - self.visitImpl($0, IdentifierTypeSyntax.self, self.visit) + self.visitImpl(&$0, IdentifierTypeSyntax.self, self.visit) } case .ifConfigClauseList: return { - self.visitImpl($0, IfConfigClauseListSyntax.self, self.visit) + self.visitImpl(&$0, IfConfigClauseListSyntax.self, self.visit) } case .ifConfigClause: return { - self.visitImpl($0, IfConfigClauseSyntax.self, self.visit) + self.visitImpl(&$0, IfConfigClauseSyntax.self, self.visit) } case .ifConfigDecl: return { - self.visitImpl($0, IfConfigDeclSyntax.self, self.visit) + self.visitImpl(&$0, IfConfigDeclSyntax.self, self.visit) } case .ifExpr: return { - self.visitImpl($0, IfExprSyntax.self, self.visit) + self.visitImpl(&$0, IfExprSyntax.self, self.visit) } case .implementsAttributeArguments: return { - self.visitImpl($0, ImplementsAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, ImplementsAttributeArgumentsSyntax.self, self.visit) } case .implicitlyUnwrappedOptionalType: return { - self.visitImpl($0, ImplicitlyUnwrappedOptionalTypeSyntax.self, self.visit) + self.visitImpl(&$0, ImplicitlyUnwrappedOptionalTypeSyntax.self, self.visit) } case .importDecl: return { - self.visitImpl($0, ImportDeclSyntax.self, self.visit) + self.visitImpl(&$0, ImportDeclSyntax.self, self.visit) } case .importPathComponentList: return { - self.visitImpl($0, ImportPathComponentListSyntax.self, self.visit) + self.visitImpl(&$0, ImportPathComponentListSyntax.self, self.visit) } case .importPathComponent: return { - self.visitImpl($0, ImportPathComponentSyntax.self, self.visit) + self.visitImpl(&$0, ImportPathComponentSyntax.self, self.visit) } case .inOutExpr: return { - self.visitImpl($0, InOutExprSyntax.self, self.visit) + self.visitImpl(&$0, InOutExprSyntax.self, self.visit) } case .infixOperatorExpr: return { - self.visitImpl($0, InfixOperatorExprSyntax.self, self.visit) + self.visitImpl(&$0, InfixOperatorExprSyntax.self, self.visit) } case .inheritanceClause: return { - self.visitImpl($0, InheritanceClauseSyntax.self, self.visit) + self.visitImpl(&$0, InheritanceClauseSyntax.self, self.visit) } case .inheritedTypeList: return { - self.visitImpl($0, InheritedTypeListSyntax.self, self.visit) + self.visitImpl(&$0, InheritedTypeListSyntax.self, self.visit) } case .inheritedType: return { - self.visitImpl($0, InheritedTypeSyntax.self, self.visit) + self.visitImpl(&$0, InheritedTypeSyntax.self, self.visit) } case .initializerClause: return { - self.visitImpl($0, InitializerClauseSyntax.self, self.visit) + self.visitImpl(&$0, InitializerClauseSyntax.self, self.visit) } case .initializerDecl: return { - self.visitImpl($0, InitializerDeclSyntax.self, self.visit) + self.visitImpl(&$0, InitializerDeclSyntax.self, self.visit) } case .integerLiteralExpr: return { - self.visitImpl($0, IntegerLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, IntegerLiteralExprSyntax.self, self.visit) } case .isExpr: return { - self.visitImpl($0, IsExprSyntax.self, self.visit) + self.visitImpl(&$0, IsExprSyntax.self, self.visit) } case .isTypePattern: return { - self.visitImpl($0, IsTypePatternSyntax.self, self.visit) + self.visitImpl(&$0, IsTypePatternSyntax.self, self.visit) } case .keyPathComponentList: return { - self.visitImpl($0, KeyPathComponentListSyntax.self, self.visit) + self.visitImpl(&$0, KeyPathComponentListSyntax.self, self.visit) } case .keyPathComponent: return { - self.visitImpl($0, KeyPathComponentSyntax.self, self.visit) + self.visitImpl(&$0, KeyPathComponentSyntax.self, self.visit) } case .keyPathExpr: return { - self.visitImpl($0, KeyPathExprSyntax.self, self.visit) + self.visitImpl(&$0, KeyPathExprSyntax.self, self.visit) } case .keyPathOptionalComponent: return { - self.visitImpl($0, KeyPathOptionalComponentSyntax.self, self.visit) + self.visitImpl(&$0, KeyPathOptionalComponentSyntax.self, self.visit) } case .keyPathPropertyComponent: return { - self.visitImpl($0, KeyPathPropertyComponentSyntax.self, self.visit) + self.visitImpl(&$0, KeyPathPropertyComponentSyntax.self, self.visit) } case .keyPathSubscriptComponent: return { - self.visitImpl($0, KeyPathSubscriptComponentSyntax.self, self.visit) + self.visitImpl(&$0, KeyPathSubscriptComponentSyntax.self, self.visit) } case .labeledExprList: return { - self.visitImpl($0, LabeledExprListSyntax.self, self.visit) + self.visitImpl(&$0, LabeledExprListSyntax.self, self.visit) } case .labeledExpr: return { - self.visitImpl($0, LabeledExprSyntax.self, self.visit) + self.visitImpl(&$0, LabeledExprSyntax.self, self.visit) } case .labeledSpecializeArgument: return { - self.visitImpl($0, LabeledSpecializeArgumentSyntax.self, self.visit) + self.visitImpl(&$0, LabeledSpecializeArgumentSyntax.self, self.visit) } case .labeledStmt: return { - self.visitImpl($0, LabeledStmtSyntax.self, self.visit) + self.visitImpl(&$0, LabeledStmtSyntax.self, self.visit) } case .layoutRequirement: return { - self.visitImpl($0, LayoutRequirementSyntax.self, self.visit) + self.visitImpl(&$0, LayoutRequirementSyntax.self, self.visit) } case .lifetimeSpecifierArgumentList: return { - self.visitImpl($0, LifetimeSpecifierArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, LifetimeSpecifierArgumentListSyntax.self, self.visit) } case .lifetimeSpecifierArgument: return { - self.visitImpl($0, LifetimeSpecifierArgumentSyntax.self, self.visit) - } - case .lifetimeSpecifierArguments: - return { - self.visitImpl($0, LifetimeSpecifierArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, LifetimeSpecifierArgumentSyntax.self, self.visit) } case .lifetimeTypeSpecifier: return { - self.visitImpl($0, LifetimeTypeSpecifierSyntax.self, self.visit) + self.visitImpl(&$0, LifetimeTypeSpecifierSyntax.self, self.visit) } case .macroDecl: return { - self.visitImpl($0, MacroDeclSyntax.self, self.visit) + self.visitImpl(&$0, MacroDeclSyntax.self, self.visit) } case .macroExpansionDecl: return { - self.visitImpl($0, MacroExpansionDeclSyntax.self, self.visit) + self.visitImpl(&$0, MacroExpansionDeclSyntax.self, self.visit) } case .macroExpansionExpr: return { - self.visitImpl($0, MacroExpansionExprSyntax.self, self.visit) + self.visitImpl(&$0, MacroExpansionExprSyntax.self, self.visit) } case .matchingPatternCondition: return { - self.visitImpl($0, MatchingPatternConditionSyntax.self, self.visit) + self.visitImpl(&$0, MatchingPatternConditionSyntax.self, self.visit) } case .memberAccessExpr: return { - self.visitImpl($0, MemberAccessExprSyntax.self, self.visit) + self.visitImpl(&$0, MemberAccessExprSyntax.self, self.visit) } case .memberBlockItemList: return { - self.visitImpl($0, MemberBlockItemListSyntax.self, self.visit) + self.visitImpl(&$0, MemberBlockItemListSyntax.self, self.visit) } case .memberBlockItem: return { - self.visitImpl($0, MemberBlockItemSyntax.self, self.visit) + self.visitImpl(&$0, MemberBlockItemSyntax.self, self.visit) } case .memberBlock: return { - self.visitImpl($0, MemberBlockSyntax.self, self.visit) + self.visitImpl(&$0, MemberBlockSyntax.self, self.visit) } case .memberType: return { - self.visitImpl($0, MemberTypeSyntax.self, self.visit) + self.visitImpl(&$0, MemberTypeSyntax.self, self.visit) } case .metatypeType: return { - self.visitImpl($0, MetatypeTypeSyntax.self, self.visit) + self.visitImpl(&$0, MetatypeTypeSyntax.self, self.visit) } case .missingDecl: return { - self.visitImpl($0, MissingDeclSyntax.self, self.visit) + self.visitImpl(&$0, MissingDeclSyntax.self, self.visit) } case .missingExpr: return { - self.visitImpl($0, MissingExprSyntax.self, self.visit) + self.visitImpl(&$0, MissingExprSyntax.self, self.visit) } case .missingPattern: return { - self.visitImpl($0, MissingPatternSyntax.self, self.visit) + self.visitImpl(&$0, MissingPatternSyntax.self, self.visit) } case .missingStmt: return { - self.visitImpl($0, MissingStmtSyntax.self, self.visit) + self.visitImpl(&$0, MissingStmtSyntax.self, self.visit) } case .missing: return { - self.visitImpl($0, MissingSyntax.self, self.visit) + self.visitImpl(&$0, MissingSyntax.self, self.visit) } case .missingType: return { - self.visitImpl($0, MissingTypeSyntax.self, self.visit) + self.visitImpl(&$0, MissingTypeSyntax.self, self.visit) } case .multipleTrailingClosureElementList: return { - self.visitImpl($0, MultipleTrailingClosureElementListSyntax.self, self.visit) + self.visitImpl(&$0, MultipleTrailingClosureElementListSyntax.self, self.visit) } case .multipleTrailingClosureElement: return { - self.visitImpl($0, MultipleTrailingClosureElementSyntax.self, self.visit) + self.visitImpl(&$0, MultipleTrailingClosureElementSyntax.self, self.visit) } case .namedOpaqueReturnType: return { - self.visitImpl($0, NamedOpaqueReturnTypeSyntax.self, self.visit) + self.visitImpl(&$0, NamedOpaqueReturnTypeSyntax.self, self.visit) } case .nilLiteralExpr: return { - self.visitImpl($0, NilLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, NilLiteralExprSyntax.self, self.visit) } case .objCSelectorPieceList: return { - self.visitImpl($0, ObjCSelectorPieceListSyntax.self, self.visit) + self.visitImpl(&$0, ObjCSelectorPieceListSyntax.self, self.visit) } case .objCSelectorPiece: return { - self.visitImpl($0, ObjCSelectorPieceSyntax.self, self.visit) + self.visitImpl(&$0, ObjCSelectorPieceSyntax.self, self.visit) } case .opaqueReturnTypeOfAttributeArguments: return { - self.visitImpl($0, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, self.visit) } case .operatorDecl: return { - self.visitImpl($0, OperatorDeclSyntax.self, self.visit) + self.visitImpl(&$0, OperatorDeclSyntax.self, self.visit) } case .operatorPrecedenceAndTypes: return { - self.visitImpl($0, OperatorPrecedenceAndTypesSyntax.self, self.visit) + self.visitImpl(&$0, OperatorPrecedenceAndTypesSyntax.self, self.visit) } case .optionalBindingCondition: return { - self.visitImpl($0, OptionalBindingConditionSyntax.self, self.visit) + self.visitImpl(&$0, OptionalBindingConditionSyntax.self, self.visit) } case .optionalChainingExpr: return { - self.visitImpl($0, OptionalChainingExprSyntax.self, self.visit) + self.visitImpl(&$0, OptionalChainingExprSyntax.self, self.visit) } case .optionalType: return { - self.visitImpl($0, OptionalTypeSyntax.self, self.visit) + self.visitImpl(&$0, OptionalTypeSyntax.self, self.visit) } case .originallyDefinedInAttributeArguments: return { - self.visitImpl($0, OriginallyDefinedInAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, OriginallyDefinedInAttributeArgumentsSyntax.self, self.visit) } case .packElementExpr: return { - self.visitImpl($0, PackElementExprSyntax.self, self.visit) + self.visitImpl(&$0, PackElementExprSyntax.self, self.visit) } case .packElementType: return { - self.visitImpl($0, PackElementTypeSyntax.self, self.visit) + self.visitImpl(&$0, PackElementTypeSyntax.self, self.visit) } case .packExpansionExpr: return { - self.visitImpl($0, PackExpansionExprSyntax.self, self.visit) + self.visitImpl(&$0, PackExpansionExprSyntax.self, self.visit) } case .packExpansionType: return { - self.visitImpl($0, PackExpansionTypeSyntax.self, self.visit) + self.visitImpl(&$0, PackExpansionTypeSyntax.self, self.visit) } case .patternBindingList: return { - self.visitImpl($0, PatternBindingListSyntax.self, self.visit) + self.visitImpl(&$0, PatternBindingListSyntax.self, self.visit) } case .patternBinding: return { - self.visitImpl($0, PatternBindingSyntax.self, self.visit) + self.visitImpl(&$0, PatternBindingSyntax.self, self.visit) } case .patternExpr: return { - self.visitImpl($0, PatternExprSyntax.self, self.visit) + self.visitImpl(&$0, PatternExprSyntax.self, self.visit) } case .platformVersionItemList: return { - self.visitImpl($0, PlatformVersionItemListSyntax.self, self.visit) + self.visitImpl(&$0, PlatformVersionItemListSyntax.self, self.visit) } case .platformVersionItem: return { - self.visitImpl($0, PlatformVersionItemSyntax.self, self.visit) + self.visitImpl(&$0, PlatformVersionItemSyntax.self, self.visit) } case .platformVersion: return { - self.visitImpl($0, PlatformVersionSyntax.self, self.visit) + self.visitImpl(&$0, PlatformVersionSyntax.self, self.visit) } case .postfixIfConfigExpr: return { - self.visitImpl($0, PostfixIfConfigExprSyntax.self, self.visit) + self.visitImpl(&$0, PostfixIfConfigExprSyntax.self, self.visit) } case .postfixOperatorExpr: return { - self.visitImpl($0, PostfixOperatorExprSyntax.self, self.visit) + self.visitImpl(&$0, PostfixOperatorExprSyntax.self, self.visit) } case .poundSourceLocationArguments: return { - self.visitImpl($0, PoundSourceLocationArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, PoundSourceLocationArgumentsSyntax.self, self.visit) } case .poundSourceLocation: return { - self.visitImpl($0, PoundSourceLocationSyntax.self, self.visit) + self.visitImpl(&$0, PoundSourceLocationSyntax.self, self.visit) } case .precedenceGroupAssignment: return { - self.visitImpl($0, PrecedenceGroupAssignmentSyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupAssignmentSyntax.self, self.visit) } case .precedenceGroupAssociativity: return { - self.visitImpl($0, PrecedenceGroupAssociativitySyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupAssociativitySyntax.self, self.visit) } case .precedenceGroupAttributeList: return { - self.visitImpl($0, PrecedenceGroupAttributeListSyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupAttributeListSyntax.self, self.visit) } case .precedenceGroupDecl: return { - self.visitImpl($0, PrecedenceGroupDeclSyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupDeclSyntax.self, self.visit) } case .precedenceGroupNameList: return { - self.visitImpl($0, PrecedenceGroupNameListSyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupNameListSyntax.self, self.visit) } case .precedenceGroupName: return { - self.visitImpl($0, PrecedenceGroupNameSyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupNameSyntax.self, self.visit) } case .precedenceGroupRelation: return { - self.visitImpl($0, PrecedenceGroupRelationSyntax.self, self.visit) + self.visitImpl(&$0, PrecedenceGroupRelationSyntax.self, self.visit) } case .prefixOperatorExpr: return { - self.visitImpl($0, PrefixOperatorExprSyntax.self, self.visit) + self.visitImpl(&$0, PrefixOperatorExprSyntax.self, self.visit) } case .primaryAssociatedTypeClause: return { - self.visitImpl($0, PrimaryAssociatedTypeClauseSyntax.self, self.visit) + self.visitImpl(&$0, PrimaryAssociatedTypeClauseSyntax.self, self.visit) } case .primaryAssociatedTypeList: return { - self.visitImpl($0, PrimaryAssociatedTypeListSyntax.self, self.visit) + self.visitImpl(&$0, PrimaryAssociatedTypeListSyntax.self, self.visit) } case .primaryAssociatedType: return { - self.visitImpl($0, PrimaryAssociatedTypeSyntax.self, self.visit) + self.visitImpl(&$0, PrimaryAssociatedTypeSyntax.self, self.visit) } case .protocolDecl: return { - self.visitImpl($0, ProtocolDeclSyntax.self, self.visit) + self.visitImpl(&$0, ProtocolDeclSyntax.self, self.visit) } case .regexLiteralExpr: return { - self.visitImpl($0, RegexLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, RegexLiteralExprSyntax.self, self.visit) } case .repeatStmt: return { - self.visitImpl($0, RepeatStmtSyntax.self, self.visit) + self.visitImpl(&$0, RepeatStmtSyntax.self, self.visit) } case .returnClause: return { - self.visitImpl($0, ReturnClauseSyntax.self, self.visit) + self.visitImpl(&$0, ReturnClauseSyntax.self, self.visit) } case .returnStmt: return { - self.visitImpl($0, ReturnStmtSyntax.self, self.visit) + self.visitImpl(&$0, ReturnStmtSyntax.self, self.visit) } case .sameTypeRequirement: return { - self.visitImpl($0, SameTypeRequirementSyntax.self, self.visit) + self.visitImpl(&$0, SameTypeRequirementSyntax.self, self.visit) } case .sequenceExpr: return { - self.visitImpl($0, SequenceExprSyntax.self, self.visit) + self.visitImpl(&$0, SequenceExprSyntax.self, self.visit) } case .simpleStringLiteralExpr: return { - self.visitImpl($0, SimpleStringLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, SimpleStringLiteralExprSyntax.self, self.visit) } case .simpleStringLiteralSegmentList: return { - self.visitImpl($0, SimpleStringLiteralSegmentListSyntax.self, self.visit) + self.visitImpl(&$0, SimpleStringLiteralSegmentListSyntax.self, self.visit) } case .simpleTypeSpecifier: return { - self.visitImpl($0, SimpleTypeSpecifierSyntax.self, self.visit) + self.visitImpl(&$0, SimpleTypeSpecifierSyntax.self, self.visit) } case .someOrAnyType: return { - self.visitImpl($0, SomeOrAnyTypeSyntax.self, self.visit) + self.visitImpl(&$0, SomeOrAnyTypeSyntax.self, self.visit) } case .sourceFile: return { - self.visitImpl($0, SourceFileSyntax.self, self.visit) + self.visitImpl(&$0, SourceFileSyntax.self, self.visit) } case .specializeAttributeArgumentList: return { - self.visitImpl($0, SpecializeAttributeArgumentListSyntax.self, self.visit) + self.visitImpl(&$0, SpecializeAttributeArgumentListSyntax.self, self.visit) } case .specializeAvailabilityArgument: return { - self.visitImpl($0, SpecializeAvailabilityArgumentSyntax.self, self.visit) + self.visitImpl(&$0, SpecializeAvailabilityArgumentSyntax.self, self.visit) } case .specializeTargetFunctionArgument: return { - self.visitImpl($0, SpecializeTargetFunctionArgumentSyntax.self, self.visit) + self.visitImpl(&$0, SpecializeTargetFunctionArgumentSyntax.self, self.visit) } case .stringLiteralExpr: return { - self.visitImpl($0, StringLiteralExprSyntax.self, self.visit) + self.visitImpl(&$0, StringLiteralExprSyntax.self, self.visit) } case .stringLiteralSegmentList: return { - self.visitImpl($0, StringLiteralSegmentListSyntax.self, self.visit) + self.visitImpl(&$0, StringLiteralSegmentListSyntax.self, self.visit) } case .stringSegment: return { - self.visitImpl($0, StringSegmentSyntax.self, self.visit) + self.visitImpl(&$0, StringSegmentSyntax.self, self.visit) } case .structDecl: return { - self.visitImpl($0, StructDeclSyntax.self, self.visit) + self.visitImpl(&$0, StructDeclSyntax.self, self.visit) } case .subscriptCallExpr: return { - self.visitImpl($0, SubscriptCallExprSyntax.self, self.visit) + self.visitImpl(&$0, SubscriptCallExprSyntax.self, self.visit) } case .subscriptDecl: return { - self.visitImpl($0, SubscriptDeclSyntax.self, self.visit) + self.visitImpl(&$0, SubscriptDeclSyntax.self, self.visit) } case .superExpr: return { - self.visitImpl($0, SuperExprSyntax.self, self.visit) + self.visitImpl(&$0, SuperExprSyntax.self, self.visit) } case .suppressedType: return { - self.visitImpl($0, SuppressedTypeSyntax.self, self.visit) + self.visitImpl(&$0, SuppressedTypeSyntax.self, self.visit) } case .switchCaseItemList: return { - self.visitImpl($0, SwitchCaseItemListSyntax.self, self.visit) + self.visitImpl(&$0, SwitchCaseItemListSyntax.self, self.visit) } case .switchCaseItem: return { - self.visitImpl($0, SwitchCaseItemSyntax.self, self.visit) + self.visitImpl(&$0, SwitchCaseItemSyntax.self, self.visit) } case .switchCaseLabel: return { - self.visitImpl($0, SwitchCaseLabelSyntax.self, self.visit) + self.visitImpl(&$0, SwitchCaseLabelSyntax.self, self.visit) } case .switchCaseList: return { - self.visitImpl($0, SwitchCaseListSyntax.self, self.visit) + self.visitImpl(&$0, SwitchCaseListSyntax.self, self.visit) } case .switchCase: return { - self.visitImpl($0, SwitchCaseSyntax.self, self.visit) + self.visitImpl(&$0, SwitchCaseSyntax.self, self.visit) } case .switchDefaultLabel: return { - self.visitImpl($0, SwitchDefaultLabelSyntax.self, self.visit) + self.visitImpl(&$0, SwitchDefaultLabelSyntax.self, self.visit) } case .switchExpr: return { - self.visitImpl($0, SwitchExprSyntax.self, self.visit) + self.visitImpl(&$0, SwitchExprSyntax.self, self.visit) } case .ternaryExpr: return { - self.visitImpl($0, TernaryExprSyntax.self, self.visit) + self.visitImpl(&$0, TernaryExprSyntax.self, self.visit) } case .thenStmt: return { - self.visitImpl($0, ThenStmtSyntax.self, self.visit) + self.visitImpl(&$0, ThenStmtSyntax.self, self.visit) } case .throwStmt: return { - self.visitImpl($0, ThrowStmtSyntax.self, self.visit) + self.visitImpl(&$0, ThrowStmtSyntax.self, self.visit) } case .throwsClause: return { - self.visitImpl($0, ThrowsClauseSyntax.self, self.visit) + self.visitImpl(&$0, ThrowsClauseSyntax.self, self.visit) } case .tryExpr: return { - self.visitImpl($0, TryExprSyntax.self, self.visit) + self.visitImpl(&$0, TryExprSyntax.self, self.visit) } case .tupleExpr: return { - self.visitImpl($0, TupleExprSyntax.self, self.visit) + self.visitImpl(&$0, TupleExprSyntax.self, self.visit) } case .tuplePatternElementList: return { - self.visitImpl($0, TuplePatternElementListSyntax.self, self.visit) + self.visitImpl(&$0, TuplePatternElementListSyntax.self, self.visit) } case .tuplePatternElement: return { - self.visitImpl($0, TuplePatternElementSyntax.self, self.visit) + self.visitImpl(&$0, TuplePatternElementSyntax.self, self.visit) } case .tuplePattern: return { - self.visitImpl($0, TuplePatternSyntax.self, self.visit) + self.visitImpl(&$0, TuplePatternSyntax.self, self.visit) } case .tupleTypeElementList: return { - self.visitImpl($0, TupleTypeElementListSyntax.self, self.visit) + self.visitImpl(&$0, TupleTypeElementListSyntax.self, self.visit) } case .tupleTypeElement: return { - self.visitImpl($0, TupleTypeElementSyntax.self, self.visit) + self.visitImpl(&$0, TupleTypeElementSyntax.self, self.visit) } case .tupleType: return { - self.visitImpl($0, TupleTypeSyntax.self, self.visit) + self.visitImpl(&$0, TupleTypeSyntax.self, self.visit) } case .typeAliasDecl: return { - self.visitImpl($0, TypeAliasDeclSyntax.self, self.visit) + self.visitImpl(&$0, TypeAliasDeclSyntax.self, self.visit) } case .typeAnnotation: return { - self.visitImpl($0, TypeAnnotationSyntax.self, self.visit) + self.visitImpl(&$0, TypeAnnotationSyntax.self, self.visit) } case .typeEffectSpecifiers: return { - self.visitImpl($0, TypeEffectSpecifiersSyntax.self, self.visit) + self.visitImpl(&$0, TypeEffectSpecifiersSyntax.self, self.visit) } case .typeExpr: return { - self.visitImpl($0, TypeExprSyntax.self, self.visit) + self.visitImpl(&$0, TypeExprSyntax.self, self.visit) } case .typeInitializerClause: return { - self.visitImpl($0, TypeInitializerClauseSyntax.self, self.visit) + self.visitImpl(&$0, TypeInitializerClauseSyntax.self, self.visit) } case .typeSpecifierList: return { - self.visitImpl($0, TypeSpecifierListSyntax.self, self.visit) + self.visitImpl(&$0, TypeSpecifierListSyntax.self, self.visit) } case .unavailableFromAsyncAttributeArguments: return { - self.visitImpl($0, UnavailableFromAsyncAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, UnavailableFromAsyncAttributeArgumentsSyntax.self, self.visit) } case .underscorePrivateAttributeArguments: return { - self.visitImpl($0, UnderscorePrivateAttributeArgumentsSyntax.self, self.visit) + self.visitImpl(&$0, UnderscorePrivateAttributeArgumentsSyntax.self, self.visit) } case .unexpectedNodes: return { - self.visitImpl($0, UnexpectedNodesSyntax.self, self.visit) + self.visitImpl(&$0, UnexpectedNodesSyntax.self, self.visit) } case .unresolvedAsExpr: return { - self.visitImpl($0, UnresolvedAsExprSyntax.self, self.visit) + self.visitImpl(&$0, UnresolvedAsExprSyntax.self, self.visit) } case .unresolvedIsExpr: return { - self.visitImpl($0, UnresolvedIsExprSyntax.self, self.visit) + self.visitImpl(&$0, UnresolvedIsExprSyntax.self, self.visit) } case .unresolvedTernaryExpr: return { - self.visitImpl($0, UnresolvedTernaryExprSyntax.self, self.visit) + self.visitImpl(&$0, UnresolvedTernaryExprSyntax.self, self.visit) } case .valueBindingPattern: return { - self.visitImpl($0, ValueBindingPatternSyntax.self, self.visit) + self.visitImpl(&$0, ValueBindingPatternSyntax.self, self.visit) } case .variableDecl: return { - self.visitImpl($0, VariableDeclSyntax.self, self.visit) + self.visitImpl(&$0, VariableDeclSyntax.self, self.visit) } case .versionComponentList: return { - self.visitImpl($0, VersionComponentListSyntax.self, self.visit) + self.visitImpl(&$0, VersionComponentListSyntax.self, self.visit) } case .versionComponent: return { - self.visitImpl($0, VersionComponentSyntax.self, self.visit) + self.visitImpl(&$0, VersionComponentSyntax.self, self.visit) } case .versionTuple: return { - self.visitImpl($0, VersionTupleSyntax.self, self.visit) + self.visitImpl(&$0, VersionTupleSyntax.self, self.visit) } case .whereClause: return { - self.visitImpl($0, WhereClauseSyntax.self, self.visit) + self.visitImpl(&$0, WhereClauseSyntax.self, self.visit) } case .whileStmt: return { - self.visitImpl($0, WhileStmtSyntax.self, self.visit) + self.visitImpl(&$0, WhileStmtSyntax.self, self.visit) } case .wildcardPattern: return { - self.visitImpl($0, WildcardPatternSyntax.self, self.visit) + self.visitImpl(&$0, WildcardPatternSyntax.self, self.visit) } case .yieldStmt: return { - self.visitImpl($0, YieldStmtSyntax.self, self.visit) + self.visitImpl(&$0, YieldStmtSyntax.self, self.visit) } case .yieldedExpressionList: return { - self.visitImpl($0, YieldedExpressionListSyntax.self, self.visit) + self.visitImpl(&$0, YieldedExpressionListSyntax.self, self.visit) } case .yieldedExpression: return { - self.visitImpl($0, YieldedExpressionSyntax.self, self.visit) + self.visitImpl(&$0, YieldedExpressionSyntax.self, self.visit) } case .yieldedExpressionsClause: return { - self.visitImpl($0, YieldedExpressionsClauseSyntax.self, self.visit) + self.visitImpl(&$0, YieldedExpressionsClauseSyntax.self, self.visit) } } } - private func dispatchVisit(_ node: Syntax) -> Syntax { - return visitationFunc(for: node)(node) + private func dispatchVisit(_ node: inout Syntax) { + visitationFunc(for: node)(&node) } #else - private func dispatchVisit(_ node: Syntax) -> Syntax { + private func dispatchVisit(_ node: inout Syntax) { switch node.raw.kind { case .token: - return visitImpl(node, TokenSyntax.self, visit) + return visitImpl(&node, TokenSyntax.self, visit) case .accessorBlock: - return visitImpl(node, AccessorBlockSyntax.self, visit) + return visitImpl(&node, AccessorBlockSyntax.self, visit) case .accessorDeclList: - return visitImpl(node, AccessorDeclListSyntax.self, visit) + return visitImpl(&node, AccessorDeclListSyntax.self, visit) case .accessorDecl: - return visitImpl(node, AccessorDeclSyntax.self, visit) + return visitImpl(&node, AccessorDeclSyntax.self, visit) case .accessorEffectSpecifiers: - return visitImpl(node, AccessorEffectSpecifiersSyntax.self, visit) + return visitImpl(&node, AccessorEffectSpecifiersSyntax.self, visit) case .accessorParameters: - return visitImpl(node, AccessorParametersSyntax.self, visit) + return visitImpl(&node, AccessorParametersSyntax.self, visit) case .actorDecl: - return visitImpl(node, ActorDeclSyntax.self, visit) + return visitImpl(&node, ActorDeclSyntax.self, visit) case .arrayElementList: - return visitImpl(node, ArrayElementListSyntax.self, visit) + return visitImpl(&node, ArrayElementListSyntax.self, visit) case .arrayElement: - return visitImpl(node, ArrayElementSyntax.self, visit) + return visitImpl(&node, ArrayElementSyntax.self, visit) case .arrayExpr: - return visitImpl(node, ArrayExprSyntax.self, visit) + return visitImpl(&node, ArrayExprSyntax.self, visit) case .arrayType: - return visitImpl(node, ArrayTypeSyntax.self, visit) + return visitImpl(&node, ArrayTypeSyntax.self, visit) case .arrowExpr: - return visitImpl(node, ArrowExprSyntax.self, visit) + return visitImpl(&node, ArrowExprSyntax.self, visit) case .asExpr: - return visitImpl(node, AsExprSyntax.self, visit) + return visitImpl(&node, AsExprSyntax.self, visit) case .assignmentExpr: - return visitImpl(node, AssignmentExprSyntax.self, visit) + return visitImpl(&node, AssignmentExprSyntax.self, visit) case .associatedTypeDecl: - return visitImpl(node, AssociatedTypeDeclSyntax.self, visit) + return visitImpl(&node, AssociatedTypeDeclSyntax.self, visit) case .attributeList: - return visitImpl(node, AttributeListSyntax.self, visit) + return visitImpl(&node, AttributeListSyntax.self, visit) case .attribute: - return visitImpl(node, AttributeSyntax.self, visit) + return visitImpl(&node, AttributeSyntax.self, visit) case .attributedType: - return visitImpl(node, AttributedTypeSyntax.self, visit) + return visitImpl(&node, AttributedTypeSyntax.self, visit) case .availabilityArgumentList: - return visitImpl(node, AvailabilityArgumentListSyntax.self, visit) + return visitImpl(&node, AvailabilityArgumentListSyntax.self, visit) case .availabilityArgument: - return visitImpl(node, AvailabilityArgumentSyntax.self, visit) + return visitImpl(&node, AvailabilityArgumentSyntax.self, visit) case .availabilityCondition: - return visitImpl(node, AvailabilityConditionSyntax.self, visit) + return visitImpl(&node, AvailabilityConditionSyntax.self, visit) case .availabilityLabeledArgument: - return visitImpl(node, AvailabilityLabeledArgumentSyntax.self, visit) + return visitImpl(&node, AvailabilityLabeledArgumentSyntax.self, visit) case .awaitExpr: - return visitImpl(node, AwaitExprSyntax.self, visit) + return visitImpl(&node, AwaitExprSyntax.self, visit) case .backDeployedAttributeArguments: - return visitImpl(node, BackDeployedAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, BackDeployedAttributeArgumentsSyntax.self, visit) case .binaryOperatorExpr: - return visitImpl(node, BinaryOperatorExprSyntax.self, visit) + return visitImpl(&node, BinaryOperatorExprSyntax.self, visit) case .booleanLiteralExpr: - return visitImpl(node, BooleanLiteralExprSyntax.self, visit) + return visitImpl(&node, BooleanLiteralExprSyntax.self, visit) case .borrowExpr: - return visitImpl(node, BorrowExprSyntax.self, visit) + return visitImpl(&node, BorrowExprSyntax.self, visit) case .breakStmt: - return visitImpl(node, BreakStmtSyntax.self, visit) - case .canImportExpr: - return visitImpl(node, CanImportExprSyntax.self, visit) - case .canImportVersionInfo: - return visitImpl(node, CanImportVersionInfoSyntax.self, visit) + return visitImpl(&node, BreakStmtSyntax.self, visit) + case ._canImportExpr: + return visitImpl(&node, _CanImportExprSyntax.self, visit) + case ._canImportVersionInfo: + return visitImpl(&node, _CanImportVersionInfoSyntax.self, visit) case .catchClauseList: - return visitImpl(node, CatchClauseListSyntax.self, visit) + return visitImpl(&node, CatchClauseListSyntax.self, visit) case .catchClause: - return visitImpl(node, CatchClauseSyntax.self, visit) + return visitImpl(&node, CatchClauseSyntax.self, visit) case .catchItemList: - return visitImpl(node, CatchItemListSyntax.self, visit) + return visitImpl(&node, CatchItemListSyntax.self, visit) case .catchItem: - return visitImpl(node, CatchItemSyntax.self, visit) + return visitImpl(&node, CatchItemSyntax.self, visit) case .classDecl: - return visitImpl(node, ClassDeclSyntax.self, visit) + return visitImpl(&node, ClassDeclSyntax.self, visit) case .classRestrictionType: - return visitImpl(node, ClassRestrictionTypeSyntax.self, visit) + return visitImpl(&node, ClassRestrictionTypeSyntax.self, visit) case .closureCaptureClause: - return visitImpl(node, ClosureCaptureClauseSyntax.self, visit) + return visitImpl(&node, ClosureCaptureClauseSyntax.self, visit) case .closureCaptureList: - return visitImpl(node, ClosureCaptureListSyntax.self, visit) + return visitImpl(&node, ClosureCaptureListSyntax.self, visit) case .closureCaptureSpecifier: - return visitImpl(node, ClosureCaptureSpecifierSyntax.self, visit) + return visitImpl(&node, ClosureCaptureSpecifierSyntax.self, visit) case .closureCapture: - return visitImpl(node, ClosureCaptureSyntax.self, visit) + return visitImpl(&node, ClosureCaptureSyntax.self, visit) case .closureExpr: - return visitImpl(node, ClosureExprSyntax.self, visit) + return visitImpl(&node, ClosureExprSyntax.self, visit) case .closureParameterClause: - return visitImpl(node, ClosureParameterClauseSyntax.self, visit) + return visitImpl(&node, ClosureParameterClauseSyntax.self, visit) case .closureParameterList: - return visitImpl(node, ClosureParameterListSyntax.self, visit) + return visitImpl(&node, ClosureParameterListSyntax.self, visit) case .closureParameter: - return visitImpl(node, ClosureParameterSyntax.self, visit) + return visitImpl(&node, ClosureParameterSyntax.self, visit) case .closureShorthandParameterList: - return visitImpl(node, ClosureShorthandParameterListSyntax.self, visit) + return visitImpl(&node, ClosureShorthandParameterListSyntax.self, visit) case .closureShorthandParameter: - return visitImpl(node, ClosureShorthandParameterSyntax.self, visit) + return visitImpl(&node, ClosureShorthandParameterSyntax.self, visit) case .closureSignature: - return visitImpl(node, ClosureSignatureSyntax.self, visit) + return visitImpl(&node, ClosureSignatureSyntax.self, visit) case .codeBlockItemList: - return visitImpl(node, CodeBlockItemListSyntax.self, visit) + return visitImpl(&node, CodeBlockItemListSyntax.self, visit) case .codeBlockItem: - return visitImpl(node, CodeBlockItemSyntax.self, visit) + return visitImpl(&node, CodeBlockItemSyntax.self, visit) case .codeBlock: - return visitImpl(node, CodeBlockSyntax.self, visit) + return visitImpl(&node, CodeBlockSyntax.self, visit) case .compositionTypeElementList: - return visitImpl(node, CompositionTypeElementListSyntax.self, visit) + return visitImpl(&node, CompositionTypeElementListSyntax.self, visit) case .compositionTypeElement: - return visitImpl(node, CompositionTypeElementSyntax.self, visit) + return visitImpl(&node, CompositionTypeElementSyntax.self, visit) case .compositionType: - return visitImpl(node, CompositionTypeSyntax.self, visit) + return visitImpl(&node, CompositionTypeSyntax.self, visit) case .conditionElementList: - return visitImpl(node, ConditionElementListSyntax.self, visit) + return visitImpl(&node, ConditionElementListSyntax.self, visit) case .conditionElement: - return visitImpl(node, ConditionElementSyntax.self, visit) + return visitImpl(&node, ConditionElementSyntax.self, visit) case .conformanceRequirement: - return visitImpl(node, ConformanceRequirementSyntax.self, visit) + return visitImpl(&node, ConformanceRequirementSyntax.self, visit) case .consumeExpr: - return visitImpl(node, ConsumeExprSyntax.self, visit) + return visitImpl(&node, ConsumeExprSyntax.self, visit) case .continueStmt: - return visitImpl(node, ContinueStmtSyntax.self, visit) + return visitImpl(&node, ContinueStmtSyntax.self, visit) case .conventionAttributeArguments: - return visitImpl(node, ConventionAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, ConventionAttributeArgumentsSyntax.self, visit) case .conventionWitnessMethodAttributeArguments: - return visitImpl(node, ConventionWitnessMethodAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, ConventionWitnessMethodAttributeArgumentsSyntax.self, visit) case .copyExpr: - return visitImpl(node, CopyExprSyntax.self, visit) + return visitImpl(&node, CopyExprSyntax.self, visit) case .declModifierDetail: - return visitImpl(node, DeclModifierDetailSyntax.self, visit) + return visitImpl(&node, DeclModifierDetailSyntax.self, visit) case .declModifierList: - return visitImpl(node, DeclModifierListSyntax.self, visit) + return visitImpl(&node, DeclModifierListSyntax.self, visit) case .declModifier: - return visitImpl(node, DeclModifierSyntax.self, visit) + return visitImpl(&node, DeclModifierSyntax.self, visit) case .declNameArgumentList: - return visitImpl(node, DeclNameArgumentListSyntax.self, visit) + return visitImpl(&node, DeclNameArgumentListSyntax.self, visit) case .declNameArgument: - return visitImpl(node, DeclNameArgumentSyntax.self, visit) + return visitImpl(&node, DeclNameArgumentSyntax.self, visit) case .declNameArguments: - return visitImpl(node, DeclNameArgumentsSyntax.self, visit) + return visitImpl(&node, DeclNameArgumentsSyntax.self, visit) case .declReferenceExpr: - return visitImpl(node, DeclReferenceExprSyntax.self, visit) + return visitImpl(&node, DeclReferenceExprSyntax.self, visit) case .deferStmt: - return visitImpl(node, DeferStmtSyntax.self, visit) + return visitImpl(&node, DeferStmtSyntax.self, visit) case .deinitializerDecl: - return visitImpl(node, DeinitializerDeclSyntax.self, visit) + return visitImpl(&node, DeinitializerDeclSyntax.self, visit) case .deinitializerEffectSpecifiers: - return visitImpl(node, DeinitializerEffectSpecifiersSyntax.self, visit) + return visitImpl(&node, DeinitializerEffectSpecifiersSyntax.self, visit) case .derivativeAttributeArguments: - return visitImpl(node, DerivativeAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, DerivativeAttributeArgumentsSyntax.self, visit) case .designatedTypeList: - return visitImpl(node, DesignatedTypeListSyntax.self, visit) + return visitImpl(&node, DesignatedTypeListSyntax.self, visit) case .designatedType: - return visitImpl(node, DesignatedTypeSyntax.self, visit) + return visitImpl(&node, DesignatedTypeSyntax.self, visit) case .dictionaryElementList: - return visitImpl(node, DictionaryElementListSyntax.self, visit) + return visitImpl(&node, DictionaryElementListSyntax.self, visit) case .dictionaryElement: - return visitImpl(node, DictionaryElementSyntax.self, visit) + return visitImpl(&node, DictionaryElementSyntax.self, visit) case .dictionaryExpr: - return visitImpl(node, DictionaryExprSyntax.self, visit) + return visitImpl(&node, DictionaryExprSyntax.self, visit) case .dictionaryType: - return visitImpl(node, DictionaryTypeSyntax.self, visit) + return visitImpl(&node, DictionaryTypeSyntax.self, visit) case .differentiabilityArgumentList: - return visitImpl(node, DifferentiabilityArgumentListSyntax.self, visit) + return visitImpl(&node, DifferentiabilityArgumentListSyntax.self, visit) case .differentiabilityArgument: - return visitImpl(node, DifferentiabilityArgumentSyntax.self, visit) + return visitImpl(&node, DifferentiabilityArgumentSyntax.self, visit) case .differentiabilityArguments: - return visitImpl(node, DifferentiabilityArgumentsSyntax.self, visit) + return visitImpl(&node, DifferentiabilityArgumentsSyntax.self, visit) case .differentiabilityWithRespectToArgument: - return visitImpl(node, DifferentiabilityWithRespectToArgumentSyntax.self, visit) + return visitImpl(&node, DifferentiabilityWithRespectToArgumentSyntax.self, visit) case .differentiableAttributeArguments: - return visitImpl(node, DifferentiableAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, DifferentiableAttributeArgumentsSyntax.self, visit) case .discardAssignmentExpr: - return visitImpl(node, DiscardAssignmentExprSyntax.self, visit) + return visitImpl(&node, DiscardAssignmentExprSyntax.self, visit) case .discardStmt: - return visitImpl(node, DiscardStmtSyntax.self, visit) + return visitImpl(&node, DiscardStmtSyntax.self, visit) case .doExpr: - return visitImpl(node, DoExprSyntax.self, visit) + return visitImpl(&node, DoExprSyntax.self, visit) case .doStmt: - return visitImpl(node, DoStmtSyntax.self, visit) + return visitImpl(&node, DoStmtSyntax.self, visit) case .documentationAttributeArgumentList: - return visitImpl(node, DocumentationAttributeArgumentListSyntax.self, visit) + return visitImpl(&node, DocumentationAttributeArgumentListSyntax.self, visit) case .documentationAttributeArgument: - return visitImpl(node, DocumentationAttributeArgumentSyntax.self, visit) + return visitImpl(&node, DocumentationAttributeArgumentSyntax.self, visit) case .dynamicReplacementAttributeArguments: - return visitImpl(node, DynamicReplacementAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, DynamicReplacementAttributeArgumentsSyntax.self, visit) case .editorPlaceholderDecl: - return visitImpl(node, EditorPlaceholderDeclSyntax.self, visit) + return visitImpl(&node, EditorPlaceholderDeclSyntax.self, visit) case .editorPlaceholderExpr: - return visitImpl(node, EditorPlaceholderExprSyntax.self, visit) + return visitImpl(&node, EditorPlaceholderExprSyntax.self, visit) case .effectsAttributeArgumentList: - return visitImpl(node, EffectsAttributeArgumentListSyntax.self, visit) + return visitImpl(&node, EffectsAttributeArgumentListSyntax.self, visit) case .enumCaseDecl: - return visitImpl(node, EnumCaseDeclSyntax.self, visit) + return visitImpl(&node, EnumCaseDeclSyntax.self, visit) case .enumCaseElementList: - return visitImpl(node, EnumCaseElementListSyntax.self, visit) + return visitImpl(&node, EnumCaseElementListSyntax.self, visit) case .enumCaseElement: - return visitImpl(node, EnumCaseElementSyntax.self, visit) + return visitImpl(&node, EnumCaseElementSyntax.self, visit) case .enumCaseParameterClause: - return visitImpl(node, EnumCaseParameterClauseSyntax.self, visit) + return visitImpl(&node, EnumCaseParameterClauseSyntax.self, visit) case .enumCaseParameterList: - return visitImpl(node, EnumCaseParameterListSyntax.self, visit) + return visitImpl(&node, EnumCaseParameterListSyntax.self, visit) case .enumCaseParameter: - return visitImpl(node, EnumCaseParameterSyntax.self, visit) + return visitImpl(&node, EnumCaseParameterSyntax.self, visit) case .enumDecl: - return visitImpl(node, EnumDeclSyntax.self, visit) + return visitImpl(&node, EnumDeclSyntax.self, visit) case .exposeAttributeArguments: - return visitImpl(node, ExposeAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, ExposeAttributeArgumentsSyntax.self, visit) case .exprList: - return visitImpl(node, ExprListSyntax.self, visit) + return visitImpl(&node, ExprListSyntax.self, visit) case .expressionPattern: - return visitImpl(node, ExpressionPatternSyntax.self, visit) + return visitImpl(&node, ExpressionPatternSyntax.self, visit) case .expressionSegment: - return visitImpl(node, ExpressionSegmentSyntax.self, visit) + return visitImpl(&node, ExpressionSegmentSyntax.self, visit) case .expressionStmt: - return visitImpl(node, ExpressionStmtSyntax.self, visit) + return visitImpl(&node, ExpressionStmtSyntax.self, visit) case .extensionDecl: - return visitImpl(node, ExtensionDeclSyntax.self, visit) + return visitImpl(&node, ExtensionDeclSyntax.self, visit) case .fallThroughStmt: - return visitImpl(node, FallThroughStmtSyntax.self, visit) + return visitImpl(&node, FallThroughStmtSyntax.self, visit) case .floatLiteralExpr: - return visitImpl(node, FloatLiteralExprSyntax.self, visit) + return visitImpl(&node, FloatLiteralExprSyntax.self, visit) case .forStmt: - return visitImpl(node, ForStmtSyntax.self, visit) + return visitImpl(&node, ForStmtSyntax.self, visit) case .forceUnwrapExpr: - return visitImpl(node, ForceUnwrapExprSyntax.self, visit) + return visitImpl(&node, ForceUnwrapExprSyntax.self, visit) case .functionCallExpr: - return visitImpl(node, FunctionCallExprSyntax.self, visit) + return visitImpl(&node, FunctionCallExprSyntax.self, visit) case .functionDecl: - return visitImpl(node, FunctionDeclSyntax.self, visit) + return visitImpl(&node, FunctionDeclSyntax.self, visit) case .functionEffectSpecifiers: - return visitImpl(node, FunctionEffectSpecifiersSyntax.self, visit) + return visitImpl(&node, FunctionEffectSpecifiersSyntax.self, visit) case .functionParameterClause: - return visitImpl(node, FunctionParameterClauseSyntax.self, visit) + return visitImpl(&node, FunctionParameterClauseSyntax.self, visit) case .functionParameterList: - return visitImpl(node, FunctionParameterListSyntax.self, visit) + return visitImpl(&node, FunctionParameterListSyntax.self, visit) case .functionParameter: - return visitImpl(node, FunctionParameterSyntax.self, visit) + return visitImpl(&node, FunctionParameterSyntax.self, visit) case .functionSignature: - return visitImpl(node, FunctionSignatureSyntax.self, visit) + return visitImpl(&node, FunctionSignatureSyntax.self, visit) case .functionType: - return visitImpl(node, FunctionTypeSyntax.self, visit) + return visitImpl(&node, FunctionTypeSyntax.self, visit) case .genericArgumentClause: - return visitImpl(node, GenericArgumentClauseSyntax.self, visit) + return visitImpl(&node, GenericArgumentClauseSyntax.self, visit) case .genericArgumentList: - return visitImpl(node, GenericArgumentListSyntax.self, visit) + return visitImpl(&node, GenericArgumentListSyntax.self, visit) case .genericArgument: - return visitImpl(node, GenericArgumentSyntax.self, visit) + return visitImpl(&node, GenericArgumentSyntax.self, visit) case .genericParameterClause: - return visitImpl(node, GenericParameterClauseSyntax.self, visit) + return visitImpl(&node, GenericParameterClauseSyntax.self, visit) case .genericParameterList: - return visitImpl(node, GenericParameterListSyntax.self, visit) + return visitImpl(&node, GenericParameterListSyntax.self, visit) case .genericParameter: - return visitImpl(node, GenericParameterSyntax.self, visit) + return visitImpl(&node, GenericParameterSyntax.self, visit) case .genericRequirementList: - return visitImpl(node, GenericRequirementListSyntax.self, visit) + return visitImpl(&node, GenericRequirementListSyntax.self, visit) case .genericRequirement: - return visitImpl(node, GenericRequirementSyntax.self, visit) + return visitImpl(&node, GenericRequirementSyntax.self, visit) case .genericSpecializationExpr: - return visitImpl(node, GenericSpecializationExprSyntax.self, visit) + return visitImpl(&node, GenericSpecializationExprSyntax.self, visit) case .genericWhereClause: - return visitImpl(node, GenericWhereClauseSyntax.self, visit) + return visitImpl(&node, GenericWhereClauseSyntax.self, visit) case .guardStmt: - return visitImpl(node, GuardStmtSyntax.self, visit) + return visitImpl(&node, GuardStmtSyntax.self, visit) case .identifierPattern: - return visitImpl(node, IdentifierPatternSyntax.self, visit) + return visitImpl(&node, IdentifierPatternSyntax.self, visit) case .identifierType: - return visitImpl(node, IdentifierTypeSyntax.self, visit) + return visitImpl(&node, IdentifierTypeSyntax.self, visit) case .ifConfigClauseList: - return visitImpl(node, IfConfigClauseListSyntax.self, visit) + return visitImpl(&node, IfConfigClauseListSyntax.self, visit) case .ifConfigClause: - return visitImpl(node, IfConfigClauseSyntax.self, visit) + return visitImpl(&node, IfConfigClauseSyntax.self, visit) case .ifConfigDecl: - return visitImpl(node, IfConfigDeclSyntax.self, visit) + return visitImpl(&node, IfConfigDeclSyntax.self, visit) case .ifExpr: - return visitImpl(node, IfExprSyntax.self, visit) + return visitImpl(&node, IfExprSyntax.self, visit) case .implementsAttributeArguments: - return visitImpl(node, ImplementsAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, ImplementsAttributeArgumentsSyntax.self, visit) case .implicitlyUnwrappedOptionalType: - return visitImpl(node, ImplicitlyUnwrappedOptionalTypeSyntax.self, visit) + return visitImpl(&node, ImplicitlyUnwrappedOptionalTypeSyntax.self, visit) case .importDecl: - return visitImpl(node, ImportDeclSyntax.self, visit) + return visitImpl(&node, ImportDeclSyntax.self, visit) case .importPathComponentList: - return visitImpl(node, ImportPathComponentListSyntax.self, visit) + return visitImpl(&node, ImportPathComponentListSyntax.self, visit) case .importPathComponent: - return visitImpl(node, ImportPathComponentSyntax.self, visit) + return visitImpl(&node, ImportPathComponentSyntax.self, visit) case .inOutExpr: - return visitImpl(node, InOutExprSyntax.self, visit) + return visitImpl(&node, InOutExprSyntax.self, visit) case .infixOperatorExpr: - return visitImpl(node, InfixOperatorExprSyntax.self, visit) + return visitImpl(&node, InfixOperatorExprSyntax.self, visit) case .inheritanceClause: - return visitImpl(node, InheritanceClauseSyntax.self, visit) + return visitImpl(&node, InheritanceClauseSyntax.self, visit) case .inheritedTypeList: - return visitImpl(node, InheritedTypeListSyntax.self, visit) + return visitImpl(&node, InheritedTypeListSyntax.self, visit) case .inheritedType: - return visitImpl(node, InheritedTypeSyntax.self, visit) + return visitImpl(&node, InheritedTypeSyntax.self, visit) case .initializerClause: - return visitImpl(node, InitializerClauseSyntax.self, visit) + return visitImpl(&node, InitializerClauseSyntax.self, visit) case .initializerDecl: - return visitImpl(node, InitializerDeclSyntax.self, visit) + return visitImpl(&node, InitializerDeclSyntax.self, visit) case .integerLiteralExpr: - return visitImpl(node, IntegerLiteralExprSyntax.self, visit) + return visitImpl(&node, IntegerLiteralExprSyntax.self, visit) case .isExpr: - return visitImpl(node, IsExprSyntax.self, visit) + return visitImpl(&node, IsExprSyntax.self, visit) case .isTypePattern: - return visitImpl(node, IsTypePatternSyntax.self, visit) + return visitImpl(&node, IsTypePatternSyntax.self, visit) case .keyPathComponentList: - return visitImpl(node, KeyPathComponentListSyntax.self, visit) + return visitImpl(&node, KeyPathComponentListSyntax.self, visit) case .keyPathComponent: - return visitImpl(node, KeyPathComponentSyntax.self, visit) + return visitImpl(&node, KeyPathComponentSyntax.self, visit) case .keyPathExpr: - return visitImpl(node, KeyPathExprSyntax.self, visit) + return visitImpl(&node, KeyPathExprSyntax.self, visit) case .keyPathOptionalComponent: - return visitImpl(node, KeyPathOptionalComponentSyntax.self, visit) + return visitImpl(&node, KeyPathOptionalComponentSyntax.self, visit) case .keyPathPropertyComponent: - return visitImpl(node, KeyPathPropertyComponentSyntax.self, visit) + return visitImpl(&node, KeyPathPropertyComponentSyntax.self, visit) case .keyPathSubscriptComponent: - return visitImpl(node, KeyPathSubscriptComponentSyntax.self, visit) + return visitImpl(&node, KeyPathSubscriptComponentSyntax.self, visit) case .labeledExprList: - return visitImpl(node, LabeledExprListSyntax.self, visit) + return visitImpl(&node, LabeledExprListSyntax.self, visit) case .labeledExpr: - return visitImpl(node, LabeledExprSyntax.self, visit) + return visitImpl(&node, LabeledExprSyntax.self, visit) case .labeledSpecializeArgument: - return visitImpl(node, LabeledSpecializeArgumentSyntax.self, visit) + return visitImpl(&node, LabeledSpecializeArgumentSyntax.self, visit) case .labeledStmt: - return visitImpl(node, LabeledStmtSyntax.self, visit) + return visitImpl(&node, LabeledStmtSyntax.self, visit) case .layoutRequirement: - return visitImpl(node, LayoutRequirementSyntax.self, visit) + return visitImpl(&node, LayoutRequirementSyntax.self, visit) case .lifetimeSpecifierArgumentList: - return visitImpl(node, LifetimeSpecifierArgumentListSyntax.self, visit) + return visitImpl(&node, LifetimeSpecifierArgumentListSyntax.self, visit) case .lifetimeSpecifierArgument: - return visitImpl(node, LifetimeSpecifierArgumentSyntax.self, visit) - case .lifetimeSpecifierArguments: - return visitImpl(node, LifetimeSpecifierArgumentsSyntax.self, visit) + return visitImpl(&node, LifetimeSpecifierArgumentSyntax.self, visit) case .lifetimeTypeSpecifier: - return visitImpl(node, LifetimeTypeSpecifierSyntax.self, visit) + return visitImpl(&node, LifetimeTypeSpecifierSyntax.self, visit) case .macroDecl: - return visitImpl(node, MacroDeclSyntax.self, visit) + return visitImpl(&node, MacroDeclSyntax.self, visit) case .macroExpansionDecl: - return visitImpl(node, MacroExpansionDeclSyntax.self, visit) + return visitImpl(&node, MacroExpansionDeclSyntax.self, visit) case .macroExpansionExpr: - return visitImpl(node, MacroExpansionExprSyntax.self, visit) + return visitImpl(&node, MacroExpansionExprSyntax.self, visit) case .matchingPatternCondition: - return visitImpl(node, MatchingPatternConditionSyntax.self, visit) + return visitImpl(&node, MatchingPatternConditionSyntax.self, visit) case .memberAccessExpr: - return visitImpl(node, MemberAccessExprSyntax.self, visit) + return visitImpl(&node, MemberAccessExprSyntax.self, visit) case .memberBlockItemList: - return visitImpl(node, MemberBlockItemListSyntax.self, visit) + return visitImpl(&node, MemberBlockItemListSyntax.self, visit) case .memberBlockItem: - return visitImpl(node, MemberBlockItemSyntax.self, visit) + return visitImpl(&node, MemberBlockItemSyntax.self, visit) case .memberBlock: - return visitImpl(node, MemberBlockSyntax.self, visit) + return visitImpl(&node, MemberBlockSyntax.self, visit) case .memberType: - return visitImpl(node, MemberTypeSyntax.self, visit) + return visitImpl(&node, MemberTypeSyntax.self, visit) case .metatypeType: - return visitImpl(node, MetatypeTypeSyntax.self, visit) + return visitImpl(&node, MetatypeTypeSyntax.self, visit) case .missingDecl: - return visitImpl(node, MissingDeclSyntax.self, visit) + return visitImpl(&node, MissingDeclSyntax.self, visit) case .missingExpr: - return visitImpl(node, MissingExprSyntax.self, visit) + return visitImpl(&node, MissingExprSyntax.self, visit) case .missingPattern: - return visitImpl(node, MissingPatternSyntax.self, visit) + return visitImpl(&node, MissingPatternSyntax.self, visit) case .missingStmt: - return visitImpl(node, MissingStmtSyntax.self, visit) + return visitImpl(&node, MissingStmtSyntax.self, visit) case .missing: - return visitImpl(node, MissingSyntax.self, visit) + return visitImpl(&node, MissingSyntax.self, visit) case .missingType: - return visitImpl(node, MissingTypeSyntax.self, visit) + return visitImpl(&node, MissingTypeSyntax.self, visit) case .multipleTrailingClosureElementList: - return visitImpl(node, MultipleTrailingClosureElementListSyntax.self, visit) + return visitImpl(&node, MultipleTrailingClosureElementListSyntax.self, visit) case .multipleTrailingClosureElement: - return visitImpl(node, MultipleTrailingClosureElementSyntax.self, visit) + return visitImpl(&node, MultipleTrailingClosureElementSyntax.self, visit) case .namedOpaqueReturnType: - return visitImpl(node, NamedOpaqueReturnTypeSyntax.self, visit) + return visitImpl(&node, NamedOpaqueReturnTypeSyntax.self, visit) case .nilLiteralExpr: - return visitImpl(node, NilLiteralExprSyntax.self, visit) + return visitImpl(&node, NilLiteralExprSyntax.self, visit) case .objCSelectorPieceList: - return visitImpl(node, ObjCSelectorPieceListSyntax.self, visit) + return visitImpl(&node, ObjCSelectorPieceListSyntax.self, visit) case .objCSelectorPiece: - return visitImpl(node, ObjCSelectorPieceSyntax.self, visit) + return visitImpl(&node, ObjCSelectorPieceSyntax.self, visit) case .opaqueReturnTypeOfAttributeArguments: - return visitImpl(node, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, visit) case .operatorDecl: - return visitImpl(node, OperatorDeclSyntax.self, visit) + return visitImpl(&node, OperatorDeclSyntax.self, visit) case .operatorPrecedenceAndTypes: - return visitImpl(node, OperatorPrecedenceAndTypesSyntax.self, visit) + return visitImpl(&node, OperatorPrecedenceAndTypesSyntax.self, visit) case .optionalBindingCondition: - return visitImpl(node, OptionalBindingConditionSyntax.self, visit) + return visitImpl(&node, OptionalBindingConditionSyntax.self, visit) case .optionalChainingExpr: - return visitImpl(node, OptionalChainingExprSyntax.self, visit) + return visitImpl(&node, OptionalChainingExprSyntax.self, visit) case .optionalType: - return visitImpl(node, OptionalTypeSyntax.self, visit) + return visitImpl(&node, OptionalTypeSyntax.self, visit) case .originallyDefinedInAttributeArguments: - return visitImpl(node, OriginallyDefinedInAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, OriginallyDefinedInAttributeArgumentsSyntax.self, visit) case .packElementExpr: - return visitImpl(node, PackElementExprSyntax.self, visit) + return visitImpl(&node, PackElementExprSyntax.self, visit) case .packElementType: - return visitImpl(node, PackElementTypeSyntax.self, visit) + return visitImpl(&node, PackElementTypeSyntax.self, visit) case .packExpansionExpr: - return visitImpl(node, PackExpansionExprSyntax.self, visit) + return visitImpl(&node, PackExpansionExprSyntax.self, visit) case .packExpansionType: - return visitImpl(node, PackExpansionTypeSyntax.self, visit) + return visitImpl(&node, PackExpansionTypeSyntax.self, visit) case .patternBindingList: - return visitImpl(node, PatternBindingListSyntax.self, visit) + return visitImpl(&node, PatternBindingListSyntax.self, visit) case .patternBinding: - return visitImpl(node, PatternBindingSyntax.self, visit) + return visitImpl(&node, PatternBindingSyntax.self, visit) case .patternExpr: - return visitImpl(node, PatternExprSyntax.self, visit) + return visitImpl(&node, PatternExprSyntax.self, visit) case .platformVersionItemList: - return visitImpl(node, PlatformVersionItemListSyntax.self, visit) + return visitImpl(&node, PlatformVersionItemListSyntax.self, visit) case .platformVersionItem: - return visitImpl(node, PlatformVersionItemSyntax.self, visit) + return visitImpl(&node, PlatformVersionItemSyntax.self, visit) case .platformVersion: - return visitImpl(node, PlatformVersionSyntax.self, visit) + return visitImpl(&node, PlatformVersionSyntax.self, visit) case .postfixIfConfigExpr: - return visitImpl(node, PostfixIfConfigExprSyntax.self, visit) + return visitImpl(&node, PostfixIfConfigExprSyntax.self, visit) case .postfixOperatorExpr: - return visitImpl(node, PostfixOperatorExprSyntax.self, visit) + return visitImpl(&node, PostfixOperatorExprSyntax.self, visit) case .poundSourceLocationArguments: - return visitImpl(node, PoundSourceLocationArgumentsSyntax.self, visit) + return visitImpl(&node, PoundSourceLocationArgumentsSyntax.self, visit) case .poundSourceLocation: - return visitImpl(node, PoundSourceLocationSyntax.self, visit) + return visitImpl(&node, PoundSourceLocationSyntax.self, visit) case .precedenceGroupAssignment: - return visitImpl(node, PrecedenceGroupAssignmentSyntax.self, visit) + return visitImpl(&node, PrecedenceGroupAssignmentSyntax.self, visit) case .precedenceGroupAssociativity: - return visitImpl(node, PrecedenceGroupAssociativitySyntax.self, visit) + return visitImpl(&node, PrecedenceGroupAssociativitySyntax.self, visit) case .precedenceGroupAttributeList: - return visitImpl(node, PrecedenceGroupAttributeListSyntax.self, visit) + return visitImpl(&node, PrecedenceGroupAttributeListSyntax.self, visit) case .precedenceGroupDecl: - return visitImpl(node, PrecedenceGroupDeclSyntax.self, visit) + return visitImpl(&node, PrecedenceGroupDeclSyntax.self, visit) case .precedenceGroupNameList: - return visitImpl(node, PrecedenceGroupNameListSyntax.self, visit) + return visitImpl(&node, PrecedenceGroupNameListSyntax.self, visit) case .precedenceGroupName: - return visitImpl(node, PrecedenceGroupNameSyntax.self, visit) + return visitImpl(&node, PrecedenceGroupNameSyntax.self, visit) case .precedenceGroupRelation: - return visitImpl(node, PrecedenceGroupRelationSyntax.self, visit) + return visitImpl(&node, PrecedenceGroupRelationSyntax.self, visit) case .prefixOperatorExpr: - return visitImpl(node, PrefixOperatorExprSyntax.self, visit) + return visitImpl(&node, PrefixOperatorExprSyntax.self, visit) case .primaryAssociatedTypeClause: - return visitImpl(node, PrimaryAssociatedTypeClauseSyntax.self, visit) + return visitImpl(&node, PrimaryAssociatedTypeClauseSyntax.self, visit) case .primaryAssociatedTypeList: - return visitImpl(node, PrimaryAssociatedTypeListSyntax.self, visit) + return visitImpl(&node, PrimaryAssociatedTypeListSyntax.self, visit) case .primaryAssociatedType: - return visitImpl(node, PrimaryAssociatedTypeSyntax.self, visit) + return visitImpl(&node, PrimaryAssociatedTypeSyntax.self, visit) case .protocolDecl: - return visitImpl(node, ProtocolDeclSyntax.self, visit) + return visitImpl(&node, ProtocolDeclSyntax.self, visit) case .regexLiteralExpr: - return visitImpl(node, RegexLiteralExprSyntax.self, visit) + return visitImpl(&node, RegexLiteralExprSyntax.self, visit) case .repeatStmt: - return visitImpl(node, RepeatStmtSyntax.self, visit) + return visitImpl(&node, RepeatStmtSyntax.self, visit) case .returnClause: - return visitImpl(node, ReturnClauseSyntax.self, visit) + return visitImpl(&node, ReturnClauseSyntax.self, visit) case .returnStmt: - return visitImpl(node, ReturnStmtSyntax.self, visit) + return visitImpl(&node, ReturnStmtSyntax.self, visit) case .sameTypeRequirement: - return visitImpl(node, SameTypeRequirementSyntax.self, visit) + return visitImpl(&node, SameTypeRequirementSyntax.self, visit) case .sequenceExpr: - return visitImpl(node, SequenceExprSyntax.self, visit) + return visitImpl(&node, SequenceExprSyntax.self, visit) case .simpleStringLiteralExpr: - return visitImpl(node, SimpleStringLiteralExprSyntax.self, visit) + return visitImpl(&node, SimpleStringLiteralExprSyntax.self, visit) case .simpleStringLiteralSegmentList: - return visitImpl(node, SimpleStringLiteralSegmentListSyntax.self, visit) + return visitImpl(&node, SimpleStringLiteralSegmentListSyntax.self, visit) case .simpleTypeSpecifier: - return visitImpl(node, SimpleTypeSpecifierSyntax.self, visit) + return visitImpl(&node, SimpleTypeSpecifierSyntax.self, visit) case .someOrAnyType: - return visitImpl(node, SomeOrAnyTypeSyntax.self, visit) + return visitImpl(&node, SomeOrAnyTypeSyntax.self, visit) case .sourceFile: - return visitImpl(node, SourceFileSyntax.self, visit) + return visitImpl(&node, SourceFileSyntax.self, visit) case .specializeAttributeArgumentList: - return visitImpl(node, SpecializeAttributeArgumentListSyntax.self, visit) + return visitImpl(&node, SpecializeAttributeArgumentListSyntax.self, visit) case .specializeAvailabilityArgument: - return visitImpl(node, SpecializeAvailabilityArgumentSyntax.self, visit) + return visitImpl(&node, SpecializeAvailabilityArgumentSyntax.self, visit) case .specializeTargetFunctionArgument: - return visitImpl(node, SpecializeTargetFunctionArgumentSyntax.self, visit) + return visitImpl(&node, SpecializeTargetFunctionArgumentSyntax.self, visit) case .stringLiteralExpr: - return visitImpl(node, StringLiteralExprSyntax.self, visit) + return visitImpl(&node, StringLiteralExprSyntax.self, visit) case .stringLiteralSegmentList: - return visitImpl(node, StringLiteralSegmentListSyntax.self, visit) + return visitImpl(&node, StringLiteralSegmentListSyntax.self, visit) case .stringSegment: - return visitImpl(node, StringSegmentSyntax.self, visit) + return visitImpl(&node, StringSegmentSyntax.self, visit) case .structDecl: - return visitImpl(node, StructDeclSyntax.self, visit) + return visitImpl(&node, StructDeclSyntax.self, visit) case .subscriptCallExpr: - return visitImpl(node, SubscriptCallExprSyntax.self, visit) + return visitImpl(&node, SubscriptCallExprSyntax.self, visit) case .subscriptDecl: - return visitImpl(node, SubscriptDeclSyntax.self, visit) + return visitImpl(&node, SubscriptDeclSyntax.self, visit) case .superExpr: - return visitImpl(node, SuperExprSyntax.self, visit) + return visitImpl(&node, SuperExprSyntax.self, visit) case .suppressedType: - return visitImpl(node, SuppressedTypeSyntax.self, visit) + return visitImpl(&node, SuppressedTypeSyntax.self, visit) case .switchCaseItemList: - return visitImpl(node, SwitchCaseItemListSyntax.self, visit) + return visitImpl(&node, SwitchCaseItemListSyntax.self, visit) case .switchCaseItem: - return visitImpl(node, SwitchCaseItemSyntax.self, visit) + return visitImpl(&node, SwitchCaseItemSyntax.self, visit) case .switchCaseLabel: - return visitImpl(node, SwitchCaseLabelSyntax.self, visit) + return visitImpl(&node, SwitchCaseLabelSyntax.self, visit) case .switchCaseList: - return visitImpl(node, SwitchCaseListSyntax.self, visit) + return visitImpl(&node, SwitchCaseListSyntax.self, visit) case .switchCase: - return visitImpl(node, SwitchCaseSyntax.self, visit) + return visitImpl(&node, SwitchCaseSyntax.self, visit) case .switchDefaultLabel: - return visitImpl(node, SwitchDefaultLabelSyntax.self, visit) + return visitImpl(&node, SwitchDefaultLabelSyntax.self, visit) case .switchExpr: - return visitImpl(node, SwitchExprSyntax.self, visit) + return visitImpl(&node, SwitchExprSyntax.self, visit) case .ternaryExpr: - return visitImpl(node, TernaryExprSyntax.self, visit) + return visitImpl(&node, TernaryExprSyntax.self, visit) case .thenStmt: - return visitImpl(node, ThenStmtSyntax.self, visit) + return visitImpl(&node, ThenStmtSyntax.self, visit) case .throwStmt: - return visitImpl(node, ThrowStmtSyntax.self, visit) + return visitImpl(&node, ThrowStmtSyntax.self, visit) case .throwsClause: - return visitImpl(node, ThrowsClauseSyntax.self, visit) + return visitImpl(&node, ThrowsClauseSyntax.self, visit) case .tryExpr: - return visitImpl(node, TryExprSyntax.self, visit) + return visitImpl(&node, TryExprSyntax.self, visit) case .tupleExpr: - return visitImpl(node, TupleExprSyntax.self, visit) + return visitImpl(&node, TupleExprSyntax.self, visit) case .tuplePatternElementList: - return visitImpl(node, TuplePatternElementListSyntax.self, visit) + return visitImpl(&node, TuplePatternElementListSyntax.self, visit) case .tuplePatternElement: - return visitImpl(node, TuplePatternElementSyntax.self, visit) + return visitImpl(&node, TuplePatternElementSyntax.self, visit) case .tuplePattern: - return visitImpl(node, TuplePatternSyntax.self, visit) + return visitImpl(&node, TuplePatternSyntax.self, visit) case .tupleTypeElementList: - return visitImpl(node, TupleTypeElementListSyntax.self, visit) + return visitImpl(&node, TupleTypeElementListSyntax.self, visit) case .tupleTypeElement: - return visitImpl(node, TupleTypeElementSyntax.self, visit) + return visitImpl(&node, TupleTypeElementSyntax.self, visit) case .tupleType: - return visitImpl(node, TupleTypeSyntax.self, visit) + return visitImpl(&node, TupleTypeSyntax.self, visit) case .typeAliasDecl: - return visitImpl(node, TypeAliasDeclSyntax.self, visit) + return visitImpl(&node, TypeAliasDeclSyntax.self, visit) case .typeAnnotation: - return visitImpl(node, TypeAnnotationSyntax.self, visit) + return visitImpl(&node, TypeAnnotationSyntax.self, visit) case .typeEffectSpecifiers: - return visitImpl(node, TypeEffectSpecifiersSyntax.self, visit) + return visitImpl(&node, TypeEffectSpecifiersSyntax.self, visit) case .typeExpr: - return visitImpl(node, TypeExprSyntax.self, visit) + return visitImpl(&node, TypeExprSyntax.self, visit) case .typeInitializerClause: - return visitImpl(node, TypeInitializerClauseSyntax.self, visit) + return visitImpl(&node, TypeInitializerClauseSyntax.self, visit) case .typeSpecifierList: - return visitImpl(node, TypeSpecifierListSyntax.self, visit) + return visitImpl(&node, TypeSpecifierListSyntax.self, visit) case .unavailableFromAsyncAttributeArguments: - return visitImpl(node, UnavailableFromAsyncAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, UnavailableFromAsyncAttributeArgumentsSyntax.self, visit) case .underscorePrivateAttributeArguments: - return visitImpl(node, UnderscorePrivateAttributeArgumentsSyntax.self, visit) + return visitImpl(&node, UnderscorePrivateAttributeArgumentsSyntax.self, visit) case .unexpectedNodes: - return visitImpl(node, UnexpectedNodesSyntax.self, visit) + return visitImpl(&node, UnexpectedNodesSyntax.self, visit) case .unresolvedAsExpr: - return visitImpl(node, UnresolvedAsExprSyntax.self, visit) + return visitImpl(&node, UnresolvedAsExprSyntax.self, visit) case .unresolvedIsExpr: - return visitImpl(node, UnresolvedIsExprSyntax.self, visit) + return visitImpl(&node, UnresolvedIsExprSyntax.self, visit) case .unresolvedTernaryExpr: - return visitImpl(node, UnresolvedTernaryExprSyntax.self, visit) + return visitImpl(&node, UnresolvedTernaryExprSyntax.self, visit) case .valueBindingPattern: - return visitImpl(node, ValueBindingPatternSyntax.self, visit) + return visitImpl(&node, ValueBindingPatternSyntax.self, visit) case .variableDecl: - return visitImpl(node, VariableDeclSyntax.self, visit) + return visitImpl(&node, VariableDeclSyntax.self, visit) case .versionComponentList: - return visitImpl(node, VersionComponentListSyntax.self, visit) + return visitImpl(&node, VersionComponentListSyntax.self, visit) case .versionComponent: - return visitImpl(node, VersionComponentSyntax.self, visit) + return visitImpl(&node, VersionComponentSyntax.self, visit) case .versionTuple: - return visitImpl(node, VersionTupleSyntax.self, visit) + return visitImpl(&node, VersionTupleSyntax.self, visit) case .whereClause: - return visitImpl(node, WhereClauseSyntax.self, visit) + return visitImpl(&node, WhereClauseSyntax.self, visit) case .whileStmt: - return visitImpl(node, WhileStmtSyntax.self, visit) + return visitImpl(&node, WhileStmtSyntax.self, visit) case .wildcardPattern: - return visitImpl(node, WildcardPatternSyntax.self, visit) + return visitImpl(&node, WildcardPatternSyntax.self, visit) case .yieldStmt: - return visitImpl(node, YieldStmtSyntax.self, visit) + return visitImpl(&node, YieldStmtSyntax.self, visit) case .yieldedExpressionList: - return visitImpl(node, YieldedExpressionListSyntax.self, visit) + return visitImpl(&node, YieldedExpressionListSyntax.self, visit) case .yieldedExpression: - return visitImpl(node, YieldedExpressionSyntax.self, visit) + return visitImpl(&node, YieldedExpressionSyntax.self, visit) case .yieldedExpressionsClause: - return visitImpl(node, YieldedExpressionsClauseSyntax.self, visit) + return visitImpl(&node, YieldedExpressionsClauseSyntax.self, visit) } } #endif - private func visitChildren( - _ node: SyntaxType - ) -> SyntaxType { + private func visitChildren(_ node: Syntax) -> Syntax { // Walk over all children of this node and rewrite them. Don't store any // rewritten nodes until the first non-`nil` value is encountered. When this // happens, retrieve all previous syntax nodes from the parent node to @@ -3900,75 +3895,48 @@ open class SyntaxRewriter { // newLayout is nil until the first child node is rewritten and rewritten // nodes are being collected. - var newLayout: ContiguousArray? - - // Rewritten children just to keep their 'SyntaxArena' alive until they are - // wrapped with 'Syntax' - var rewrittens: ContiguousArray = [] - - let syntaxNode = node._syntaxNode + var newLayout: UnsafeMutableBufferPointer = .init(start: nil, count: 0) - // Incrementing i manually is faster than using .enumerated() - var childIndex = 0 - for (raw, info) in RawSyntaxChildren(syntaxNode) { - defer { - childIndex += 1 - } + // Keep 'SyntaxArena' of rewritten nodes alive until they are wrapped + // with 'Syntax' + var rewrittens: ContiguousArray = [] - guard let child = raw, viewMode.shouldTraverse(node: child) else { - // Node does not exist or should not be visited. If we are collecting - // rewritten nodes, we need to collect this one as well, otherwise we - // can ignore it. - if newLayout != nil { - newLayout!.append(raw) - } - continue - } + for case let (child?, info) in RawSyntaxChildren(node) where viewMode.shouldTraverse(node: child) { // Build the Syntax node to rewrite - let absoluteRaw = AbsoluteRawSyntax(raw: child, info: info) + var childNode = nodeFactory.create(parent: node, raw: child, absoluteInfo: info) - let rewritten = dispatchVisit(Syntax(absoluteRaw, parent: syntaxNode)) - if rewritten.id != info.nodeId { + dispatchVisit(&childNode) + if childNode.raw.id != child.id { // The node was rewritten, let's handle it - if newLayout == nil { - // We have not yet collected any previous rewritten nodes. Initialize - // the new layout with the previous nodes of the parent. This is - // possible, since we know they were not rewritten. - // The below implementation is based on Collection.map but directly - // reserves enough capacity for the entire layout. - newLayout = ContiguousArray() - newLayout!.reserveCapacity(node.raw.layoutView!.children.count) - for j in 0 ..< childIndex { - newLayout!.append(node.raw.layoutView!.children[j]) - } + if newLayout.baseAddress == nil { + // We have not yet collected any previous rewritten nodes. Initialize + // the new layout with the previous nodes of the parent. + newLayout = .allocate(capacity: node.raw.layoutView!.children.count) + _ = newLayout.initialize(fromContentsOf: node.raw.layoutView!.children) } - // Now that we know we have a new layout in which we collect rewritten - // nodes, add it. - rewrittens.append(rewritten) - newLayout!.append(rewritten.raw) - } else { - // The node was not changed by the rewriter. Only store it if a previous - // node has been rewritten and we are collecting a rewritten layout. - if newLayout != nil { - newLayout!.append(raw) - } + // Update the rewritten child. + newLayout[Int(info.indexInParent)] = childNode.raw + // Retain the syntax arena of the new node until it's wrapped with Syntax node. + rewrittens.append(childNode.raw.arenaReference.retained) } + + // Recycle 'childNode.info' + nodeFactory.dispose(&childNode) } - if let newLayout { + if newLayout.baseAddress != nil { // A child node was rewritten. Build the updated node. - // Sanity check, ensure the new children are the same length. - precondition(newLayout.count == node.raw.layoutView!.children.count) - let arena = SyntaxArena() - let newRaw = node.raw.layoutView!.replacingLayout(with: Array(newLayout), arena: arena) + let newRaw = node.raw.layoutView!.replacingLayout(with: newLayout, arena: arena) + newLayout.deinitialize() + newLayout.deallocate() // 'withExtendedLifetime' to keep 'SyntaxArena's of them alive until here. return withExtendedLifetime(rewrittens) { - Syntax(raw: newRaw, rawNodeArena: arena).cast(SyntaxType.self) + Syntax(raw: newRaw, rawNodeArena: arena) } } else { // No child node was rewritten. So no need to change this node as well. diff --git a/Sources/SwiftSyntax/generated/SyntaxTraits.swift b/Sources/SwiftSyntax/generated/SyntaxTraits.swift index 83c8529f9a2..c6428f14909 100644 --- a/Sources/SwiftSyntax/generated/SyntaxTraits.swift +++ b/Sources/SwiftSyntax/generated/SyntaxTraits.swift @@ -32,29 +32,29 @@ public protocol BracedSyntax: SyntaxProtocol { } } -public extension BracedSyntax { +extension BracedSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> BracedSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> BracedSyntax { var copy: BracedSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `BracedSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: BracedSyntax.Protocol) -> Bool { + public func isProtocol(_: BracedSyntax.Protocol) -> Bool { return self.asProtocol(BracedSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `BracedSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: BracedSyntax.Protocol) -> BracedSyntax? { + public func asProtocol(_: BracedSyntax.Protocol) -> BracedSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? BracedSyntax } } @@ -105,29 +105,29 @@ public protocol DeclGroupSyntax: SyntaxProtocol, DeclSyntaxProtocol { } } -public extension DeclGroupSyntax { +extension DeclGroupSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> DeclGroupSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> DeclGroupSyntax { var copy: DeclGroupSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `DeclGroupSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: DeclGroupSyntax.Protocol) -> Bool { + public func isProtocol(_: DeclGroupSyntax.Protocol) -> Bool { return self.asProtocol(DeclGroupSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `DeclGroupSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: DeclGroupSyntax.Protocol) -> DeclGroupSyntax? { + public func asProtocol(_: DeclGroupSyntax.Protocol) -> DeclGroupSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? DeclGroupSyntax } } @@ -166,29 +166,29 @@ public protocol EffectSpecifiersSyntax: SyntaxProtocol { } } -public extension EffectSpecifiersSyntax { +extension EffectSpecifiersSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> EffectSpecifiersSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> EffectSpecifiersSyntax { var copy: EffectSpecifiersSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `EffectSpecifiersSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: EffectSpecifiersSyntax.Protocol) -> Bool { + public func isProtocol(_: EffectSpecifiersSyntax.Protocol) -> Bool { return self.asProtocol(EffectSpecifiersSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `EffectSpecifiersSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: EffectSpecifiersSyntax.Protocol) -> EffectSpecifiersSyntax? { + public func asProtocol(_: EffectSpecifiersSyntax.Protocol) -> EffectSpecifiersSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? EffectSpecifiersSyntax } } @@ -249,29 +249,29 @@ public protocol FreestandingMacroExpansionSyntax: SyntaxProtocol { } } -public extension FreestandingMacroExpansionSyntax { +extension FreestandingMacroExpansionSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> FreestandingMacroExpansionSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> FreestandingMacroExpansionSyntax { var copy: FreestandingMacroExpansionSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `FreestandingMacroExpansionSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: FreestandingMacroExpansionSyntax.Protocol) -> Bool { + public func isProtocol(_: FreestandingMacroExpansionSyntax.Protocol) -> Bool { return self.asProtocol(FreestandingMacroExpansionSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `FreestandingMacroExpansionSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: FreestandingMacroExpansionSyntax.Protocol) -> FreestandingMacroExpansionSyntax? { + public func asProtocol(_: FreestandingMacroExpansionSyntax.Protocol) -> FreestandingMacroExpansionSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? FreestandingMacroExpansionSyntax } } @@ -288,29 +288,29 @@ public protocol NamedDeclSyntax: SyntaxProtocol { } } -public extension NamedDeclSyntax { +extension NamedDeclSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> NamedDeclSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> NamedDeclSyntax { var copy: NamedDeclSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `NamedDeclSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: NamedDeclSyntax.Protocol) -> Bool { + public func isProtocol(_: NamedDeclSyntax.Protocol) -> Bool { return self.asProtocol(NamedDeclSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `NamedDeclSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: NamedDeclSyntax.Protocol) -> NamedDeclSyntax? { + public func asProtocol(_: NamedDeclSyntax.Protocol) -> NamedDeclSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? NamedDeclSyntax } } @@ -332,29 +332,29 @@ public protocol MissingNodeSyntax: SyntaxProtocol { } } -public extension MissingNodeSyntax { +extension MissingNodeSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> MissingNodeSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> MissingNodeSyntax { var copy: MissingNodeSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `MissingNodeSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: MissingNodeSyntax.Protocol) -> Bool { + public func isProtocol(_: MissingNodeSyntax.Protocol) -> Bool { return self.asProtocol(MissingNodeSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `MissingNodeSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: MissingNodeSyntax.Protocol) -> MissingNodeSyntax? { + public func asProtocol(_: MissingNodeSyntax.Protocol) -> MissingNodeSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? MissingNodeSyntax } } @@ -379,29 +379,29 @@ public protocol ParenthesizedSyntax: SyntaxProtocol { } } -public extension ParenthesizedSyntax { +extension ParenthesizedSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> ParenthesizedSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> ParenthesizedSyntax { var copy: ParenthesizedSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `ParenthesizedSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: ParenthesizedSyntax.Protocol) -> Bool { + public func isProtocol(_: ParenthesizedSyntax.Protocol) -> Bool { return self.asProtocol(ParenthesizedSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `ParenthesizedSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: ParenthesizedSyntax.Protocol) -> ParenthesizedSyntax? { + public func asProtocol(_: ParenthesizedSyntax.Protocol) -> ParenthesizedSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? ParenthesizedSyntax } } @@ -415,29 +415,29 @@ public protocol WithAttributesSyntax: SyntaxProtocol { } } -public extension WithAttributesSyntax { +extension WithAttributesSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithAttributesSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithAttributesSyntax { var copy: WithAttributesSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithAttributesSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithAttributesSyntax.Protocol) -> Bool { + public func isProtocol(_: WithAttributesSyntax.Protocol) -> Bool { return self.asProtocol(WithAttributesSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithAttributesSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithAttributesSyntax.Protocol) -> WithAttributesSyntax? { + public func asProtocol(_: WithAttributesSyntax.Protocol) -> WithAttributesSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithAttributesSyntax } } @@ -451,29 +451,29 @@ public protocol WithCodeBlockSyntax: SyntaxProtocol { } } -public extension WithCodeBlockSyntax { +extension WithCodeBlockSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithCodeBlockSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithCodeBlockSyntax { var copy: WithCodeBlockSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithCodeBlockSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithCodeBlockSyntax.Protocol) -> Bool { + public func isProtocol(_: WithCodeBlockSyntax.Protocol) -> Bool { return self.asProtocol(WithCodeBlockSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithCodeBlockSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithCodeBlockSyntax.Protocol) -> WithCodeBlockSyntax? { + public func asProtocol(_: WithCodeBlockSyntax.Protocol) -> WithCodeBlockSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithCodeBlockSyntax } } @@ -497,29 +497,29 @@ public protocol WithGenericParametersSyntax: SyntaxProtocol { } } -public extension WithGenericParametersSyntax { +extension WithGenericParametersSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithGenericParametersSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithGenericParametersSyntax { var copy: WithGenericParametersSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithGenericParametersSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithGenericParametersSyntax.Protocol) -> Bool { + public func isProtocol(_: WithGenericParametersSyntax.Protocol) -> Bool { return self.asProtocol(WithGenericParametersSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithGenericParametersSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithGenericParametersSyntax.Protocol) -> WithGenericParametersSyntax? { + public func asProtocol(_: WithGenericParametersSyntax.Protocol) -> WithGenericParametersSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithGenericParametersSyntax } } @@ -533,29 +533,29 @@ public protocol WithModifiersSyntax: SyntaxProtocol { } } -public extension WithModifiersSyntax { +extension WithModifiersSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithModifiersSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithModifiersSyntax { var copy: WithModifiersSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithModifiersSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithModifiersSyntax.Protocol) -> Bool { + public func isProtocol(_: WithModifiersSyntax.Protocol) -> Bool { return self.asProtocol(WithModifiersSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithModifiersSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithModifiersSyntax.Protocol) -> WithModifiersSyntax? { + public func asProtocol(_: WithModifiersSyntax.Protocol) -> WithModifiersSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithModifiersSyntax } } @@ -569,29 +569,29 @@ public protocol WithOptionalCodeBlockSyntax: SyntaxProtocol { } } -public extension WithOptionalCodeBlockSyntax { +extension WithOptionalCodeBlockSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithOptionalCodeBlockSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithOptionalCodeBlockSyntax { var copy: WithOptionalCodeBlockSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithOptionalCodeBlockSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithOptionalCodeBlockSyntax.Protocol) -> Bool { + public func isProtocol(_: WithOptionalCodeBlockSyntax.Protocol) -> Bool { return self.asProtocol(WithOptionalCodeBlockSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithOptionalCodeBlockSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithOptionalCodeBlockSyntax.Protocol) -> WithOptionalCodeBlockSyntax? { + public func asProtocol(_: WithOptionalCodeBlockSyntax.Protocol) -> WithOptionalCodeBlockSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithOptionalCodeBlockSyntax } } @@ -605,29 +605,29 @@ public protocol WithStatementsSyntax: SyntaxProtocol { } } -public extension WithStatementsSyntax { +extension WithStatementsSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithStatementsSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithStatementsSyntax { var copy: WithStatementsSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithStatementsSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithStatementsSyntax.Protocol) -> Bool { + public func isProtocol(_: WithStatementsSyntax.Protocol) -> Bool { return self.asProtocol(WithStatementsSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithStatementsSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithStatementsSyntax.Protocol) -> WithStatementsSyntax? { + public func asProtocol(_: WithStatementsSyntax.Protocol) -> WithStatementsSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithStatementsSyntax } } @@ -644,29 +644,29 @@ public protocol WithTrailingCommaSyntax: SyntaxProtocol { } } -public extension WithTrailingCommaSyntax { +extension WithTrailingCommaSyntax { /// Without this function, the `with` function defined on `SyntaxProtocol` /// does not work on existentials of this protocol type. @_disfavoredOverload - func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithTrailingCommaSyntax { + public func with(_ keyPath: WritableKeyPath, _ newChild: T) -> WithTrailingCommaSyntax { var copy: WithTrailingCommaSyntax = self copy[keyPath: keyPath] = newChild return copy } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Check whether the non-type erased version of this syntax node conforms to /// `WithTrailingCommaSyntax`. /// Note that this will incur an existential conversion. - func isProtocol(_: WithTrailingCommaSyntax.Protocol) -> Bool { + public func isProtocol(_: WithTrailingCommaSyntax.Protocol) -> Bool { return self.asProtocol(WithTrailingCommaSyntax.self) != nil } /// Return the non-type erased version of this syntax node if it conforms to /// `WithTrailingCommaSyntax`. Otherwise return `nil`. /// Note that this will incur an existential conversion. - func asProtocol(_: WithTrailingCommaSyntax.Protocol) -> WithTrailingCommaSyntax? { + public func asProtocol(_: WithTrailingCommaSyntax.Protocol) -> WithTrailingCommaSyntax? { return Syntax(self).asProtocol(SyntaxProtocol.self) as? WithTrailingCommaSyntax } } @@ -779,8 +779,6 @@ extension LabeledSpecializeArgumentSyntax: WithTrailingCommaSyntax {} extension LifetimeSpecifierArgumentSyntax: WithTrailingCommaSyntax {} -extension LifetimeSpecifierArgumentsSyntax: ParenthesizedSyntax {} - extension MacroDeclSyntax: NamedDeclSyntax, WithAttributesSyntax, WithGenericParametersSyntax, WithModifiersSyntax {} extension MacroExpansionDeclSyntax: FreestandingMacroExpansionSyntax, WithAttributesSyntax, WithModifiersSyntax {} diff --git a/Sources/SwiftSyntax/generated/SyntaxVisitor.swift b/Sources/SwiftSyntax/generated/SyntaxVisitor.swift index 3b40df48540..33641e9dc6a 100644 --- a/Sources/SwiftSyntax/generated/SyntaxVisitor.swift +++ b/Sources/SwiftSyntax/generated/SyntaxVisitor.swift @@ -24,6 +24,9 @@ public enum SyntaxVisitorContinueKind { open class SyntaxVisitor { public let viewMode: SyntaxTreeViewMode + /// 'Syntax' object factory recycling 'Syntax.Info' instances. + private let nodeFactory: SyntaxNodeFactory = SyntaxNodeFactory() + public init(viewMode: SyntaxTreeViewMode) { self.viewMode = viewMode } @@ -31,7 +34,8 @@ open class SyntaxVisitor { /// Walk all nodes of the given syntax tree, calling the corresponding `visit` /// function for every node that is being visited. public func walk(_ node: some SyntaxProtocol) { - visit(Syntax(node)) + var syntaxNode = Syntax(node) + visit(&syntaxNode) } /// Visiting ``AccessorBlockSyntax`` specifically. @@ -358,28 +362,28 @@ open class SyntaxVisitor { open func visitPost(_ node: BreakStmtSyntax) { } - /// Visiting ``CanImportExprSyntax`` specifically. + /// Visiting `_CanImportExprSyntax` specifically. /// - Parameter node: the node we are visiting. /// - Returns: how should we continue visiting. - open func visit(_ node: CanImportExprSyntax) -> SyntaxVisitorContinueKind { + open func visit(_ node: _CanImportExprSyntax) -> SyntaxVisitorContinueKind { return .visitChildren } - /// The function called after visiting ``CanImportExprSyntax`` and its descendants. + /// The function called after visiting `_CanImportExprSyntax` and its descendants. /// - node: the node we just finished visiting. - open func visitPost(_ node: CanImportExprSyntax) { + open func visitPost(_ node: _CanImportExprSyntax) { } - /// Visiting ``CanImportVersionInfoSyntax`` specifically. + /// Visiting `_CanImportVersionInfoSyntax` specifically. /// - Parameter node: the node we are visiting. /// - Returns: how should we continue visiting. - open func visit(_ node: CanImportVersionInfoSyntax) -> SyntaxVisitorContinueKind { + open func visit(_ node: _CanImportVersionInfoSyntax) -> SyntaxVisitorContinueKind { return .visitChildren } - /// The function called after visiting ``CanImportVersionInfoSyntax`` and its descendants. + /// The function called after visiting `_CanImportVersionInfoSyntax` and its descendants. /// - node: the node we just finished visiting. - open func visitPost(_ node: CanImportVersionInfoSyntax) { + open func visitPost(_ node: _CanImportVersionInfoSyntax) { } /// Visiting ``CatchClauseListSyntax`` specifically. @@ -1996,24 +2000,6 @@ open class SyntaxVisitor { open func visitPost(_ node: LifetimeSpecifierArgumentSyntax) { } - /// Visiting `LifetimeSpecifierArgumentsSyntax` specifically. - /// - Parameter node: the node we are visiting. - /// - Returns: how should we continue visiting. - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif - open func visit(_ node: LifetimeSpecifierArgumentsSyntax) -> SyntaxVisitorContinueKind { - return .visitChildren - } - - /// The function called after visiting `LifetimeSpecifierArgumentsSyntax` and its descendants. - /// - node: the node we just finished visiting. - #if compiler(>=5.8) - @_spi(ExperimentalLanguageFeatures) - #endif - open func visitPost(_ node: LifetimeSpecifierArgumentsSyntax) { - } - /// Visiting `LifetimeTypeSpecifierSyntax` specifically. /// - Parameter node: the node we are visiting. /// - Returns: how should we continue visiting. @@ -3490,21 +3476,30 @@ open class SyntaxVisitor { open func visitPost(_ node: TokenSyntax) { } - /// Interpret `data` as a node of type `nodeType`, visit it, calling + /// Cast `node` to a node of type `nodeType`, visit it, calling /// the `visit` and `visitPost` functions during visitation. + /// + /// - Note: node is an `inout` parameter so that callers don't have to retain it before passing it to `visitImpl`. + /// With it being an `inout` parameter, the caller and `visitImpl` can work on the same reference of `node` without + /// any reference counting. + /// - Note: Inline so that the optimizer can look through the calles to `visit` and `visitPost`, which means it + /// doesn't need to retain `self` when forming closures to the unapplied function references on `self`. + @inline(__always) private func visitImpl( - _ node: Syntax, + _ node: inout Syntax, _ nodeType: NodeType.Type, _ visit: (NodeType) -> SyntaxVisitorContinueKind, _ visitPost: (NodeType) -> Void ) { - let node = node.cast(NodeType.self) - let needsChildren = (visit(node) == .visitChildren) + let castedNode = node.cast(NodeType.self) + // We retain castedNode.info here before passing it to visit. + // I don't think that's necessary because castedNode is already retained but don't know how to prevent it. + let needsChildren = (visit(castedNode) == .visitChildren) // Avoid calling into visitChildren if possible. if needsChildren && !node.raw.layoutView!.children.isEmpty { - visitChildren(node) + visitChildren(&node) } - visitPost(node) + visitPost(castedNode) } // SwiftSyntax requires a lot of stack space in debug builds for syntax tree @@ -3531,7 +3526,7 @@ open class SyntaxVisitor { /// that determines the correct visitation function will be popped of the /// stack before the function is being called, making the switch's stack /// space transient instead of having it linger in the call stack. - private func visitationFunc(for node: Syntax) -> ((Syntax) -> Void) { + private func visitationFunc(for node: Syntax) -> ((inout Syntax) -> Void) { switch node.raw.kind { case .token: return { @@ -3542,1147 +3537,1144 @@ open class SyntaxVisitor { } case .accessorBlock: return { - self.visitImpl($0, AccessorBlockSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AccessorBlockSyntax.self, self.visit, self.visitPost) } case .accessorDeclList: return { - self.visitImpl($0, AccessorDeclListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AccessorDeclListSyntax.self, self.visit, self.visitPost) } case .accessorDecl: return { - self.visitImpl($0, AccessorDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AccessorDeclSyntax.self, self.visit, self.visitPost) } case .accessorEffectSpecifiers: return { - self.visitImpl($0, AccessorEffectSpecifiersSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AccessorEffectSpecifiersSyntax.self, self.visit, self.visitPost) } case .accessorParameters: return { - self.visitImpl($0, AccessorParametersSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AccessorParametersSyntax.self, self.visit, self.visitPost) } case .actorDecl: return { - self.visitImpl($0, ActorDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ActorDeclSyntax.self, self.visit, self.visitPost) } case .arrayElementList: return { - self.visitImpl($0, ArrayElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ArrayElementListSyntax.self, self.visit, self.visitPost) } case .arrayElement: return { - self.visitImpl($0, ArrayElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ArrayElementSyntax.self, self.visit, self.visitPost) } case .arrayExpr: return { - self.visitImpl($0, ArrayExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ArrayExprSyntax.self, self.visit, self.visitPost) } case .arrayType: return { - self.visitImpl($0, ArrayTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ArrayTypeSyntax.self, self.visit, self.visitPost) } case .arrowExpr: return { - self.visitImpl($0, ArrowExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ArrowExprSyntax.self, self.visit, self.visitPost) } case .asExpr: return { - self.visitImpl($0, AsExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AsExprSyntax.self, self.visit, self.visitPost) } case .assignmentExpr: return { - self.visitImpl($0, AssignmentExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AssignmentExprSyntax.self, self.visit, self.visitPost) } case .associatedTypeDecl: return { - self.visitImpl($0, AssociatedTypeDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AssociatedTypeDeclSyntax.self, self.visit, self.visitPost) } case .attributeList: return { - self.visitImpl($0, AttributeListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AttributeListSyntax.self, self.visit, self.visitPost) } case .attribute: return { - self.visitImpl($0, AttributeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AttributeSyntax.self, self.visit, self.visitPost) } case .attributedType: return { - self.visitImpl($0, AttributedTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AttributedTypeSyntax.self, self.visit, self.visitPost) } case .availabilityArgumentList: return { - self.visitImpl($0, AvailabilityArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AvailabilityArgumentListSyntax.self, self.visit, self.visitPost) } case .availabilityArgument: return { - self.visitImpl($0, AvailabilityArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AvailabilityArgumentSyntax.self, self.visit, self.visitPost) } case .availabilityCondition: return { - self.visitImpl($0, AvailabilityConditionSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AvailabilityConditionSyntax.self, self.visit, self.visitPost) } case .availabilityLabeledArgument: return { - self.visitImpl($0, AvailabilityLabeledArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AvailabilityLabeledArgumentSyntax.self, self.visit, self.visitPost) } case .awaitExpr: return { - self.visitImpl($0, AwaitExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, AwaitExprSyntax.self, self.visit, self.visitPost) } case .backDeployedAttributeArguments: return { - self.visitImpl($0, BackDeployedAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, BackDeployedAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .binaryOperatorExpr: return { - self.visitImpl($0, BinaryOperatorExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, BinaryOperatorExprSyntax.self, self.visit, self.visitPost) } case .booleanLiteralExpr: return { - self.visitImpl($0, BooleanLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, BooleanLiteralExprSyntax.self, self.visit, self.visitPost) } case .borrowExpr: return { - self.visitImpl($0, BorrowExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, BorrowExprSyntax.self, self.visit, self.visitPost) } case .breakStmt: return { - self.visitImpl($0, BreakStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, BreakStmtSyntax.self, self.visit, self.visitPost) } - case .canImportExpr: + case ._canImportExpr: return { - self.visitImpl($0, CanImportExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, _CanImportExprSyntax.self, self.visit, self.visitPost) } - case .canImportVersionInfo: + case ._canImportVersionInfo: return { - self.visitImpl($0, CanImportVersionInfoSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, _CanImportVersionInfoSyntax.self, self.visit, self.visitPost) } case .catchClauseList: return { - self.visitImpl($0, CatchClauseListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CatchClauseListSyntax.self, self.visit, self.visitPost) } case .catchClause: return { - self.visitImpl($0, CatchClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CatchClauseSyntax.self, self.visit, self.visitPost) } case .catchItemList: return { - self.visitImpl($0, CatchItemListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CatchItemListSyntax.self, self.visit, self.visitPost) } case .catchItem: return { - self.visitImpl($0, CatchItemSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CatchItemSyntax.self, self.visit, self.visitPost) } case .classDecl: return { - self.visitImpl($0, ClassDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClassDeclSyntax.self, self.visit, self.visitPost) } case .classRestrictionType: return { - self.visitImpl($0, ClassRestrictionTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClassRestrictionTypeSyntax.self, self.visit, self.visitPost) } case .closureCaptureClause: return { - self.visitImpl($0, ClosureCaptureClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureCaptureClauseSyntax.self, self.visit, self.visitPost) } case .closureCaptureList: return { - self.visitImpl($0, ClosureCaptureListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureCaptureListSyntax.self, self.visit, self.visitPost) } case .closureCaptureSpecifier: return { - self.visitImpl($0, ClosureCaptureSpecifierSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureCaptureSpecifierSyntax.self, self.visit, self.visitPost) } case .closureCapture: return { - self.visitImpl($0, ClosureCaptureSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureCaptureSyntax.self, self.visit, self.visitPost) } case .closureExpr: return { - self.visitImpl($0, ClosureExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureExprSyntax.self, self.visit, self.visitPost) } case .closureParameterClause: return { - self.visitImpl($0, ClosureParameterClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureParameterClauseSyntax.self, self.visit, self.visitPost) } case .closureParameterList: return { - self.visitImpl($0, ClosureParameterListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureParameterListSyntax.self, self.visit, self.visitPost) } case .closureParameter: return { - self.visitImpl($0, ClosureParameterSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureParameterSyntax.self, self.visit, self.visitPost) } case .closureShorthandParameterList: return { - self.visitImpl($0, ClosureShorthandParameterListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureShorthandParameterListSyntax.self, self.visit, self.visitPost) } case .closureShorthandParameter: return { - self.visitImpl($0, ClosureShorthandParameterSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureShorthandParameterSyntax.self, self.visit, self.visitPost) } case .closureSignature: return { - self.visitImpl($0, ClosureSignatureSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ClosureSignatureSyntax.self, self.visit, self.visitPost) } case .codeBlockItemList: return { - self.visitImpl($0, CodeBlockItemListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CodeBlockItemListSyntax.self, self.visit, self.visitPost) } case .codeBlockItem: return { - self.visitImpl($0, CodeBlockItemSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CodeBlockItemSyntax.self, self.visit, self.visitPost) } case .codeBlock: return { - self.visitImpl($0, CodeBlockSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CodeBlockSyntax.self, self.visit, self.visitPost) } case .compositionTypeElementList: return { - self.visitImpl($0, CompositionTypeElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CompositionTypeElementListSyntax.self, self.visit, self.visitPost) } case .compositionTypeElement: return { - self.visitImpl($0, CompositionTypeElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CompositionTypeElementSyntax.self, self.visit, self.visitPost) } case .compositionType: return { - self.visitImpl($0, CompositionTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CompositionTypeSyntax.self, self.visit, self.visitPost) } case .conditionElementList: return { - self.visitImpl($0, ConditionElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ConditionElementListSyntax.self, self.visit, self.visitPost) } case .conditionElement: return { - self.visitImpl($0, ConditionElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ConditionElementSyntax.self, self.visit, self.visitPost) } case .conformanceRequirement: return { - self.visitImpl($0, ConformanceRequirementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ConformanceRequirementSyntax.self, self.visit, self.visitPost) } case .consumeExpr: return { - self.visitImpl($0, ConsumeExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ConsumeExprSyntax.self, self.visit, self.visitPost) } case .continueStmt: return { - self.visitImpl($0, ContinueStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ContinueStmtSyntax.self, self.visit, self.visitPost) } case .conventionAttributeArguments: return { - self.visitImpl($0, ConventionAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ConventionAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .conventionWitnessMethodAttributeArguments: return { - self.visitImpl($0, ConventionWitnessMethodAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ConventionWitnessMethodAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .copyExpr: return { - self.visitImpl($0, CopyExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, CopyExprSyntax.self, self.visit, self.visitPost) } case .declModifierDetail: return { - self.visitImpl($0, DeclModifierDetailSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclModifierDetailSyntax.self, self.visit, self.visitPost) } case .declModifierList: return { - self.visitImpl($0, DeclModifierListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclModifierListSyntax.self, self.visit, self.visitPost) } case .declModifier: return { - self.visitImpl($0, DeclModifierSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclModifierSyntax.self, self.visit, self.visitPost) } case .declNameArgumentList: return { - self.visitImpl($0, DeclNameArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclNameArgumentListSyntax.self, self.visit, self.visitPost) } case .declNameArgument: return { - self.visitImpl($0, DeclNameArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclNameArgumentSyntax.self, self.visit, self.visitPost) } case .declNameArguments: return { - self.visitImpl($0, DeclNameArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclNameArgumentsSyntax.self, self.visit, self.visitPost) } case .declReferenceExpr: return { - self.visitImpl($0, DeclReferenceExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeclReferenceExprSyntax.self, self.visit, self.visitPost) } case .deferStmt: return { - self.visitImpl($0, DeferStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeferStmtSyntax.self, self.visit, self.visitPost) } case .deinitializerDecl: return { - self.visitImpl($0, DeinitializerDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeinitializerDeclSyntax.self, self.visit, self.visitPost) } case .deinitializerEffectSpecifiers: return { - self.visitImpl($0, DeinitializerEffectSpecifiersSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DeinitializerEffectSpecifiersSyntax.self, self.visit, self.visitPost) } case .derivativeAttributeArguments: return { - self.visitImpl($0, DerivativeAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DerivativeAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .designatedTypeList: return { - self.visitImpl($0, DesignatedTypeListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DesignatedTypeListSyntax.self, self.visit, self.visitPost) } case .designatedType: return { - self.visitImpl($0, DesignatedTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DesignatedTypeSyntax.self, self.visit, self.visitPost) } case .dictionaryElementList: return { - self.visitImpl($0, DictionaryElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DictionaryElementListSyntax.self, self.visit, self.visitPost) } case .dictionaryElement: return { - self.visitImpl($0, DictionaryElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DictionaryElementSyntax.self, self.visit, self.visitPost) } case .dictionaryExpr: return { - self.visitImpl($0, DictionaryExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DictionaryExprSyntax.self, self.visit, self.visitPost) } case .dictionaryType: return { - self.visitImpl($0, DictionaryTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DictionaryTypeSyntax.self, self.visit, self.visitPost) } case .differentiabilityArgumentList: return { - self.visitImpl($0, DifferentiabilityArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DifferentiabilityArgumentListSyntax.self, self.visit, self.visitPost) } case .differentiabilityArgument: return { - self.visitImpl($0, DifferentiabilityArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DifferentiabilityArgumentSyntax.self, self.visit, self.visitPost) } case .differentiabilityArguments: return { - self.visitImpl($0, DifferentiabilityArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DifferentiabilityArgumentsSyntax.self, self.visit, self.visitPost) } case .differentiabilityWithRespectToArgument: return { - self.visitImpl($0, DifferentiabilityWithRespectToArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DifferentiabilityWithRespectToArgumentSyntax.self, self.visit, self.visitPost) } case .differentiableAttributeArguments: return { - self.visitImpl($0, DifferentiableAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DifferentiableAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .discardAssignmentExpr: return { - self.visitImpl($0, DiscardAssignmentExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DiscardAssignmentExprSyntax.self, self.visit, self.visitPost) } case .discardStmt: return { - self.visitImpl($0, DiscardStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DiscardStmtSyntax.self, self.visit, self.visitPost) } case .doExpr: return { - self.visitImpl($0, DoExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DoExprSyntax.self, self.visit, self.visitPost) } case .doStmt: return { - self.visitImpl($0, DoStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DoStmtSyntax.self, self.visit, self.visitPost) } case .documentationAttributeArgumentList: return { - self.visitImpl($0, DocumentationAttributeArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DocumentationAttributeArgumentListSyntax.self, self.visit, self.visitPost) } case .documentationAttributeArgument: return { - self.visitImpl($0, DocumentationAttributeArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DocumentationAttributeArgumentSyntax.self, self.visit, self.visitPost) } case .dynamicReplacementAttributeArguments: return { - self.visitImpl($0, DynamicReplacementAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, DynamicReplacementAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .editorPlaceholderDecl: return { - self.visitImpl($0, EditorPlaceholderDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EditorPlaceholderDeclSyntax.self, self.visit, self.visitPost) } case .editorPlaceholderExpr: return { - self.visitImpl($0, EditorPlaceholderExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EditorPlaceholderExprSyntax.self, self.visit, self.visitPost) } case .effectsAttributeArgumentList: return { - self.visitImpl($0, EffectsAttributeArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EffectsAttributeArgumentListSyntax.self, self.visit, self.visitPost) } case .enumCaseDecl: return { - self.visitImpl($0, EnumCaseDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumCaseDeclSyntax.self, self.visit, self.visitPost) } case .enumCaseElementList: return { - self.visitImpl($0, EnumCaseElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumCaseElementListSyntax.self, self.visit, self.visitPost) } case .enumCaseElement: return { - self.visitImpl($0, EnumCaseElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumCaseElementSyntax.self, self.visit, self.visitPost) } case .enumCaseParameterClause: return { - self.visitImpl($0, EnumCaseParameterClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumCaseParameterClauseSyntax.self, self.visit, self.visitPost) } case .enumCaseParameterList: return { - self.visitImpl($0, EnumCaseParameterListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumCaseParameterListSyntax.self, self.visit, self.visitPost) } case .enumCaseParameter: return { - self.visitImpl($0, EnumCaseParameterSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumCaseParameterSyntax.self, self.visit, self.visitPost) } case .enumDecl: return { - self.visitImpl($0, EnumDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, EnumDeclSyntax.self, self.visit, self.visitPost) } case .exposeAttributeArguments: return { - self.visitImpl($0, ExposeAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ExposeAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .exprList: return { - self.visitImpl($0, ExprListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ExprListSyntax.self, self.visit, self.visitPost) } case .expressionPattern: return { - self.visitImpl($0, ExpressionPatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ExpressionPatternSyntax.self, self.visit, self.visitPost) } case .expressionSegment: return { - self.visitImpl($0, ExpressionSegmentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ExpressionSegmentSyntax.self, self.visit, self.visitPost) } case .expressionStmt: return { - self.visitImpl($0, ExpressionStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ExpressionStmtSyntax.self, self.visit, self.visitPost) } case .extensionDecl: return { - self.visitImpl($0, ExtensionDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ExtensionDeclSyntax.self, self.visit, self.visitPost) } case .fallThroughStmt: return { - self.visitImpl($0, FallThroughStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FallThroughStmtSyntax.self, self.visit, self.visitPost) } case .floatLiteralExpr: return { - self.visitImpl($0, FloatLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FloatLiteralExprSyntax.self, self.visit, self.visitPost) } case .forStmt: return { - self.visitImpl($0, ForStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ForStmtSyntax.self, self.visit, self.visitPost) } case .forceUnwrapExpr: return { - self.visitImpl($0, ForceUnwrapExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ForceUnwrapExprSyntax.self, self.visit, self.visitPost) } case .functionCallExpr: return { - self.visitImpl($0, FunctionCallExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionCallExprSyntax.self, self.visit, self.visitPost) } case .functionDecl: return { - self.visitImpl($0, FunctionDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionDeclSyntax.self, self.visit, self.visitPost) } case .functionEffectSpecifiers: return { - self.visitImpl($0, FunctionEffectSpecifiersSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionEffectSpecifiersSyntax.self, self.visit, self.visitPost) } case .functionParameterClause: return { - self.visitImpl($0, FunctionParameterClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionParameterClauseSyntax.self, self.visit, self.visitPost) } case .functionParameterList: return { - self.visitImpl($0, FunctionParameterListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionParameterListSyntax.self, self.visit, self.visitPost) } case .functionParameter: return { - self.visitImpl($0, FunctionParameterSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionParameterSyntax.self, self.visit, self.visitPost) } case .functionSignature: return { - self.visitImpl($0, FunctionSignatureSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionSignatureSyntax.self, self.visit, self.visitPost) } case .functionType: return { - self.visitImpl($0, FunctionTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, FunctionTypeSyntax.self, self.visit, self.visitPost) } case .genericArgumentClause: return { - self.visitImpl($0, GenericArgumentClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericArgumentClauseSyntax.self, self.visit, self.visitPost) } case .genericArgumentList: return { - self.visitImpl($0, GenericArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericArgumentListSyntax.self, self.visit, self.visitPost) } case .genericArgument: return { - self.visitImpl($0, GenericArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericArgumentSyntax.self, self.visit, self.visitPost) } case .genericParameterClause: return { - self.visitImpl($0, GenericParameterClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericParameterClauseSyntax.self, self.visit, self.visitPost) } case .genericParameterList: return { - self.visitImpl($0, GenericParameterListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericParameterListSyntax.self, self.visit, self.visitPost) } case .genericParameter: return { - self.visitImpl($0, GenericParameterSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericParameterSyntax.self, self.visit, self.visitPost) } case .genericRequirementList: return { - self.visitImpl($0, GenericRequirementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericRequirementListSyntax.self, self.visit, self.visitPost) } case .genericRequirement: return { - self.visitImpl($0, GenericRequirementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericRequirementSyntax.self, self.visit, self.visitPost) } case .genericSpecializationExpr: return { - self.visitImpl($0, GenericSpecializationExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericSpecializationExprSyntax.self, self.visit, self.visitPost) } case .genericWhereClause: return { - self.visitImpl($0, GenericWhereClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GenericWhereClauseSyntax.self, self.visit, self.visitPost) } case .guardStmt: return { - self.visitImpl($0, GuardStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, GuardStmtSyntax.self, self.visit, self.visitPost) } case .identifierPattern: return { - self.visitImpl($0, IdentifierPatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IdentifierPatternSyntax.self, self.visit, self.visitPost) } case .identifierType: return { - self.visitImpl($0, IdentifierTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IdentifierTypeSyntax.self, self.visit, self.visitPost) } case .ifConfigClauseList: return { - self.visitImpl($0, IfConfigClauseListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IfConfigClauseListSyntax.self, self.visit, self.visitPost) } case .ifConfigClause: return { - self.visitImpl($0, IfConfigClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IfConfigClauseSyntax.self, self.visit, self.visitPost) } case .ifConfigDecl: return { - self.visitImpl($0, IfConfigDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IfConfigDeclSyntax.self, self.visit, self.visitPost) } case .ifExpr: return { - self.visitImpl($0, IfExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IfExprSyntax.self, self.visit, self.visitPost) } case .implementsAttributeArguments: return { - self.visitImpl($0, ImplementsAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ImplementsAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .implicitlyUnwrappedOptionalType: return { - self.visitImpl($0, ImplicitlyUnwrappedOptionalTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ImplicitlyUnwrappedOptionalTypeSyntax.self, self.visit, self.visitPost) } case .importDecl: return { - self.visitImpl($0, ImportDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ImportDeclSyntax.self, self.visit, self.visitPost) } case .importPathComponentList: return { - self.visitImpl($0, ImportPathComponentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ImportPathComponentListSyntax.self, self.visit, self.visitPost) } case .importPathComponent: return { - self.visitImpl($0, ImportPathComponentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ImportPathComponentSyntax.self, self.visit, self.visitPost) } case .inOutExpr: return { - self.visitImpl($0, InOutExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InOutExprSyntax.self, self.visit, self.visitPost) } case .infixOperatorExpr: return { - self.visitImpl($0, InfixOperatorExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InfixOperatorExprSyntax.self, self.visit, self.visitPost) } case .inheritanceClause: return { - self.visitImpl($0, InheritanceClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InheritanceClauseSyntax.self, self.visit, self.visitPost) } case .inheritedTypeList: return { - self.visitImpl($0, InheritedTypeListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InheritedTypeListSyntax.self, self.visit, self.visitPost) } case .inheritedType: return { - self.visitImpl($0, InheritedTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InheritedTypeSyntax.self, self.visit, self.visitPost) } case .initializerClause: return { - self.visitImpl($0, InitializerClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InitializerClauseSyntax.self, self.visit, self.visitPost) } case .initializerDecl: return { - self.visitImpl($0, InitializerDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, InitializerDeclSyntax.self, self.visit, self.visitPost) } case .integerLiteralExpr: return { - self.visitImpl($0, IntegerLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IntegerLiteralExprSyntax.self, self.visit, self.visitPost) } case .isExpr: return { - self.visitImpl($0, IsExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IsExprSyntax.self, self.visit, self.visitPost) } case .isTypePattern: return { - self.visitImpl($0, IsTypePatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, IsTypePatternSyntax.self, self.visit, self.visitPost) } case .keyPathComponentList: return { - self.visitImpl($0, KeyPathComponentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, KeyPathComponentListSyntax.self, self.visit, self.visitPost) } case .keyPathComponent: return { - self.visitImpl($0, KeyPathComponentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, KeyPathComponentSyntax.self, self.visit, self.visitPost) } case .keyPathExpr: return { - self.visitImpl($0, KeyPathExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, KeyPathExprSyntax.self, self.visit, self.visitPost) } case .keyPathOptionalComponent: return { - self.visitImpl($0, KeyPathOptionalComponentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, KeyPathOptionalComponentSyntax.self, self.visit, self.visitPost) } case .keyPathPropertyComponent: return { - self.visitImpl($0, KeyPathPropertyComponentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, KeyPathPropertyComponentSyntax.self, self.visit, self.visitPost) } case .keyPathSubscriptComponent: return { - self.visitImpl($0, KeyPathSubscriptComponentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, KeyPathSubscriptComponentSyntax.self, self.visit, self.visitPost) } case .labeledExprList: return { - self.visitImpl($0, LabeledExprListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LabeledExprListSyntax.self, self.visit, self.visitPost) } case .labeledExpr: return { - self.visitImpl($0, LabeledExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LabeledExprSyntax.self, self.visit, self.visitPost) } case .labeledSpecializeArgument: return { - self.visitImpl($0, LabeledSpecializeArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LabeledSpecializeArgumentSyntax.self, self.visit, self.visitPost) } case .labeledStmt: return { - self.visitImpl($0, LabeledStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LabeledStmtSyntax.self, self.visit, self.visitPost) } case .layoutRequirement: return { - self.visitImpl($0, LayoutRequirementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LayoutRequirementSyntax.self, self.visit, self.visitPost) } case .lifetimeSpecifierArgumentList: return { - self.visitImpl($0, LifetimeSpecifierArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LifetimeSpecifierArgumentListSyntax.self, self.visit, self.visitPost) } case .lifetimeSpecifierArgument: return { - self.visitImpl($0, LifetimeSpecifierArgumentSyntax.self, self.visit, self.visitPost) - } - case .lifetimeSpecifierArguments: - return { - self.visitImpl($0, LifetimeSpecifierArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LifetimeSpecifierArgumentSyntax.self, self.visit, self.visitPost) } case .lifetimeTypeSpecifier: return { - self.visitImpl($0, LifetimeTypeSpecifierSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, LifetimeTypeSpecifierSyntax.self, self.visit, self.visitPost) } case .macroDecl: return { - self.visitImpl($0, MacroDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MacroDeclSyntax.self, self.visit, self.visitPost) } case .macroExpansionDecl: return { - self.visitImpl($0, MacroExpansionDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MacroExpansionDeclSyntax.self, self.visit, self.visitPost) } case .macroExpansionExpr: return { - self.visitImpl($0, MacroExpansionExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MacroExpansionExprSyntax.self, self.visit, self.visitPost) } case .matchingPatternCondition: return { - self.visitImpl($0, MatchingPatternConditionSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MatchingPatternConditionSyntax.self, self.visit, self.visitPost) } case .memberAccessExpr: return { - self.visitImpl($0, MemberAccessExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MemberAccessExprSyntax.self, self.visit, self.visitPost) } case .memberBlockItemList: return { - self.visitImpl($0, MemberBlockItemListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MemberBlockItemListSyntax.self, self.visit, self.visitPost) } case .memberBlockItem: return { - self.visitImpl($0, MemberBlockItemSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MemberBlockItemSyntax.self, self.visit, self.visitPost) } case .memberBlock: return { - self.visitImpl($0, MemberBlockSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MemberBlockSyntax.self, self.visit, self.visitPost) } case .memberType: return { - self.visitImpl($0, MemberTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MemberTypeSyntax.self, self.visit, self.visitPost) } case .metatypeType: return { - self.visitImpl($0, MetatypeTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MetatypeTypeSyntax.self, self.visit, self.visitPost) } case .missingDecl: return { - self.visitImpl($0, MissingDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MissingDeclSyntax.self, self.visit, self.visitPost) } case .missingExpr: return { - self.visitImpl($0, MissingExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MissingExprSyntax.self, self.visit, self.visitPost) } case .missingPattern: return { - self.visitImpl($0, MissingPatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MissingPatternSyntax.self, self.visit, self.visitPost) } case .missingStmt: return { - self.visitImpl($0, MissingStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MissingStmtSyntax.self, self.visit, self.visitPost) } case .missing: return { - self.visitImpl($0, MissingSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MissingSyntax.self, self.visit, self.visitPost) } case .missingType: return { - self.visitImpl($0, MissingTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MissingTypeSyntax.self, self.visit, self.visitPost) } case .multipleTrailingClosureElementList: return { - self.visitImpl($0, MultipleTrailingClosureElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MultipleTrailingClosureElementListSyntax.self, self.visit, self.visitPost) } case .multipleTrailingClosureElement: return { - self.visitImpl($0, MultipleTrailingClosureElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, MultipleTrailingClosureElementSyntax.self, self.visit, self.visitPost) } case .namedOpaqueReturnType: return { - self.visitImpl($0, NamedOpaqueReturnTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, NamedOpaqueReturnTypeSyntax.self, self.visit, self.visitPost) } case .nilLiteralExpr: return { - self.visitImpl($0, NilLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, NilLiteralExprSyntax.self, self.visit, self.visitPost) } case .objCSelectorPieceList: return { - self.visitImpl($0, ObjCSelectorPieceListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ObjCSelectorPieceListSyntax.self, self.visit, self.visitPost) } case .objCSelectorPiece: return { - self.visitImpl($0, ObjCSelectorPieceSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ObjCSelectorPieceSyntax.self, self.visit, self.visitPost) } case .opaqueReturnTypeOfAttributeArguments: return { - self.visitImpl($0, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .operatorDecl: return { - self.visitImpl($0, OperatorDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OperatorDeclSyntax.self, self.visit, self.visitPost) } case .operatorPrecedenceAndTypes: return { - self.visitImpl($0, OperatorPrecedenceAndTypesSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OperatorPrecedenceAndTypesSyntax.self, self.visit, self.visitPost) } case .optionalBindingCondition: return { - self.visitImpl($0, OptionalBindingConditionSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OptionalBindingConditionSyntax.self, self.visit, self.visitPost) } case .optionalChainingExpr: return { - self.visitImpl($0, OptionalChainingExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OptionalChainingExprSyntax.self, self.visit, self.visitPost) } case .optionalType: return { - self.visitImpl($0, OptionalTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OptionalTypeSyntax.self, self.visit, self.visitPost) } case .originallyDefinedInAttributeArguments: return { - self.visitImpl($0, OriginallyDefinedInAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, OriginallyDefinedInAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .packElementExpr: return { - self.visitImpl($0, PackElementExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PackElementExprSyntax.self, self.visit, self.visitPost) } case .packElementType: return { - self.visitImpl($0, PackElementTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PackElementTypeSyntax.self, self.visit, self.visitPost) } case .packExpansionExpr: return { - self.visitImpl($0, PackExpansionExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PackExpansionExprSyntax.self, self.visit, self.visitPost) } case .packExpansionType: return { - self.visitImpl($0, PackExpansionTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PackExpansionTypeSyntax.self, self.visit, self.visitPost) } case .patternBindingList: return { - self.visitImpl($0, PatternBindingListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PatternBindingListSyntax.self, self.visit, self.visitPost) } case .patternBinding: return { - self.visitImpl($0, PatternBindingSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PatternBindingSyntax.self, self.visit, self.visitPost) } case .patternExpr: return { - self.visitImpl($0, PatternExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PatternExprSyntax.self, self.visit, self.visitPost) } case .platformVersionItemList: return { - self.visitImpl($0, PlatformVersionItemListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PlatformVersionItemListSyntax.self, self.visit, self.visitPost) } case .platformVersionItem: return { - self.visitImpl($0, PlatformVersionItemSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PlatformVersionItemSyntax.self, self.visit, self.visitPost) } case .platformVersion: return { - self.visitImpl($0, PlatformVersionSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PlatformVersionSyntax.self, self.visit, self.visitPost) } case .postfixIfConfigExpr: return { - self.visitImpl($0, PostfixIfConfigExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PostfixIfConfigExprSyntax.self, self.visit, self.visitPost) } case .postfixOperatorExpr: return { - self.visitImpl($0, PostfixOperatorExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PostfixOperatorExprSyntax.self, self.visit, self.visitPost) } case .poundSourceLocationArguments: return { - self.visitImpl($0, PoundSourceLocationArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PoundSourceLocationArgumentsSyntax.self, self.visit, self.visitPost) } case .poundSourceLocation: return { - self.visitImpl($0, PoundSourceLocationSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PoundSourceLocationSyntax.self, self.visit, self.visitPost) } case .precedenceGroupAssignment: return { - self.visitImpl($0, PrecedenceGroupAssignmentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupAssignmentSyntax.self, self.visit, self.visitPost) } case .precedenceGroupAssociativity: return { - self.visitImpl($0, PrecedenceGroupAssociativitySyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupAssociativitySyntax.self, self.visit, self.visitPost) } case .precedenceGroupAttributeList: return { - self.visitImpl($0, PrecedenceGroupAttributeListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupAttributeListSyntax.self, self.visit, self.visitPost) } case .precedenceGroupDecl: return { - self.visitImpl($0, PrecedenceGroupDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupDeclSyntax.self, self.visit, self.visitPost) } case .precedenceGroupNameList: return { - self.visitImpl($0, PrecedenceGroupNameListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupNameListSyntax.self, self.visit, self.visitPost) } case .precedenceGroupName: return { - self.visitImpl($0, PrecedenceGroupNameSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupNameSyntax.self, self.visit, self.visitPost) } case .precedenceGroupRelation: return { - self.visitImpl($0, PrecedenceGroupRelationSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrecedenceGroupRelationSyntax.self, self.visit, self.visitPost) } case .prefixOperatorExpr: return { - self.visitImpl($0, PrefixOperatorExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrefixOperatorExprSyntax.self, self.visit, self.visitPost) } case .primaryAssociatedTypeClause: return { - self.visitImpl($0, PrimaryAssociatedTypeClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrimaryAssociatedTypeClauseSyntax.self, self.visit, self.visitPost) } case .primaryAssociatedTypeList: return { - self.visitImpl($0, PrimaryAssociatedTypeListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrimaryAssociatedTypeListSyntax.self, self.visit, self.visitPost) } case .primaryAssociatedType: return { - self.visitImpl($0, PrimaryAssociatedTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, PrimaryAssociatedTypeSyntax.self, self.visit, self.visitPost) } case .protocolDecl: return { - self.visitImpl($0, ProtocolDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ProtocolDeclSyntax.self, self.visit, self.visitPost) } case .regexLiteralExpr: return { - self.visitImpl($0, RegexLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, RegexLiteralExprSyntax.self, self.visit, self.visitPost) } case .repeatStmt: return { - self.visitImpl($0, RepeatStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, RepeatStmtSyntax.self, self.visit, self.visitPost) } case .returnClause: return { - self.visitImpl($0, ReturnClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ReturnClauseSyntax.self, self.visit, self.visitPost) } case .returnStmt: return { - self.visitImpl($0, ReturnStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ReturnStmtSyntax.self, self.visit, self.visitPost) } case .sameTypeRequirement: return { - self.visitImpl($0, SameTypeRequirementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SameTypeRequirementSyntax.self, self.visit, self.visitPost) } case .sequenceExpr: return { - self.visitImpl($0, SequenceExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SequenceExprSyntax.self, self.visit, self.visitPost) } case .simpleStringLiteralExpr: return { - self.visitImpl($0, SimpleStringLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SimpleStringLiteralExprSyntax.self, self.visit, self.visitPost) } case .simpleStringLiteralSegmentList: return { - self.visitImpl($0, SimpleStringLiteralSegmentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SimpleStringLiteralSegmentListSyntax.self, self.visit, self.visitPost) } case .simpleTypeSpecifier: return { - self.visitImpl($0, SimpleTypeSpecifierSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SimpleTypeSpecifierSyntax.self, self.visit, self.visitPost) } case .someOrAnyType: return { - self.visitImpl($0, SomeOrAnyTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SomeOrAnyTypeSyntax.self, self.visit, self.visitPost) } case .sourceFile: return { - self.visitImpl($0, SourceFileSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SourceFileSyntax.self, self.visit, self.visitPost) } case .specializeAttributeArgumentList: return { - self.visitImpl($0, SpecializeAttributeArgumentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SpecializeAttributeArgumentListSyntax.self, self.visit, self.visitPost) } case .specializeAvailabilityArgument: return { - self.visitImpl($0, SpecializeAvailabilityArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SpecializeAvailabilityArgumentSyntax.self, self.visit, self.visitPost) } case .specializeTargetFunctionArgument: return { - self.visitImpl($0, SpecializeTargetFunctionArgumentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SpecializeTargetFunctionArgumentSyntax.self, self.visit, self.visitPost) } case .stringLiteralExpr: return { - self.visitImpl($0, StringLiteralExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, StringLiteralExprSyntax.self, self.visit, self.visitPost) } case .stringLiteralSegmentList: return { - self.visitImpl($0, StringLiteralSegmentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, StringLiteralSegmentListSyntax.self, self.visit, self.visitPost) } case .stringSegment: return { - self.visitImpl($0, StringSegmentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, StringSegmentSyntax.self, self.visit, self.visitPost) } case .structDecl: return { - self.visitImpl($0, StructDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, StructDeclSyntax.self, self.visit, self.visitPost) } case .subscriptCallExpr: return { - self.visitImpl($0, SubscriptCallExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SubscriptCallExprSyntax.self, self.visit, self.visitPost) } case .subscriptDecl: return { - self.visitImpl($0, SubscriptDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SubscriptDeclSyntax.self, self.visit, self.visitPost) } case .superExpr: return { - self.visitImpl($0, SuperExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SuperExprSyntax.self, self.visit, self.visitPost) } case .suppressedType: return { - self.visitImpl($0, SuppressedTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SuppressedTypeSyntax.self, self.visit, self.visitPost) } case .switchCaseItemList: return { - self.visitImpl($0, SwitchCaseItemListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchCaseItemListSyntax.self, self.visit, self.visitPost) } case .switchCaseItem: return { - self.visitImpl($0, SwitchCaseItemSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchCaseItemSyntax.self, self.visit, self.visitPost) } case .switchCaseLabel: return { - self.visitImpl($0, SwitchCaseLabelSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchCaseLabelSyntax.self, self.visit, self.visitPost) } case .switchCaseList: return { - self.visitImpl($0, SwitchCaseListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchCaseListSyntax.self, self.visit, self.visitPost) } case .switchCase: return { - self.visitImpl($0, SwitchCaseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchCaseSyntax.self, self.visit, self.visitPost) } case .switchDefaultLabel: return { - self.visitImpl($0, SwitchDefaultLabelSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchDefaultLabelSyntax.self, self.visit, self.visitPost) } case .switchExpr: return { - self.visitImpl($0, SwitchExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, SwitchExprSyntax.self, self.visit, self.visitPost) } case .ternaryExpr: return { - self.visitImpl($0, TernaryExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TernaryExprSyntax.self, self.visit, self.visitPost) } case .thenStmt: return { - self.visitImpl($0, ThenStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ThenStmtSyntax.self, self.visit, self.visitPost) } case .throwStmt: return { - self.visitImpl($0, ThrowStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ThrowStmtSyntax.self, self.visit, self.visitPost) } case .throwsClause: return { - self.visitImpl($0, ThrowsClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ThrowsClauseSyntax.self, self.visit, self.visitPost) } case .tryExpr: return { - self.visitImpl($0, TryExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TryExprSyntax.self, self.visit, self.visitPost) } case .tupleExpr: return { - self.visitImpl($0, TupleExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TupleExprSyntax.self, self.visit, self.visitPost) } case .tuplePatternElementList: return { - self.visitImpl($0, TuplePatternElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TuplePatternElementListSyntax.self, self.visit, self.visitPost) } case .tuplePatternElement: return { - self.visitImpl($0, TuplePatternElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TuplePatternElementSyntax.self, self.visit, self.visitPost) } case .tuplePattern: return { - self.visitImpl($0, TuplePatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TuplePatternSyntax.self, self.visit, self.visitPost) } case .tupleTypeElementList: return { - self.visitImpl($0, TupleTypeElementListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TupleTypeElementListSyntax.self, self.visit, self.visitPost) } case .tupleTypeElement: return { - self.visitImpl($0, TupleTypeElementSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TupleTypeElementSyntax.self, self.visit, self.visitPost) } case .tupleType: return { - self.visitImpl($0, TupleTypeSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TupleTypeSyntax.self, self.visit, self.visitPost) } case .typeAliasDecl: return { - self.visitImpl($0, TypeAliasDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TypeAliasDeclSyntax.self, self.visit, self.visitPost) } case .typeAnnotation: return { - self.visitImpl($0, TypeAnnotationSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TypeAnnotationSyntax.self, self.visit, self.visitPost) } case .typeEffectSpecifiers: return { - self.visitImpl($0, TypeEffectSpecifiersSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TypeEffectSpecifiersSyntax.self, self.visit, self.visitPost) } case .typeExpr: return { - self.visitImpl($0, TypeExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TypeExprSyntax.self, self.visit, self.visitPost) } case .typeInitializerClause: return { - self.visitImpl($0, TypeInitializerClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TypeInitializerClauseSyntax.self, self.visit, self.visitPost) } case .typeSpecifierList: return { - self.visitImpl($0, TypeSpecifierListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, TypeSpecifierListSyntax.self, self.visit, self.visitPost) } case .unavailableFromAsyncAttributeArguments: return { - self.visitImpl($0, UnavailableFromAsyncAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, UnavailableFromAsyncAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .underscorePrivateAttributeArguments: return { - self.visitImpl($0, UnderscorePrivateAttributeArgumentsSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, UnderscorePrivateAttributeArgumentsSyntax.self, self.visit, self.visitPost) } case .unexpectedNodes: return { - self.visitImpl($0, UnexpectedNodesSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, UnexpectedNodesSyntax.self, self.visit, self.visitPost) } case .unresolvedAsExpr: return { - self.visitImpl($0, UnresolvedAsExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, UnresolvedAsExprSyntax.self, self.visit, self.visitPost) } case .unresolvedIsExpr: return { - self.visitImpl($0, UnresolvedIsExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, UnresolvedIsExprSyntax.self, self.visit, self.visitPost) } case .unresolvedTernaryExpr: return { - self.visitImpl($0, UnresolvedTernaryExprSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, UnresolvedTernaryExprSyntax.self, self.visit, self.visitPost) } case .valueBindingPattern: return { - self.visitImpl($0, ValueBindingPatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, ValueBindingPatternSyntax.self, self.visit, self.visitPost) } case .variableDecl: return { - self.visitImpl($0, VariableDeclSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, VariableDeclSyntax.self, self.visit, self.visitPost) } case .versionComponentList: return { - self.visitImpl($0, VersionComponentListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, VersionComponentListSyntax.self, self.visit, self.visitPost) } case .versionComponent: return { - self.visitImpl($0, VersionComponentSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, VersionComponentSyntax.self, self.visit, self.visitPost) } case .versionTuple: return { - self.visitImpl($0, VersionTupleSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, VersionTupleSyntax.self, self.visit, self.visitPost) } case .whereClause: return { - self.visitImpl($0, WhereClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, WhereClauseSyntax.self, self.visit, self.visitPost) } case .whileStmt: return { - self.visitImpl($0, WhileStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, WhileStmtSyntax.self, self.visit, self.visitPost) } case .wildcardPattern: return { - self.visitImpl($0, WildcardPatternSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, WildcardPatternSyntax.self, self.visit, self.visitPost) } case .yieldStmt: return { - self.visitImpl($0, YieldStmtSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, YieldStmtSyntax.self, self.visit, self.visitPost) } case .yieldedExpressionList: return { - self.visitImpl($0, YieldedExpressionListSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, YieldedExpressionListSyntax.self, self.visit, self.visitPost) } case .yieldedExpression: return { - self.visitImpl($0, YieldedExpressionSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, YieldedExpressionSyntax.self, self.visit, self.visitPost) } case .yieldedExpressionsClause: return { - self.visitImpl($0, YieldedExpressionsClauseSyntax.self, self.visit, self.visitPost) + self.visitImpl(&$0, YieldedExpressionsClauseSyntax.self, self.visit, self.visitPost) } } } - private func visit(_ node: Syntax) { - return visitationFunc(for: node)(node) + private func visit(_ node: inout Syntax) { + return visitationFunc(for: node)(&node) } #else - private func visit(_ node: Syntax) { + /// - Note: `node` is `inout` to avoid ref-counting. See comment in `visitImpl` + private func visit(_ node: inout Syntax) { switch node.raw.kind { case .token: let node = node.cast(TokenSyntax.self) @@ -4690,581 +4682,581 @@ open class SyntaxVisitor { // No children to visit. visitPost(node) case .accessorBlock: - visitImpl(node, AccessorBlockSyntax.self, visit, visitPost) + visitImpl(&node, AccessorBlockSyntax.self, visit, visitPost) case .accessorDeclList: - visitImpl(node, AccessorDeclListSyntax.self, visit, visitPost) + visitImpl(&node, AccessorDeclListSyntax.self, visit, visitPost) case .accessorDecl: - visitImpl(node, AccessorDeclSyntax.self, visit, visitPost) + visitImpl(&node, AccessorDeclSyntax.self, visit, visitPost) case .accessorEffectSpecifiers: - visitImpl(node, AccessorEffectSpecifiersSyntax.self, visit, visitPost) + visitImpl(&node, AccessorEffectSpecifiersSyntax.self, visit, visitPost) case .accessorParameters: - visitImpl(node, AccessorParametersSyntax.self, visit, visitPost) + visitImpl(&node, AccessorParametersSyntax.self, visit, visitPost) case .actorDecl: - visitImpl(node, ActorDeclSyntax.self, visit, visitPost) + visitImpl(&node, ActorDeclSyntax.self, visit, visitPost) case .arrayElementList: - visitImpl(node, ArrayElementListSyntax.self, visit, visitPost) + visitImpl(&node, ArrayElementListSyntax.self, visit, visitPost) case .arrayElement: - visitImpl(node, ArrayElementSyntax.self, visit, visitPost) + visitImpl(&node, ArrayElementSyntax.self, visit, visitPost) case .arrayExpr: - visitImpl(node, ArrayExprSyntax.self, visit, visitPost) + visitImpl(&node, ArrayExprSyntax.self, visit, visitPost) case .arrayType: - visitImpl(node, ArrayTypeSyntax.self, visit, visitPost) + visitImpl(&node, ArrayTypeSyntax.self, visit, visitPost) case .arrowExpr: - visitImpl(node, ArrowExprSyntax.self, visit, visitPost) + visitImpl(&node, ArrowExprSyntax.self, visit, visitPost) case .asExpr: - visitImpl(node, AsExprSyntax.self, visit, visitPost) + visitImpl(&node, AsExprSyntax.self, visit, visitPost) case .assignmentExpr: - visitImpl(node, AssignmentExprSyntax.self, visit, visitPost) + visitImpl(&node, AssignmentExprSyntax.self, visit, visitPost) case .associatedTypeDecl: - visitImpl(node, AssociatedTypeDeclSyntax.self, visit, visitPost) + visitImpl(&node, AssociatedTypeDeclSyntax.self, visit, visitPost) case .attributeList: - visitImpl(node, AttributeListSyntax.self, visit, visitPost) + visitImpl(&node, AttributeListSyntax.self, visit, visitPost) case .attribute: - visitImpl(node, AttributeSyntax.self, visit, visitPost) + visitImpl(&node, AttributeSyntax.self, visit, visitPost) case .attributedType: - visitImpl(node, AttributedTypeSyntax.self, visit, visitPost) + visitImpl(&node, AttributedTypeSyntax.self, visit, visitPost) case .availabilityArgumentList: - visitImpl(node, AvailabilityArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, AvailabilityArgumentListSyntax.self, visit, visitPost) case .availabilityArgument: - visitImpl(node, AvailabilityArgumentSyntax.self, visit, visitPost) + visitImpl(&node, AvailabilityArgumentSyntax.self, visit, visitPost) case .availabilityCondition: - visitImpl(node, AvailabilityConditionSyntax.self, visit, visitPost) + visitImpl(&node, AvailabilityConditionSyntax.self, visit, visitPost) case .availabilityLabeledArgument: - visitImpl(node, AvailabilityLabeledArgumentSyntax.self, visit, visitPost) + visitImpl(&node, AvailabilityLabeledArgumentSyntax.self, visit, visitPost) case .awaitExpr: - visitImpl(node, AwaitExprSyntax.self, visit, visitPost) + visitImpl(&node, AwaitExprSyntax.self, visit, visitPost) case .backDeployedAttributeArguments: - visitImpl(node, BackDeployedAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, BackDeployedAttributeArgumentsSyntax.self, visit, visitPost) case .binaryOperatorExpr: - visitImpl(node, BinaryOperatorExprSyntax.self, visit, visitPost) + visitImpl(&node, BinaryOperatorExprSyntax.self, visit, visitPost) case .booleanLiteralExpr: - visitImpl(node, BooleanLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, BooleanLiteralExprSyntax.self, visit, visitPost) case .borrowExpr: - visitImpl(node, BorrowExprSyntax.self, visit, visitPost) + visitImpl(&node, BorrowExprSyntax.self, visit, visitPost) case .breakStmt: - visitImpl(node, BreakStmtSyntax.self, visit, visitPost) - case .canImportExpr: - visitImpl(node, CanImportExprSyntax.self, visit, visitPost) - case .canImportVersionInfo: - visitImpl(node, CanImportVersionInfoSyntax.self, visit, visitPost) + visitImpl(&node, BreakStmtSyntax.self, visit, visitPost) + case ._canImportExpr: + visitImpl(&node, _CanImportExprSyntax.self, visit, visitPost) + case ._canImportVersionInfo: + visitImpl(&node, _CanImportVersionInfoSyntax.self, visit, visitPost) case .catchClauseList: - visitImpl(node, CatchClauseListSyntax.self, visit, visitPost) + visitImpl(&node, CatchClauseListSyntax.self, visit, visitPost) case .catchClause: - visitImpl(node, CatchClauseSyntax.self, visit, visitPost) + visitImpl(&node, CatchClauseSyntax.self, visit, visitPost) case .catchItemList: - visitImpl(node, CatchItemListSyntax.self, visit, visitPost) + visitImpl(&node, CatchItemListSyntax.self, visit, visitPost) case .catchItem: - visitImpl(node, CatchItemSyntax.self, visit, visitPost) + visitImpl(&node, CatchItemSyntax.self, visit, visitPost) case .classDecl: - visitImpl(node, ClassDeclSyntax.self, visit, visitPost) + visitImpl(&node, ClassDeclSyntax.self, visit, visitPost) case .classRestrictionType: - visitImpl(node, ClassRestrictionTypeSyntax.self, visit, visitPost) + visitImpl(&node, ClassRestrictionTypeSyntax.self, visit, visitPost) case .closureCaptureClause: - visitImpl(node, ClosureCaptureClauseSyntax.self, visit, visitPost) + visitImpl(&node, ClosureCaptureClauseSyntax.self, visit, visitPost) case .closureCaptureList: - visitImpl(node, ClosureCaptureListSyntax.self, visit, visitPost) + visitImpl(&node, ClosureCaptureListSyntax.self, visit, visitPost) case .closureCaptureSpecifier: - visitImpl(node, ClosureCaptureSpecifierSyntax.self, visit, visitPost) + visitImpl(&node, ClosureCaptureSpecifierSyntax.self, visit, visitPost) case .closureCapture: - visitImpl(node, ClosureCaptureSyntax.self, visit, visitPost) + visitImpl(&node, ClosureCaptureSyntax.self, visit, visitPost) case .closureExpr: - visitImpl(node, ClosureExprSyntax.self, visit, visitPost) + visitImpl(&node, ClosureExprSyntax.self, visit, visitPost) case .closureParameterClause: - visitImpl(node, ClosureParameterClauseSyntax.self, visit, visitPost) + visitImpl(&node, ClosureParameterClauseSyntax.self, visit, visitPost) case .closureParameterList: - visitImpl(node, ClosureParameterListSyntax.self, visit, visitPost) + visitImpl(&node, ClosureParameterListSyntax.self, visit, visitPost) case .closureParameter: - visitImpl(node, ClosureParameterSyntax.self, visit, visitPost) + visitImpl(&node, ClosureParameterSyntax.self, visit, visitPost) case .closureShorthandParameterList: - visitImpl(node, ClosureShorthandParameterListSyntax.self, visit, visitPost) + visitImpl(&node, ClosureShorthandParameterListSyntax.self, visit, visitPost) case .closureShorthandParameter: - visitImpl(node, ClosureShorthandParameterSyntax.self, visit, visitPost) + visitImpl(&node, ClosureShorthandParameterSyntax.self, visit, visitPost) case .closureSignature: - visitImpl(node, ClosureSignatureSyntax.self, visit, visitPost) + visitImpl(&node, ClosureSignatureSyntax.self, visit, visitPost) case .codeBlockItemList: - visitImpl(node, CodeBlockItemListSyntax.self, visit, visitPost) + visitImpl(&node, CodeBlockItemListSyntax.self, visit, visitPost) case .codeBlockItem: - visitImpl(node, CodeBlockItemSyntax.self, visit, visitPost) + visitImpl(&node, CodeBlockItemSyntax.self, visit, visitPost) case .codeBlock: - visitImpl(node, CodeBlockSyntax.self, visit, visitPost) + visitImpl(&node, CodeBlockSyntax.self, visit, visitPost) case .compositionTypeElementList: - visitImpl(node, CompositionTypeElementListSyntax.self, visit, visitPost) + visitImpl(&node, CompositionTypeElementListSyntax.self, visit, visitPost) case .compositionTypeElement: - visitImpl(node, CompositionTypeElementSyntax.self, visit, visitPost) + visitImpl(&node, CompositionTypeElementSyntax.self, visit, visitPost) case .compositionType: - visitImpl(node, CompositionTypeSyntax.self, visit, visitPost) + visitImpl(&node, CompositionTypeSyntax.self, visit, visitPost) case .conditionElementList: - visitImpl(node, ConditionElementListSyntax.self, visit, visitPost) + visitImpl(&node, ConditionElementListSyntax.self, visit, visitPost) case .conditionElement: - visitImpl(node, ConditionElementSyntax.self, visit, visitPost) + visitImpl(&node, ConditionElementSyntax.self, visit, visitPost) case .conformanceRequirement: - visitImpl(node, ConformanceRequirementSyntax.self, visit, visitPost) + visitImpl(&node, ConformanceRequirementSyntax.self, visit, visitPost) case .consumeExpr: - visitImpl(node, ConsumeExprSyntax.self, visit, visitPost) + visitImpl(&node, ConsumeExprSyntax.self, visit, visitPost) case .continueStmt: - visitImpl(node, ContinueStmtSyntax.self, visit, visitPost) + visitImpl(&node, ContinueStmtSyntax.self, visit, visitPost) case .conventionAttributeArguments: - visitImpl(node, ConventionAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, ConventionAttributeArgumentsSyntax.self, visit, visitPost) case .conventionWitnessMethodAttributeArguments: - visitImpl(node, ConventionWitnessMethodAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, ConventionWitnessMethodAttributeArgumentsSyntax.self, visit, visitPost) case .copyExpr: - visitImpl(node, CopyExprSyntax.self, visit, visitPost) + visitImpl(&node, CopyExprSyntax.self, visit, visitPost) case .declModifierDetail: - visitImpl(node, DeclModifierDetailSyntax.self, visit, visitPost) + visitImpl(&node, DeclModifierDetailSyntax.self, visit, visitPost) case .declModifierList: - visitImpl(node, DeclModifierListSyntax.self, visit, visitPost) + visitImpl(&node, DeclModifierListSyntax.self, visit, visitPost) case .declModifier: - visitImpl(node, DeclModifierSyntax.self, visit, visitPost) + visitImpl(&node, DeclModifierSyntax.self, visit, visitPost) case .declNameArgumentList: - visitImpl(node, DeclNameArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, DeclNameArgumentListSyntax.self, visit, visitPost) case .declNameArgument: - visitImpl(node, DeclNameArgumentSyntax.self, visit, visitPost) + visitImpl(&node, DeclNameArgumentSyntax.self, visit, visitPost) case .declNameArguments: - visitImpl(node, DeclNameArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, DeclNameArgumentsSyntax.self, visit, visitPost) case .declReferenceExpr: - visitImpl(node, DeclReferenceExprSyntax.self, visit, visitPost) + visitImpl(&node, DeclReferenceExprSyntax.self, visit, visitPost) case .deferStmt: - visitImpl(node, DeferStmtSyntax.self, visit, visitPost) + visitImpl(&node, DeferStmtSyntax.self, visit, visitPost) case .deinitializerDecl: - visitImpl(node, DeinitializerDeclSyntax.self, visit, visitPost) + visitImpl(&node, DeinitializerDeclSyntax.self, visit, visitPost) case .deinitializerEffectSpecifiers: - visitImpl(node, DeinitializerEffectSpecifiersSyntax.self, visit, visitPost) + visitImpl(&node, DeinitializerEffectSpecifiersSyntax.self, visit, visitPost) case .derivativeAttributeArguments: - visitImpl(node, DerivativeAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, DerivativeAttributeArgumentsSyntax.self, visit, visitPost) case .designatedTypeList: - visitImpl(node, DesignatedTypeListSyntax.self, visit, visitPost) + visitImpl(&node, DesignatedTypeListSyntax.self, visit, visitPost) case .designatedType: - visitImpl(node, DesignatedTypeSyntax.self, visit, visitPost) + visitImpl(&node, DesignatedTypeSyntax.self, visit, visitPost) case .dictionaryElementList: - visitImpl(node, DictionaryElementListSyntax.self, visit, visitPost) + visitImpl(&node, DictionaryElementListSyntax.self, visit, visitPost) case .dictionaryElement: - visitImpl(node, DictionaryElementSyntax.self, visit, visitPost) + visitImpl(&node, DictionaryElementSyntax.self, visit, visitPost) case .dictionaryExpr: - visitImpl(node, DictionaryExprSyntax.self, visit, visitPost) + visitImpl(&node, DictionaryExprSyntax.self, visit, visitPost) case .dictionaryType: - visitImpl(node, DictionaryTypeSyntax.self, visit, visitPost) + visitImpl(&node, DictionaryTypeSyntax.self, visit, visitPost) case .differentiabilityArgumentList: - visitImpl(node, DifferentiabilityArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, DifferentiabilityArgumentListSyntax.self, visit, visitPost) case .differentiabilityArgument: - visitImpl(node, DifferentiabilityArgumentSyntax.self, visit, visitPost) + visitImpl(&node, DifferentiabilityArgumentSyntax.self, visit, visitPost) case .differentiabilityArguments: - visitImpl(node, DifferentiabilityArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, DifferentiabilityArgumentsSyntax.self, visit, visitPost) case .differentiabilityWithRespectToArgument: - visitImpl(node, DifferentiabilityWithRespectToArgumentSyntax.self, visit, visitPost) + visitImpl(&node, DifferentiabilityWithRespectToArgumentSyntax.self, visit, visitPost) case .differentiableAttributeArguments: - visitImpl(node, DifferentiableAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, DifferentiableAttributeArgumentsSyntax.self, visit, visitPost) case .discardAssignmentExpr: - visitImpl(node, DiscardAssignmentExprSyntax.self, visit, visitPost) + visitImpl(&node, DiscardAssignmentExprSyntax.self, visit, visitPost) case .discardStmt: - visitImpl(node, DiscardStmtSyntax.self, visit, visitPost) + visitImpl(&node, DiscardStmtSyntax.self, visit, visitPost) case .doExpr: - visitImpl(node, DoExprSyntax.self, visit, visitPost) + visitImpl(&node, DoExprSyntax.self, visit, visitPost) case .doStmt: - visitImpl(node, DoStmtSyntax.self, visit, visitPost) + visitImpl(&node, DoStmtSyntax.self, visit, visitPost) case .documentationAttributeArgumentList: - visitImpl(node, DocumentationAttributeArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, DocumentationAttributeArgumentListSyntax.self, visit, visitPost) case .documentationAttributeArgument: - visitImpl(node, DocumentationAttributeArgumentSyntax.self, visit, visitPost) + visitImpl(&node, DocumentationAttributeArgumentSyntax.self, visit, visitPost) case .dynamicReplacementAttributeArguments: - visitImpl(node, DynamicReplacementAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, DynamicReplacementAttributeArgumentsSyntax.self, visit, visitPost) case .editorPlaceholderDecl: - visitImpl(node, EditorPlaceholderDeclSyntax.self, visit, visitPost) + visitImpl(&node, EditorPlaceholderDeclSyntax.self, visit, visitPost) case .editorPlaceholderExpr: - visitImpl(node, EditorPlaceholderExprSyntax.self, visit, visitPost) + visitImpl(&node, EditorPlaceholderExprSyntax.self, visit, visitPost) case .effectsAttributeArgumentList: - visitImpl(node, EffectsAttributeArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, EffectsAttributeArgumentListSyntax.self, visit, visitPost) case .enumCaseDecl: - visitImpl(node, EnumCaseDeclSyntax.self, visit, visitPost) + visitImpl(&node, EnumCaseDeclSyntax.self, visit, visitPost) case .enumCaseElementList: - visitImpl(node, EnumCaseElementListSyntax.self, visit, visitPost) + visitImpl(&node, EnumCaseElementListSyntax.self, visit, visitPost) case .enumCaseElement: - visitImpl(node, EnumCaseElementSyntax.self, visit, visitPost) + visitImpl(&node, EnumCaseElementSyntax.self, visit, visitPost) case .enumCaseParameterClause: - visitImpl(node, EnumCaseParameterClauseSyntax.self, visit, visitPost) + visitImpl(&node, EnumCaseParameterClauseSyntax.self, visit, visitPost) case .enumCaseParameterList: - visitImpl(node, EnumCaseParameterListSyntax.self, visit, visitPost) + visitImpl(&node, EnumCaseParameterListSyntax.self, visit, visitPost) case .enumCaseParameter: - visitImpl(node, EnumCaseParameterSyntax.self, visit, visitPost) + visitImpl(&node, EnumCaseParameterSyntax.self, visit, visitPost) case .enumDecl: - visitImpl(node, EnumDeclSyntax.self, visit, visitPost) + visitImpl(&node, EnumDeclSyntax.self, visit, visitPost) case .exposeAttributeArguments: - visitImpl(node, ExposeAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, ExposeAttributeArgumentsSyntax.self, visit, visitPost) case .exprList: - visitImpl(node, ExprListSyntax.self, visit, visitPost) + visitImpl(&node, ExprListSyntax.self, visit, visitPost) case .expressionPattern: - visitImpl(node, ExpressionPatternSyntax.self, visit, visitPost) + visitImpl(&node, ExpressionPatternSyntax.self, visit, visitPost) case .expressionSegment: - visitImpl(node, ExpressionSegmentSyntax.self, visit, visitPost) + visitImpl(&node, ExpressionSegmentSyntax.self, visit, visitPost) case .expressionStmt: - visitImpl(node, ExpressionStmtSyntax.self, visit, visitPost) + visitImpl(&node, ExpressionStmtSyntax.self, visit, visitPost) case .extensionDecl: - visitImpl(node, ExtensionDeclSyntax.self, visit, visitPost) + visitImpl(&node, ExtensionDeclSyntax.self, visit, visitPost) case .fallThroughStmt: - visitImpl(node, FallThroughStmtSyntax.self, visit, visitPost) + visitImpl(&node, FallThroughStmtSyntax.self, visit, visitPost) case .floatLiteralExpr: - visitImpl(node, FloatLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, FloatLiteralExprSyntax.self, visit, visitPost) case .forStmt: - visitImpl(node, ForStmtSyntax.self, visit, visitPost) + visitImpl(&node, ForStmtSyntax.self, visit, visitPost) case .forceUnwrapExpr: - visitImpl(node, ForceUnwrapExprSyntax.self, visit, visitPost) + visitImpl(&node, ForceUnwrapExprSyntax.self, visit, visitPost) case .functionCallExpr: - visitImpl(node, FunctionCallExprSyntax.self, visit, visitPost) + visitImpl(&node, FunctionCallExprSyntax.self, visit, visitPost) case .functionDecl: - visitImpl(node, FunctionDeclSyntax.self, visit, visitPost) + visitImpl(&node, FunctionDeclSyntax.self, visit, visitPost) case .functionEffectSpecifiers: - visitImpl(node, FunctionEffectSpecifiersSyntax.self, visit, visitPost) + visitImpl(&node, FunctionEffectSpecifiersSyntax.self, visit, visitPost) case .functionParameterClause: - visitImpl(node, FunctionParameterClauseSyntax.self, visit, visitPost) + visitImpl(&node, FunctionParameterClauseSyntax.self, visit, visitPost) case .functionParameterList: - visitImpl(node, FunctionParameterListSyntax.self, visit, visitPost) + visitImpl(&node, FunctionParameterListSyntax.self, visit, visitPost) case .functionParameter: - visitImpl(node, FunctionParameterSyntax.self, visit, visitPost) + visitImpl(&node, FunctionParameterSyntax.self, visit, visitPost) case .functionSignature: - visitImpl(node, FunctionSignatureSyntax.self, visit, visitPost) + visitImpl(&node, FunctionSignatureSyntax.self, visit, visitPost) case .functionType: - visitImpl(node, FunctionTypeSyntax.self, visit, visitPost) + visitImpl(&node, FunctionTypeSyntax.self, visit, visitPost) case .genericArgumentClause: - visitImpl(node, GenericArgumentClauseSyntax.self, visit, visitPost) + visitImpl(&node, GenericArgumentClauseSyntax.self, visit, visitPost) case .genericArgumentList: - visitImpl(node, GenericArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, GenericArgumentListSyntax.self, visit, visitPost) case .genericArgument: - visitImpl(node, GenericArgumentSyntax.self, visit, visitPost) + visitImpl(&node, GenericArgumentSyntax.self, visit, visitPost) case .genericParameterClause: - visitImpl(node, GenericParameterClauseSyntax.self, visit, visitPost) + visitImpl(&node, GenericParameterClauseSyntax.self, visit, visitPost) case .genericParameterList: - visitImpl(node, GenericParameterListSyntax.self, visit, visitPost) + visitImpl(&node, GenericParameterListSyntax.self, visit, visitPost) case .genericParameter: - visitImpl(node, GenericParameterSyntax.self, visit, visitPost) + visitImpl(&node, GenericParameterSyntax.self, visit, visitPost) case .genericRequirementList: - visitImpl(node, GenericRequirementListSyntax.self, visit, visitPost) + visitImpl(&node, GenericRequirementListSyntax.self, visit, visitPost) case .genericRequirement: - visitImpl(node, GenericRequirementSyntax.self, visit, visitPost) + visitImpl(&node, GenericRequirementSyntax.self, visit, visitPost) case .genericSpecializationExpr: - visitImpl(node, GenericSpecializationExprSyntax.self, visit, visitPost) + visitImpl(&node, GenericSpecializationExprSyntax.self, visit, visitPost) case .genericWhereClause: - visitImpl(node, GenericWhereClauseSyntax.self, visit, visitPost) + visitImpl(&node, GenericWhereClauseSyntax.self, visit, visitPost) case .guardStmt: - visitImpl(node, GuardStmtSyntax.self, visit, visitPost) + visitImpl(&node, GuardStmtSyntax.self, visit, visitPost) case .identifierPattern: - visitImpl(node, IdentifierPatternSyntax.self, visit, visitPost) + visitImpl(&node, IdentifierPatternSyntax.self, visit, visitPost) case .identifierType: - visitImpl(node, IdentifierTypeSyntax.self, visit, visitPost) + visitImpl(&node, IdentifierTypeSyntax.self, visit, visitPost) case .ifConfigClauseList: - visitImpl(node, IfConfigClauseListSyntax.self, visit, visitPost) + visitImpl(&node, IfConfigClauseListSyntax.self, visit, visitPost) case .ifConfigClause: - visitImpl(node, IfConfigClauseSyntax.self, visit, visitPost) + visitImpl(&node, IfConfigClauseSyntax.self, visit, visitPost) case .ifConfigDecl: - visitImpl(node, IfConfigDeclSyntax.self, visit, visitPost) + visitImpl(&node, IfConfigDeclSyntax.self, visit, visitPost) case .ifExpr: - visitImpl(node, IfExprSyntax.self, visit, visitPost) + visitImpl(&node, IfExprSyntax.self, visit, visitPost) case .implementsAttributeArguments: - visitImpl(node, ImplementsAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, ImplementsAttributeArgumentsSyntax.self, visit, visitPost) case .implicitlyUnwrappedOptionalType: - visitImpl(node, ImplicitlyUnwrappedOptionalTypeSyntax.self, visit, visitPost) + visitImpl(&node, ImplicitlyUnwrappedOptionalTypeSyntax.self, visit, visitPost) case .importDecl: - visitImpl(node, ImportDeclSyntax.self, visit, visitPost) + visitImpl(&node, ImportDeclSyntax.self, visit, visitPost) case .importPathComponentList: - visitImpl(node, ImportPathComponentListSyntax.self, visit, visitPost) + visitImpl(&node, ImportPathComponentListSyntax.self, visit, visitPost) case .importPathComponent: - visitImpl(node, ImportPathComponentSyntax.self, visit, visitPost) + visitImpl(&node, ImportPathComponentSyntax.self, visit, visitPost) case .inOutExpr: - visitImpl(node, InOutExprSyntax.self, visit, visitPost) + visitImpl(&node, InOutExprSyntax.self, visit, visitPost) case .infixOperatorExpr: - visitImpl(node, InfixOperatorExprSyntax.self, visit, visitPost) + visitImpl(&node, InfixOperatorExprSyntax.self, visit, visitPost) case .inheritanceClause: - visitImpl(node, InheritanceClauseSyntax.self, visit, visitPost) + visitImpl(&node, InheritanceClauseSyntax.self, visit, visitPost) case .inheritedTypeList: - visitImpl(node, InheritedTypeListSyntax.self, visit, visitPost) + visitImpl(&node, InheritedTypeListSyntax.self, visit, visitPost) case .inheritedType: - visitImpl(node, InheritedTypeSyntax.self, visit, visitPost) + visitImpl(&node, InheritedTypeSyntax.self, visit, visitPost) case .initializerClause: - visitImpl(node, InitializerClauseSyntax.self, visit, visitPost) + visitImpl(&node, InitializerClauseSyntax.self, visit, visitPost) case .initializerDecl: - visitImpl(node, InitializerDeclSyntax.self, visit, visitPost) + visitImpl(&node, InitializerDeclSyntax.self, visit, visitPost) case .integerLiteralExpr: - visitImpl(node, IntegerLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, IntegerLiteralExprSyntax.self, visit, visitPost) case .isExpr: - visitImpl(node, IsExprSyntax.self, visit, visitPost) + visitImpl(&node, IsExprSyntax.self, visit, visitPost) case .isTypePattern: - visitImpl(node, IsTypePatternSyntax.self, visit, visitPost) + visitImpl(&node, IsTypePatternSyntax.self, visit, visitPost) case .keyPathComponentList: - visitImpl(node, KeyPathComponentListSyntax.self, visit, visitPost) + visitImpl(&node, KeyPathComponentListSyntax.self, visit, visitPost) case .keyPathComponent: - visitImpl(node, KeyPathComponentSyntax.self, visit, visitPost) + visitImpl(&node, KeyPathComponentSyntax.self, visit, visitPost) case .keyPathExpr: - visitImpl(node, KeyPathExprSyntax.self, visit, visitPost) + visitImpl(&node, KeyPathExprSyntax.self, visit, visitPost) case .keyPathOptionalComponent: - visitImpl(node, KeyPathOptionalComponentSyntax.self, visit, visitPost) + visitImpl(&node, KeyPathOptionalComponentSyntax.self, visit, visitPost) case .keyPathPropertyComponent: - visitImpl(node, KeyPathPropertyComponentSyntax.self, visit, visitPost) + visitImpl(&node, KeyPathPropertyComponentSyntax.self, visit, visitPost) case .keyPathSubscriptComponent: - visitImpl(node, KeyPathSubscriptComponentSyntax.self, visit, visitPost) + visitImpl(&node, KeyPathSubscriptComponentSyntax.self, visit, visitPost) case .labeledExprList: - visitImpl(node, LabeledExprListSyntax.self, visit, visitPost) + visitImpl(&node, LabeledExprListSyntax.self, visit, visitPost) case .labeledExpr: - visitImpl(node, LabeledExprSyntax.self, visit, visitPost) + visitImpl(&node, LabeledExprSyntax.self, visit, visitPost) case .labeledSpecializeArgument: - visitImpl(node, LabeledSpecializeArgumentSyntax.self, visit, visitPost) + visitImpl(&node, LabeledSpecializeArgumentSyntax.self, visit, visitPost) case .labeledStmt: - visitImpl(node, LabeledStmtSyntax.self, visit, visitPost) + visitImpl(&node, LabeledStmtSyntax.self, visit, visitPost) case .layoutRequirement: - visitImpl(node, LayoutRequirementSyntax.self, visit, visitPost) + visitImpl(&node, LayoutRequirementSyntax.self, visit, visitPost) case .lifetimeSpecifierArgumentList: - visitImpl(node, LifetimeSpecifierArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, LifetimeSpecifierArgumentListSyntax.self, visit, visitPost) case .lifetimeSpecifierArgument: - visitImpl(node, LifetimeSpecifierArgumentSyntax.self, visit, visitPost) - case .lifetimeSpecifierArguments: - visitImpl(node, LifetimeSpecifierArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, LifetimeSpecifierArgumentSyntax.self, visit, visitPost) case .lifetimeTypeSpecifier: - visitImpl(node, LifetimeTypeSpecifierSyntax.self, visit, visitPost) + visitImpl(&node, LifetimeTypeSpecifierSyntax.self, visit, visitPost) case .macroDecl: - visitImpl(node, MacroDeclSyntax.self, visit, visitPost) + visitImpl(&node, MacroDeclSyntax.self, visit, visitPost) case .macroExpansionDecl: - visitImpl(node, MacroExpansionDeclSyntax.self, visit, visitPost) + visitImpl(&node, MacroExpansionDeclSyntax.self, visit, visitPost) case .macroExpansionExpr: - visitImpl(node, MacroExpansionExprSyntax.self, visit, visitPost) + visitImpl(&node, MacroExpansionExprSyntax.self, visit, visitPost) case .matchingPatternCondition: - visitImpl(node, MatchingPatternConditionSyntax.self, visit, visitPost) + visitImpl(&node, MatchingPatternConditionSyntax.self, visit, visitPost) case .memberAccessExpr: - visitImpl(node, MemberAccessExprSyntax.self, visit, visitPost) + visitImpl(&node, MemberAccessExprSyntax.self, visit, visitPost) case .memberBlockItemList: - visitImpl(node, MemberBlockItemListSyntax.self, visit, visitPost) + visitImpl(&node, MemberBlockItemListSyntax.self, visit, visitPost) case .memberBlockItem: - visitImpl(node, MemberBlockItemSyntax.self, visit, visitPost) + visitImpl(&node, MemberBlockItemSyntax.self, visit, visitPost) case .memberBlock: - visitImpl(node, MemberBlockSyntax.self, visit, visitPost) + visitImpl(&node, MemberBlockSyntax.self, visit, visitPost) case .memberType: - visitImpl(node, MemberTypeSyntax.self, visit, visitPost) + visitImpl(&node, MemberTypeSyntax.self, visit, visitPost) case .metatypeType: - visitImpl(node, MetatypeTypeSyntax.self, visit, visitPost) + visitImpl(&node, MetatypeTypeSyntax.self, visit, visitPost) case .missingDecl: - visitImpl(node, MissingDeclSyntax.self, visit, visitPost) + visitImpl(&node, MissingDeclSyntax.self, visit, visitPost) case .missingExpr: - visitImpl(node, MissingExprSyntax.self, visit, visitPost) + visitImpl(&node, MissingExprSyntax.self, visit, visitPost) case .missingPattern: - visitImpl(node, MissingPatternSyntax.self, visit, visitPost) + visitImpl(&node, MissingPatternSyntax.self, visit, visitPost) case .missingStmt: - visitImpl(node, MissingStmtSyntax.self, visit, visitPost) + visitImpl(&node, MissingStmtSyntax.self, visit, visitPost) case .missing: - visitImpl(node, MissingSyntax.self, visit, visitPost) + visitImpl(&node, MissingSyntax.self, visit, visitPost) case .missingType: - visitImpl(node, MissingTypeSyntax.self, visit, visitPost) + visitImpl(&node, MissingTypeSyntax.self, visit, visitPost) case .multipleTrailingClosureElementList: - visitImpl(node, MultipleTrailingClosureElementListSyntax.self, visit, visitPost) + visitImpl(&node, MultipleTrailingClosureElementListSyntax.self, visit, visitPost) case .multipleTrailingClosureElement: - visitImpl(node, MultipleTrailingClosureElementSyntax.self, visit, visitPost) + visitImpl(&node, MultipleTrailingClosureElementSyntax.self, visit, visitPost) case .namedOpaqueReturnType: - visitImpl(node, NamedOpaqueReturnTypeSyntax.self, visit, visitPost) + visitImpl(&node, NamedOpaqueReturnTypeSyntax.self, visit, visitPost) case .nilLiteralExpr: - visitImpl(node, NilLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, NilLiteralExprSyntax.self, visit, visitPost) case .objCSelectorPieceList: - visitImpl(node, ObjCSelectorPieceListSyntax.self, visit, visitPost) + visitImpl(&node, ObjCSelectorPieceListSyntax.self, visit, visitPost) case .objCSelectorPiece: - visitImpl(node, ObjCSelectorPieceSyntax.self, visit, visitPost) + visitImpl(&node, ObjCSelectorPieceSyntax.self, visit, visitPost) case .opaqueReturnTypeOfAttributeArguments: - visitImpl(node, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, OpaqueReturnTypeOfAttributeArgumentsSyntax.self, visit, visitPost) case .operatorDecl: - visitImpl(node, OperatorDeclSyntax.self, visit, visitPost) + visitImpl(&node, OperatorDeclSyntax.self, visit, visitPost) case .operatorPrecedenceAndTypes: - visitImpl(node, OperatorPrecedenceAndTypesSyntax.self, visit, visitPost) + visitImpl(&node, OperatorPrecedenceAndTypesSyntax.self, visit, visitPost) case .optionalBindingCondition: - visitImpl(node, OptionalBindingConditionSyntax.self, visit, visitPost) + visitImpl(&node, OptionalBindingConditionSyntax.self, visit, visitPost) case .optionalChainingExpr: - visitImpl(node, OptionalChainingExprSyntax.self, visit, visitPost) + visitImpl(&node, OptionalChainingExprSyntax.self, visit, visitPost) case .optionalType: - visitImpl(node, OptionalTypeSyntax.self, visit, visitPost) + visitImpl(&node, OptionalTypeSyntax.self, visit, visitPost) case .originallyDefinedInAttributeArguments: - visitImpl(node, OriginallyDefinedInAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, OriginallyDefinedInAttributeArgumentsSyntax.self, visit, visitPost) case .packElementExpr: - visitImpl(node, PackElementExprSyntax.self, visit, visitPost) + visitImpl(&node, PackElementExprSyntax.self, visit, visitPost) case .packElementType: - visitImpl(node, PackElementTypeSyntax.self, visit, visitPost) + visitImpl(&node, PackElementTypeSyntax.self, visit, visitPost) case .packExpansionExpr: - visitImpl(node, PackExpansionExprSyntax.self, visit, visitPost) + visitImpl(&node, PackExpansionExprSyntax.self, visit, visitPost) case .packExpansionType: - visitImpl(node, PackExpansionTypeSyntax.self, visit, visitPost) + visitImpl(&node, PackExpansionTypeSyntax.self, visit, visitPost) case .patternBindingList: - visitImpl(node, PatternBindingListSyntax.self, visit, visitPost) + visitImpl(&node, PatternBindingListSyntax.self, visit, visitPost) case .patternBinding: - visitImpl(node, PatternBindingSyntax.self, visit, visitPost) + visitImpl(&node, PatternBindingSyntax.self, visit, visitPost) case .patternExpr: - visitImpl(node, PatternExprSyntax.self, visit, visitPost) + visitImpl(&node, PatternExprSyntax.self, visit, visitPost) case .platformVersionItemList: - visitImpl(node, PlatformVersionItemListSyntax.self, visit, visitPost) + visitImpl(&node, PlatformVersionItemListSyntax.self, visit, visitPost) case .platformVersionItem: - visitImpl(node, PlatformVersionItemSyntax.self, visit, visitPost) + visitImpl(&node, PlatformVersionItemSyntax.self, visit, visitPost) case .platformVersion: - visitImpl(node, PlatformVersionSyntax.self, visit, visitPost) + visitImpl(&node, PlatformVersionSyntax.self, visit, visitPost) case .postfixIfConfigExpr: - visitImpl(node, PostfixIfConfigExprSyntax.self, visit, visitPost) + visitImpl(&node, PostfixIfConfigExprSyntax.self, visit, visitPost) case .postfixOperatorExpr: - visitImpl(node, PostfixOperatorExprSyntax.self, visit, visitPost) + visitImpl(&node, PostfixOperatorExprSyntax.self, visit, visitPost) case .poundSourceLocationArguments: - visitImpl(node, PoundSourceLocationArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, PoundSourceLocationArgumentsSyntax.self, visit, visitPost) case .poundSourceLocation: - visitImpl(node, PoundSourceLocationSyntax.self, visit, visitPost) + visitImpl(&node, PoundSourceLocationSyntax.self, visit, visitPost) case .precedenceGroupAssignment: - visitImpl(node, PrecedenceGroupAssignmentSyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupAssignmentSyntax.self, visit, visitPost) case .precedenceGroupAssociativity: - visitImpl(node, PrecedenceGroupAssociativitySyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupAssociativitySyntax.self, visit, visitPost) case .precedenceGroupAttributeList: - visitImpl(node, PrecedenceGroupAttributeListSyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupAttributeListSyntax.self, visit, visitPost) case .precedenceGroupDecl: - visitImpl(node, PrecedenceGroupDeclSyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupDeclSyntax.self, visit, visitPost) case .precedenceGroupNameList: - visitImpl(node, PrecedenceGroupNameListSyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupNameListSyntax.self, visit, visitPost) case .precedenceGroupName: - visitImpl(node, PrecedenceGroupNameSyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupNameSyntax.self, visit, visitPost) case .precedenceGroupRelation: - visitImpl(node, PrecedenceGroupRelationSyntax.self, visit, visitPost) + visitImpl(&node, PrecedenceGroupRelationSyntax.self, visit, visitPost) case .prefixOperatorExpr: - visitImpl(node, PrefixOperatorExprSyntax.self, visit, visitPost) + visitImpl(&node, PrefixOperatorExprSyntax.self, visit, visitPost) case .primaryAssociatedTypeClause: - visitImpl(node, PrimaryAssociatedTypeClauseSyntax.self, visit, visitPost) + visitImpl(&node, PrimaryAssociatedTypeClauseSyntax.self, visit, visitPost) case .primaryAssociatedTypeList: - visitImpl(node, PrimaryAssociatedTypeListSyntax.self, visit, visitPost) + visitImpl(&node, PrimaryAssociatedTypeListSyntax.self, visit, visitPost) case .primaryAssociatedType: - visitImpl(node, PrimaryAssociatedTypeSyntax.self, visit, visitPost) + visitImpl(&node, PrimaryAssociatedTypeSyntax.self, visit, visitPost) case .protocolDecl: - visitImpl(node, ProtocolDeclSyntax.self, visit, visitPost) + visitImpl(&node, ProtocolDeclSyntax.self, visit, visitPost) case .regexLiteralExpr: - visitImpl(node, RegexLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, RegexLiteralExprSyntax.self, visit, visitPost) case .repeatStmt: - visitImpl(node, RepeatStmtSyntax.self, visit, visitPost) + visitImpl(&node, RepeatStmtSyntax.self, visit, visitPost) case .returnClause: - visitImpl(node, ReturnClauseSyntax.self, visit, visitPost) + visitImpl(&node, ReturnClauseSyntax.self, visit, visitPost) case .returnStmt: - visitImpl(node, ReturnStmtSyntax.self, visit, visitPost) + visitImpl(&node, ReturnStmtSyntax.self, visit, visitPost) case .sameTypeRequirement: - visitImpl(node, SameTypeRequirementSyntax.self, visit, visitPost) + visitImpl(&node, SameTypeRequirementSyntax.self, visit, visitPost) case .sequenceExpr: - visitImpl(node, SequenceExprSyntax.self, visit, visitPost) + visitImpl(&node, SequenceExprSyntax.self, visit, visitPost) case .simpleStringLiteralExpr: - visitImpl(node, SimpleStringLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, SimpleStringLiteralExprSyntax.self, visit, visitPost) case .simpleStringLiteralSegmentList: - visitImpl(node, SimpleStringLiteralSegmentListSyntax.self, visit, visitPost) + visitImpl(&node, SimpleStringLiteralSegmentListSyntax.self, visit, visitPost) case .simpleTypeSpecifier: - visitImpl(node, SimpleTypeSpecifierSyntax.self, visit, visitPost) + visitImpl(&node, SimpleTypeSpecifierSyntax.self, visit, visitPost) case .someOrAnyType: - visitImpl(node, SomeOrAnyTypeSyntax.self, visit, visitPost) + visitImpl(&node, SomeOrAnyTypeSyntax.self, visit, visitPost) case .sourceFile: - visitImpl(node, SourceFileSyntax.self, visit, visitPost) + visitImpl(&node, SourceFileSyntax.self, visit, visitPost) case .specializeAttributeArgumentList: - visitImpl(node, SpecializeAttributeArgumentListSyntax.self, visit, visitPost) + visitImpl(&node, SpecializeAttributeArgumentListSyntax.self, visit, visitPost) case .specializeAvailabilityArgument: - visitImpl(node, SpecializeAvailabilityArgumentSyntax.self, visit, visitPost) + visitImpl(&node, SpecializeAvailabilityArgumentSyntax.self, visit, visitPost) case .specializeTargetFunctionArgument: - visitImpl(node, SpecializeTargetFunctionArgumentSyntax.self, visit, visitPost) + visitImpl(&node, SpecializeTargetFunctionArgumentSyntax.self, visit, visitPost) case .stringLiteralExpr: - visitImpl(node, StringLiteralExprSyntax.self, visit, visitPost) + visitImpl(&node, StringLiteralExprSyntax.self, visit, visitPost) case .stringLiteralSegmentList: - visitImpl(node, StringLiteralSegmentListSyntax.self, visit, visitPost) + visitImpl(&node, StringLiteralSegmentListSyntax.self, visit, visitPost) case .stringSegment: - visitImpl(node, StringSegmentSyntax.self, visit, visitPost) + visitImpl(&node, StringSegmentSyntax.self, visit, visitPost) case .structDecl: - visitImpl(node, StructDeclSyntax.self, visit, visitPost) + visitImpl(&node, StructDeclSyntax.self, visit, visitPost) case .subscriptCallExpr: - visitImpl(node, SubscriptCallExprSyntax.self, visit, visitPost) + visitImpl(&node, SubscriptCallExprSyntax.self, visit, visitPost) case .subscriptDecl: - visitImpl(node, SubscriptDeclSyntax.self, visit, visitPost) + visitImpl(&node, SubscriptDeclSyntax.self, visit, visitPost) case .superExpr: - visitImpl(node, SuperExprSyntax.self, visit, visitPost) + visitImpl(&node, SuperExprSyntax.self, visit, visitPost) case .suppressedType: - visitImpl(node, SuppressedTypeSyntax.self, visit, visitPost) + visitImpl(&node, SuppressedTypeSyntax.self, visit, visitPost) case .switchCaseItemList: - visitImpl(node, SwitchCaseItemListSyntax.self, visit, visitPost) + visitImpl(&node, SwitchCaseItemListSyntax.self, visit, visitPost) case .switchCaseItem: - visitImpl(node, SwitchCaseItemSyntax.self, visit, visitPost) + visitImpl(&node, SwitchCaseItemSyntax.self, visit, visitPost) case .switchCaseLabel: - visitImpl(node, SwitchCaseLabelSyntax.self, visit, visitPost) + visitImpl(&node, SwitchCaseLabelSyntax.self, visit, visitPost) case .switchCaseList: - visitImpl(node, SwitchCaseListSyntax.self, visit, visitPost) + visitImpl(&node, SwitchCaseListSyntax.self, visit, visitPost) case .switchCase: - visitImpl(node, SwitchCaseSyntax.self, visit, visitPost) + visitImpl(&node, SwitchCaseSyntax.self, visit, visitPost) case .switchDefaultLabel: - visitImpl(node, SwitchDefaultLabelSyntax.self, visit, visitPost) + visitImpl(&node, SwitchDefaultLabelSyntax.self, visit, visitPost) case .switchExpr: - visitImpl(node, SwitchExprSyntax.self, visit, visitPost) + visitImpl(&node, SwitchExprSyntax.self, visit, visitPost) case .ternaryExpr: - visitImpl(node, TernaryExprSyntax.self, visit, visitPost) + visitImpl(&node, TernaryExprSyntax.self, visit, visitPost) case .thenStmt: - visitImpl(node, ThenStmtSyntax.self, visit, visitPost) + visitImpl(&node, ThenStmtSyntax.self, visit, visitPost) case .throwStmt: - visitImpl(node, ThrowStmtSyntax.self, visit, visitPost) + visitImpl(&node, ThrowStmtSyntax.self, visit, visitPost) case .throwsClause: - visitImpl(node, ThrowsClauseSyntax.self, visit, visitPost) + visitImpl(&node, ThrowsClauseSyntax.self, visit, visitPost) case .tryExpr: - visitImpl(node, TryExprSyntax.self, visit, visitPost) + visitImpl(&node, TryExprSyntax.self, visit, visitPost) case .tupleExpr: - visitImpl(node, TupleExprSyntax.self, visit, visitPost) + visitImpl(&node, TupleExprSyntax.self, visit, visitPost) case .tuplePatternElementList: - visitImpl(node, TuplePatternElementListSyntax.self, visit, visitPost) + visitImpl(&node, TuplePatternElementListSyntax.self, visit, visitPost) case .tuplePatternElement: - visitImpl(node, TuplePatternElementSyntax.self, visit, visitPost) + visitImpl(&node, TuplePatternElementSyntax.self, visit, visitPost) case .tuplePattern: - visitImpl(node, TuplePatternSyntax.self, visit, visitPost) + visitImpl(&node, TuplePatternSyntax.self, visit, visitPost) case .tupleTypeElementList: - visitImpl(node, TupleTypeElementListSyntax.self, visit, visitPost) + visitImpl(&node, TupleTypeElementListSyntax.self, visit, visitPost) case .tupleTypeElement: - visitImpl(node, TupleTypeElementSyntax.self, visit, visitPost) + visitImpl(&node, TupleTypeElementSyntax.self, visit, visitPost) case .tupleType: - visitImpl(node, TupleTypeSyntax.self, visit, visitPost) + visitImpl(&node, TupleTypeSyntax.self, visit, visitPost) case .typeAliasDecl: - visitImpl(node, TypeAliasDeclSyntax.self, visit, visitPost) + visitImpl(&node, TypeAliasDeclSyntax.self, visit, visitPost) case .typeAnnotation: - visitImpl(node, TypeAnnotationSyntax.self, visit, visitPost) + visitImpl(&node, TypeAnnotationSyntax.self, visit, visitPost) case .typeEffectSpecifiers: - visitImpl(node, TypeEffectSpecifiersSyntax.self, visit, visitPost) + visitImpl(&node, TypeEffectSpecifiersSyntax.self, visit, visitPost) case .typeExpr: - visitImpl(node, TypeExprSyntax.self, visit, visitPost) + visitImpl(&node, TypeExprSyntax.self, visit, visitPost) case .typeInitializerClause: - visitImpl(node, TypeInitializerClauseSyntax.self, visit, visitPost) + visitImpl(&node, TypeInitializerClauseSyntax.self, visit, visitPost) case .typeSpecifierList: - visitImpl(node, TypeSpecifierListSyntax.self, visit, visitPost) + visitImpl(&node, TypeSpecifierListSyntax.self, visit, visitPost) case .unavailableFromAsyncAttributeArguments: - visitImpl(node, UnavailableFromAsyncAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, UnavailableFromAsyncAttributeArgumentsSyntax.self, visit, visitPost) case .underscorePrivateAttributeArguments: - visitImpl(node, UnderscorePrivateAttributeArgumentsSyntax.self, visit, visitPost) + visitImpl(&node, UnderscorePrivateAttributeArgumentsSyntax.self, visit, visitPost) case .unexpectedNodes: - visitImpl(node, UnexpectedNodesSyntax.self, visit, visitPost) + visitImpl(&node, UnexpectedNodesSyntax.self, visit, visitPost) case .unresolvedAsExpr: - visitImpl(node, UnresolvedAsExprSyntax.self, visit, visitPost) + visitImpl(&node, UnresolvedAsExprSyntax.self, visit, visitPost) case .unresolvedIsExpr: - visitImpl(node, UnresolvedIsExprSyntax.self, visit, visitPost) + visitImpl(&node, UnresolvedIsExprSyntax.self, visit, visitPost) case .unresolvedTernaryExpr: - visitImpl(node, UnresolvedTernaryExprSyntax.self, visit, visitPost) + visitImpl(&node, UnresolvedTernaryExprSyntax.self, visit, visitPost) case .valueBindingPattern: - visitImpl(node, ValueBindingPatternSyntax.self, visit, visitPost) + visitImpl(&node, ValueBindingPatternSyntax.self, visit, visitPost) case .variableDecl: - visitImpl(node, VariableDeclSyntax.self, visit, visitPost) + visitImpl(&node, VariableDeclSyntax.self, visit, visitPost) case .versionComponentList: - visitImpl(node, VersionComponentListSyntax.self, visit, visitPost) + visitImpl(&node, VersionComponentListSyntax.self, visit, visitPost) case .versionComponent: - visitImpl(node, VersionComponentSyntax.self, visit, visitPost) + visitImpl(&node, VersionComponentSyntax.self, visit, visitPost) case .versionTuple: - visitImpl(node, VersionTupleSyntax.self, visit, visitPost) + visitImpl(&node, VersionTupleSyntax.self, visit, visitPost) case .whereClause: - visitImpl(node, WhereClauseSyntax.self, visit, visitPost) + visitImpl(&node, WhereClauseSyntax.self, visit, visitPost) case .whileStmt: - visitImpl(node, WhileStmtSyntax.self, visit, visitPost) + visitImpl(&node, WhileStmtSyntax.self, visit, visitPost) case .wildcardPattern: - visitImpl(node, WildcardPatternSyntax.self, visit, visitPost) + visitImpl(&node, WildcardPatternSyntax.self, visit, visitPost) case .yieldStmt: - visitImpl(node, YieldStmtSyntax.self, visit, visitPost) + visitImpl(&node, YieldStmtSyntax.self, visit, visitPost) case .yieldedExpressionList: - visitImpl(node, YieldedExpressionListSyntax.self, visit, visitPost) + visitImpl(&node, YieldedExpressionListSyntax.self, visit, visitPost) case .yieldedExpression: - visitImpl(node, YieldedExpressionSyntax.self, visit, visitPost) + visitImpl(&node, YieldedExpressionSyntax.self, visit, visitPost) case .yieldedExpressionsClause: - visitImpl(node, YieldedExpressionsClauseSyntax.self, visit, visitPost) + visitImpl(&node, YieldedExpressionsClauseSyntax.self, visit, visitPost) } } #endif - private func visitChildren(_ node: some SyntaxProtocol) { - let syntaxNode = Syntax(node) - for childRaw in NonNilRawSyntaxChildren(syntaxNode, viewMode: viewMode) { - visit(Syntax(childRaw, parent: syntaxNode)) + /// - Note: `node` is `inout` to avoid reference counting. See comment in `visitImpl`. + private func visitChildren(_ node: inout Syntax) { + for case let (child?, info) in RawSyntaxChildren(node) where viewMode.shouldTraverse(node: child) { + var childNode = nodeFactory.create(parent: node, raw: child, absoluteInfo: info) + visit(&childNode) + nodeFactory.dispose(&childNode) } } } diff --git a/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesC.swift b/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesC.swift index be8f1764629..ba466a6adff 100644 --- a/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesC.swift +++ b/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesC.swift @@ -13,14 +13,14 @@ //===----------------------------------------------------------------------===// @_spi(RawSyntax) -public struct RawCanImportExprSyntax: RawExprSyntaxNodeProtocol { +public struct Raw_CanImportExprSyntax: RawExprSyntaxNodeProtocol { @_spi(RawSyntax) public var layoutView: RawSyntaxLayoutView { return raw.layoutView! } public static func isKindOf(_ raw: RawSyntax) -> Bool { - return raw.kind == .canImportExpr + return raw.kind == ._canImportExpr } public var raw: RawSyntax @@ -49,14 +49,14 @@ public struct RawCanImportExprSyntax: RawExprSyntaxNodeProtocol { _ unexpectedBetweenLeftParenAndImportPath: RawUnexpectedNodesSyntax? = nil, importPath: RawTokenSyntax, _ unexpectedBetweenImportPathAndVersionInfo: RawUnexpectedNodesSyntax? = nil, - versionInfo: RawCanImportVersionInfoSyntax?, + versionInfo: Raw_CanImportVersionInfoSyntax?, _ unexpectedBetweenVersionInfoAndRightParen: RawUnexpectedNodesSyntax? = nil, rightParen: RawTokenSyntax, _ unexpectedAfterRightParen: RawUnexpectedNodesSyntax? = nil, arena: __shared SyntaxArena ) { let raw = RawSyntax.makeLayout( - kind: .canImportExpr, uninitializedCount: 11, arena: arena) { layout in + kind: ._canImportExpr, uninitializedCount: 11, arena: arena) { layout in layout.initialize(repeating: nil) layout[0] = unexpectedBeforeCanImportKeyword?.raw layout[1] = canImportKeyword.raw @@ -101,8 +101,8 @@ public struct RawCanImportExprSyntax: RawExprSyntaxNodeProtocol { layoutView.children[6].map(RawUnexpectedNodesSyntax.init(raw:)) } - public var versionInfo: RawCanImportVersionInfoSyntax? { - layoutView.children[7].map(RawCanImportVersionInfoSyntax.init(raw:)) + public var versionInfo: Raw_CanImportVersionInfoSyntax? { + layoutView.children[7].map(Raw_CanImportVersionInfoSyntax.init(raw:)) } public var unexpectedBetweenVersionInfoAndRightParen: RawUnexpectedNodesSyntax? { @@ -119,14 +119,14 @@ public struct RawCanImportExprSyntax: RawExprSyntaxNodeProtocol { } @_spi(RawSyntax) -public struct RawCanImportVersionInfoSyntax: RawExprSyntaxNodeProtocol { +public struct Raw_CanImportVersionInfoSyntax: RawExprSyntaxNodeProtocol { @_spi(RawSyntax) public var layoutView: RawSyntaxLayoutView { return raw.layoutView! } public static func isKindOf(_ raw: RawSyntax) -> Bool { - return raw.kind == .canImportVersionInfo + return raw.kind == ._canImportVersionInfo } public var raw: RawSyntax @@ -160,7 +160,7 @@ public struct RawCanImportVersionInfoSyntax: RawExprSyntaxNodeProtocol { arena: __shared SyntaxArena ) { let raw = RawSyntax.makeLayout( - kind: .canImportVersionInfo, uninitializedCount: 9, arena: arena) { layout in + kind: ._canImportVersionInfo, uninitializedCount: 9, arena: arena) { layout in layout.initialize(repeating: nil) layout[0] = unexpectedBeforeComma?.raw layout[1] = comma.raw diff --git a/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesEF.swift b/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesEF.swift index 3b65d5be404..0ac329a0a14 100644 --- a/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesEF.swift +++ b/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesEF.swift @@ -988,7 +988,7 @@ public struct RawExprSyntax: RawExprSyntaxNodeProtocol { public static func isKindOf(_ raw: RawSyntax) -> Bool { switch raw.kind { - case .arrayExpr, .arrowExpr, .asExpr, .assignmentExpr, .awaitExpr, .binaryOperatorExpr, .booleanLiteralExpr, .borrowExpr, .canImportExpr, .canImportVersionInfo, .closureExpr, .consumeExpr, .copyExpr, .declReferenceExpr, .dictionaryExpr, .discardAssignmentExpr, .doExpr, .editorPlaceholderExpr, .floatLiteralExpr, .forceUnwrapExpr, .functionCallExpr, .genericSpecializationExpr, .ifExpr, .inOutExpr, .infixOperatorExpr, .integerLiteralExpr, .isExpr, .keyPathExpr, .macroExpansionExpr, .memberAccessExpr, .missingExpr, .nilLiteralExpr, .optionalChainingExpr, .packElementExpr, .packExpansionExpr, .patternExpr, .postfixIfConfigExpr, .postfixOperatorExpr, .prefixOperatorExpr, .regexLiteralExpr, .sequenceExpr, .simpleStringLiteralExpr, .stringLiteralExpr, .subscriptCallExpr, .superExpr, .switchExpr, .ternaryExpr, .tryExpr, .tupleExpr, .typeExpr, .unresolvedAsExpr, .unresolvedIsExpr, .unresolvedTernaryExpr: + case .arrayExpr, .arrowExpr, .asExpr, .assignmentExpr, .awaitExpr, .binaryOperatorExpr, .booleanLiteralExpr, .borrowExpr, ._canImportExpr, ._canImportVersionInfo, .closureExpr, .consumeExpr, .copyExpr, .declReferenceExpr, .dictionaryExpr, .discardAssignmentExpr, .doExpr, .editorPlaceholderExpr, .floatLiteralExpr, .forceUnwrapExpr, .functionCallExpr, .genericSpecializationExpr, .ifExpr, .inOutExpr, .infixOperatorExpr, .integerLiteralExpr, .isExpr, .keyPathExpr, .macroExpansionExpr, .memberAccessExpr, .missingExpr, .nilLiteralExpr, .optionalChainingExpr, .packElementExpr, .packExpansionExpr, .patternExpr, .postfixIfConfigExpr, .postfixOperatorExpr, .prefixOperatorExpr, .regexLiteralExpr, .sequenceExpr, .simpleStringLiteralExpr, .stringLiteralExpr, .subscriptCallExpr, .superExpr, .switchExpr, .ternaryExpr, .tryExpr, .tupleExpr, .typeExpr, .unresolvedAsExpr, .unresolvedIsExpr, .unresolvedTernaryExpr: return true default: return false diff --git a/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesJKLMN.swift b/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesJKLMN.swift index d5e9ab34c9d..18adc64115b 100644 --- a/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesJKLMN.swift +++ b/Sources/SwiftSyntax/generated/raw/RawSyntaxNodesJKLMN.swift @@ -1053,14 +1053,14 @@ public struct RawLifetimeSpecifierArgumentSyntax: RawSyntaxNodeProtocol { @_spi(ExperimentalLanguageFeatures) #endif @_spi(RawSyntax) -public struct RawLifetimeSpecifierArgumentsSyntax: RawSyntaxNodeProtocol { +public struct RawLifetimeTypeSpecifierSyntax: RawSyntaxNodeProtocol { @_spi(RawSyntax) public var layoutView: RawSyntaxLayoutView { return raw.layoutView! } public static func isKindOf(_ raw: RawSyntax) -> Bool { - return raw.kind == .lifetimeSpecifierArguments + return raw.kind == .lifetimeTypeSpecifier } public var raw: RawSyntax @@ -1082,9 +1082,13 @@ public struct RawLifetimeSpecifierArgumentsSyntax: RawSyntaxNodeProtocol { } public init( - _ unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax? = nil, + _ unexpectedBeforeDependsOnKeyword: RawUnexpectedNodesSyntax? = nil, + dependsOnKeyword: RawTokenSyntax, + _ unexpectedBetweenDependsOnKeywordAndLeftParen: RawUnexpectedNodesSyntax? = nil, leftParen: RawTokenSyntax, - _ unexpectedBetweenLeftParenAndArguments: RawUnexpectedNodesSyntax? = nil, + _ unexpectedBetweenLeftParenAndScopedKeyword: RawUnexpectedNodesSyntax? = nil, + scopedKeyword: RawTokenSyntax?, + _ unexpectedBetweenScopedKeywordAndArguments: RawUnexpectedNodesSyntax? = nil, arguments: RawLifetimeSpecifierArgumentListSyntax, _ unexpectedBetweenArgumentsAndRightParen: RawUnexpectedNodesSyntax? = nil, rightParen: RawTokenSyntax, @@ -1092,118 +1096,65 @@ public struct RawLifetimeSpecifierArgumentsSyntax: RawSyntaxNodeProtocol { arena: __shared SyntaxArena ) { let raw = RawSyntax.makeLayout( - kind: .lifetimeSpecifierArguments, uninitializedCount: 7, arena: arena) { layout in + kind: .lifetimeTypeSpecifier, uninitializedCount: 11, arena: arena) { layout in layout.initialize(repeating: nil) - layout[0] = unexpectedBeforeLeftParen?.raw - layout[1] = leftParen.raw - layout[2] = unexpectedBetweenLeftParenAndArguments?.raw - layout[3] = arguments.raw - layout[4] = unexpectedBetweenArgumentsAndRightParen?.raw - layout[5] = rightParen.raw - layout[6] = unexpectedAfterRightParen?.raw + layout[0] = unexpectedBeforeDependsOnKeyword?.raw + layout[1] = dependsOnKeyword.raw + layout[2] = unexpectedBetweenDependsOnKeywordAndLeftParen?.raw + layout[3] = leftParen.raw + layout[4] = unexpectedBetweenLeftParenAndScopedKeyword?.raw + layout[5] = scopedKeyword?.raw + layout[6] = unexpectedBetweenScopedKeywordAndArguments?.raw + layout[7] = arguments.raw + layout[8] = unexpectedBetweenArgumentsAndRightParen?.raw + layout[9] = rightParen.raw + layout[10] = unexpectedAfterRightParen?.raw } self.init(unchecked: raw) } - public var unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax? { + public var unexpectedBeforeDependsOnKeyword: RawUnexpectedNodesSyntax? { layoutView.children[0].map(RawUnexpectedNodesSyntax.init(raw:)) } - public var leftParen: RawTokenSyntax { + public var dependsOnKeyword: RawTokenSyntax { layoutView.children[1].map(RawTokenSyntax.init(raw:))! } - public var unexpectedBetweenLeftParenAndArguments: RawUnexpectedNodesSyntax? { + public var unexpectedBetweenDependsOnKeywordAndLeftParen: RawUnexpectedNodesSyntax? { layoutView.children[2].map(RawUnexpectedNodesSyntax.init(raw:)) } - public var arguments: RawLifetimeSpecifierArgumentListSyntax { - layoutView.children[3].map(RawLifetimeSpecifierArgumentListSyntax.init(raw:))! + public var leftParen: RawTokenSyntax { + layoutView.children[3].map(RawTokenSyntax.init(raw:))! } - public var unexpectedBetweenArgumentsAndRightParen: RawUnexpectedNodesSyntax? { + public var unexpectedBetweenLeftParenAndScopedKeyword: RawUnexpectedNodesSyntax? { layoutView.children[4].map(RawUnexpectedNodesSyntax.init(raw:)) } - public var rightParen: RawTokenSyntax { - layoutView.children[5].map(RawTokenSyntax.init(raw:))! + public var scopedKeyword: RawTokenSyntax? { + layoutView.children[5].map(RawTokenSyntax.init(raw:)) } - public var unexpectedAfterRightParen: RawUnexpectedNodesSyntax? { + public var unexpectedBetweenScopedKeywordAndArguments: RawUnexpectedNodesSyntax? { layoutView.children[6].map(RawUnexpectedNodesSyntax.init(raw:)) } -} - -#if compiler(>=5.8) -@_spi(ExperimentalLanguageFeatures) -#endif -@_spi(RawSyntax) -public struct RawLifetimeTypeSpecifierSyntax: RawSyntaxNodeProtocol { - @_spi(RawSyntax) - public var layoutView: RawSyntaxLayoutView { - return raw.layoutView! - } - - public static func isKindOf(_ raw: RawSyntax) -> Bool { - return raw.kind == .lifetimeTypeSpecifier - } - - public var raw: RawSyntax - - init(raw: RawSyntax) { - precondition(Self.isKindOf(raw)) - self.raw = raw - } - - private init(unchecked raw: RawSyntax) { - self.raw = raw - } - - public init?(_ other: some RawSyntaxNodeProtocol) { - guard Self.isKindOf(other.raw) else { - return nil - } - self.init(unchecked: other.raw) - } - - public init( - _ unexpectedBeforeSpecifier: RawUnexpectedNodesSyntax? = nil, - specifier: RawTokenSyntax, - _ unexpectedBetweenSpecifierAndArguments: RawUnexpectedNodesSyntax? = nil, - arguments: RawLifetimeSpecifierArgumentsSyntax, - _ unexpectedAfterArguments: RawUnexpectedNodesSyntax? = nil, - arena: __shared SyntaxArena - ) { - let raw = RawSyntax.makeLayout( - kind: .lifetimeTypeSpecifier, uninitializedCount: 5, arena: arena) { layout in - layout.initialize(repeating: nil) - layout[0] = unexpectedBeforeSpecifier?.raw - layout[1] = specifier.raw - layout[2] = unexpectedBetweenSpecifierAndArguments?.raw - layout[3] = arguments.raw - layout[4] = unexpectedAfterArguments?.raw - } - self.init(unchecked: raw) - } - public var unexpectedBeforeSpecifier: RawUnexpectedNodesSyntax? { - layoutView.children[0].map(RawUnexpectedNodesSyntax.init(raw:)) - } - - public var specifier: RawTokenSyntax { - layoutView.children[1].map(RawTokenSyntax.init(raw:))! + public var arguments: RawLifetimeSpecifierArgumentListSyntax { + layoutView.children[7].map(RawLifetimeSpecifierArgumentListSyntax.init(raw:))! } - public var unexpectedBetweenSpecifierAndArguments: RawUnexpectedNodesSyntax? { - layoutView.children[2].map(RawUnexpectedNodesSyntax.init(raw:)) + public var unexpectedBetweenArgumentsAndRightParen: RawUnexpectedNodesSyntax? { + layoutView.children[8].map(RawUnexpectedNodesSyntax.init(raw:)) } - public var arguments: RawLifetimeSpecifierArgumentsSyntax { - layoutView.children[3].map(RawLifetimeSpecifierArgumentsSyntax.init(raw:))! + public var rightParen: RawTokenSyntax { + layoutView.children[9].map(RawTokenSyntax.init(raw:))! } - public var unexpectedAfterArguments: RawUnexpectedNodesSyntax? { - layoutView.children[4].map(RawUnexpectedNodesSyntax.init(raw:)) + public var unexpectedAfterRightParen: RawUnexpectedNodesSyntax? { + layoutView.children[10].map(RawUnexpectedNodesSyntax.init(raw:)) } } diff --git a/Sources/SwiftSyntax/generated/raw/RawSyntaxValidation.swift b/Sources/SwiftSyntax/generated/raw/RawSyntaxValidation.swift index 8d22721337f..0ea86afdd76 100644 --- a/Sources/SwiftSyntax/generated/raw/RawSyntaxValidation.swift +++ b/Sources/SwiftSyntax/generated/raw/RawSyntaxValidation.swift @@ -464,7 +464,7 @@ func validateLayout(layout: RawSyntaxBuffer, as kind: SyntaxKind) { assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 3, verify(layout[3], as: RawTokenSyntax?.self, tokenChoices: [.tokenKind(.identifier)])) assertNoError(kind, 4, verify(layout[4], as: RawUnexpectedNodesSyntax?.self)) - case .canImportExpr: + case ._canImportExpr: assert(layout.count == 11) assertNoError(kind, 0, verify(layout[0], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 1, verify(layout[1], as: RawTokenSyntax.self, tokenChoices: [.keyword("canImport")])) @@ -473,11 +473,11 @@ func validateLayout(layout: RawSyntaxBuffer, as kind: SyntaxKind) { assertNoError(kind, 4, verify(layout[4], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 5, verify(layout[5], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.identifier)])) assertNoError(kind, 6, verify(layout[6], as: RawUnexpectedNodesSyntax?.self)) - assertNoError(kind, 7, verify(layout[7], as: RawCanImportVersionInfoSyntax?.self)) + assertNoError(kind, 7, verify(layout[7], as: Raw_CanImportVersionInfoSyntax?.self)) assertNoError(kind, 8, verify(layout[8], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 9, verify(layout[9], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.rightParen)])) assertNoError(kind, 10, verify(layout[10], as: RawUnexpectedNodesSyntax?.self)) - case .canImportVersionInfo: + case ._canImportVersionInfo: assert(layout.count == 9) assertNoError(kind, 0, verify(layout[0], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 1, verify(layout[1], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.comma)])) @@ -797,9 +797,9 @@ func validateLayout(layout: RawSyntaxBuffer, as kind: SyntaxKind) { .keyword("_resultDependsOnSelf"), .keyword("required"), .keyword("static"), - .keyword("transferring"), .keyword("unowned"), - .keyword("weak") + .keyword("weak"), + .keyword("sending") ])) assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 3, verify(layout[3], as: RawDeclModifierDetailSyntax?.self)) @@ -1725,27 +1725,19 @@ func validateLayout(layout: RawSyntaxBuffer, as kind: SyntaxKind) { assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 3, verify(layout[3], as: RawTokenSyntax?.self, tokenChoices: [.tokenKind(.comma)])) assertNoError(kind, 4, verify(layout[4], as: RawUnexpectedNodesSyntax?.self)) - case .lifetimeSpecifierArguments: - assert(layout.count == 7) - assertNoError(kind, 0, verify(layout[0], as: RawUnexpectedNodesSyntax?.self)) - assertNoError(kind, 1, verify(layout[1], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.leftParen)])) - assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) - assertNoError(kind, 3, verify(layout[3], as: RawLifetimeSpecifierArgumentListSyntax.self)) - assertNoError(kind, 4, verify(layout[4], as: RawUnexpectedNodesSyntax?.self)) - assertNoError(kind, 5, verify(layout[5], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.rightParen)])) - assertNoError(kind, 6, verify(layout[6], as: RawUnexpectedNodesSyntax?.self)) case .lifetimeTypeSpecifier: - assert(layout.count == 5) + assert(layout.count == 11) assertNoError(kind, 0, verify(layout[0], as: RawUnexpectedNodesSyntax?.self)) - assertNoError(kind, 1, verify(layout[1], as: RawTokenSyntax.self, tokenChoices: [ - .keyword("_copy"), - .keyword("_consume"), - .keyword("_borrow"), - .keyword("_mutate") - ])) + assertNoError(kind, 1, verify(layout[1], as: RawTokenSyntax.self, tokenChoices: [.keyword("dependsOn")])) assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) - assertNoError(kind, 3, verify(layout[3], as: RawLifetimeSpecifierArgumentsSyntax.self)) + assertNoError(kind, 3, verify(layout[3], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.leftParen)])) assertNoError(kind, 4, verify(layout[4], as: RawUnexpectedNodesSyntax?.self)) + assertNoError(kind, 5, verify(layout[5], as: RawTokenSyntax?.self, tokenChoices: [.keyword("scoped")])) + assertNoError(kind, 6, verify(layout[6], as: RawUnexpectedNodesSyntax?.self)) + assertNoError(kind, 7, verify(layout[7], as: RawLifetimeSpecifierArgumentListSyntax.self)) + assertNoError(kind, 8, verify(layout[8], as: RawUnexpectedNodesSyntax?.self)) + assertNoError(kind, 9, verify(layout[9], as: RawTokenSyntax.self, tokenChoices: [.tokenKind(.rightParen)])) + assertNoError(kind, 10, verify(layout[10], as: RawUnexpectedNodesSyntax?.self)) case .macroDecl: assert(layout.count == 17) assertNoError(kind, 0, verify(layout[0], as: RawUnexpectedNodesSyntax?.self)) @@ -2305,8 +2297,8 @@ func validateLayout(layout: RawSyntaxBuffer, as kind: SyntaxKind) { .keyword("_const"), .keyword("borrowing"), .keyword("consuming"), - .keyword("transferring"), - .keyword("_resultDependsOn") + .keyword("_resultDependsOn"), + .keyword("sending") ])) assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) case .someOrAnyType: @@ -2714,7 +2706,8 @@ func validateLayout(layout: RawSyntaxBuffer, as kind: SyntaxKind) { .keyword("inout"), .keyword("_mutating"), .keyword("_borrowing"), - .keyword("_consuming") + .keyword("_consuming"), + .keyword("borrowing") ])) assertNoError(kind, 2, verify(layout[2], as: RawUnexpectedNodesSyntax?.self)) assertNoError(kind, 3, verify(layout[3], as: RawPatternSyntax.self)) diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesAB.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesAB.swift index 88645b6cba8..136a9cf9237 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesAB.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesAB.swift @@ -46,7 +46,7 @@ public struct AccessorBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo self = .getter(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(AccessorDeclListSyntax.self) { self = .accessors(node) return @@ -109,7 +109,7 @@ public struct AccessorBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .accessorBlock else { return nil } @@ -238,17 +238,15 @@ public struct AccessorBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftBrace, - \Self.leftBrace, - \Self.unexpectedBetweenLeftBraceAndAccessors, - \Self.accessors, - \Self.unexpectedBetweenAccessorsAndRightBrace, - \Self.rightBrace, - \Self.unexpectedAfterRightBrace - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftBrace, + \Self.leftBrace, + \Self.unexpectedBetweenLeftBraceAndAccessors, + \Self.accessors, + \Self.unexpectedBetweenAccessorsAndRightBrace, + \Self.rightBrace, + \Self.unexpectedAfterRightBrace + ]) } // MARK: - AccessorDeclSyntax @@ -268,7 +266,7 @@ public struct AccessorBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo public struct AccessorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .accessorDecl else { return nil } @@ -500,23 +498,21 @@ public struct AccessorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifier, - \Self.modifier, - \Self.unexpectedBetweenModifierAndAccessorSpecifier, - \Self.accessorSpecifier, - \Self.unexpectedBetweenAccessorSpecifierAndParameters, - \Self.parameters, - \Self.unexpectedBetweenParametersAndEffectSpecifiers, - \Self.effectSpecifiers, - \Self.unexpectedBetweenEffectSpecifiersAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifier, + \Self.modifier, + \Self.unexpectedBetweenModifierAndAccessorSpecifier, + \Self.accessorSpecifier, + \Self.unexpectedBetweenAccessorSpecifierAndParameters, + \Self.parameters, + \Self.unexpectedBetweenParametersAndEffectSpecifiers, + \Self.effectSpecifiers, + \Self.unexpectedBetweenEffectSpecifiersAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - AccessorEffectSpecifiersSyntax @@ -532,7 +528,7 @@ public struct AccessorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS public struct AccessorEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .accessorEffectSpecifiers else { return nil } @@ -633,15 +629,13 @@ public struct AccessorEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAsyncSpecifier, - \Self.asyncSpecifier, - \Self.unexpectedBetweenAsyncSpecifierAndThrowsClause, - \Self.throwsClause, - \Self.unexpectedAfterThrowsClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAsyncSpecifier, + \Self.asyncSpecifier, + \Self.unexpectedBetweenAsyncSpecifierAndThrowsClause, + \Self.throwsClause, + \Self.unexpectedAfterThrowsClause + ]) } // MARK: - AccessorParametersSyntax @@ -658,7 +652,7 @@ public struct AccessorEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _L public struct AccessorParametersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .accessorParameters else { return nil } @@ -784,17 +778,15 @@ public struct AccessorParametersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndName, - \Self.name, - \Self.unexpectedBetweenNameAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndName, + \Self.name, + \Self.unexpectedBetweenNameAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - ActorDeclSyntax @@ -812,7 +804,7 @@ public struct AccessorParametersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn public struct ActorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .actorDecl else { return nil } @@ -1121,27 +1113,25 @@ public struct ActorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndActorKeyword, - \Self.actorKeyword, - \Self.unexpectedBetweenActorKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, - \Self.memberBlock, - \Self.unexpectedAfterMemberBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndActorKeyword, + \Self.actorKeyword, + \Self.unexpectedBetweenActorKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, + \Self.memberBlock, + \Self.unexpectedAfterMemberBlock + ]) } // MARK: - ArrayElementSyntax @@ -1159,7 +1149,7 @@ public struct ActorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynt public struct ArrayElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .arrayElement else { return nil } @@ -1255,15 +1245,13 @@ public struct ArrayElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ArrayExprSyntax @@ -1278,7 +1266,7 @@ public struct ArrayElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod public struct ArrayExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .arrayExpr else { return nil } @@ -1428,17 +1416,15 @@ public struct ArrayExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndElements, - \Self.elements, - \Self.unexpectedBetweenElementsAndRightSquare, - \Self.rightSquare, - \Self.unexpectedAfterRightSquare - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndElements, + \Self.elements, + \Self.unexpectedBetweenElementsAndRightSquare, + \Self.rightSquare, + \Self.unexpectedAfterRightSquare + ]) } // MARK: - ArrayTypeSyntax @@ -1451,7 +1437,7 @@ public struct ArrayExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt public struct ArrayTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .arrayType else { return nil } @@ -1574,17 +1560,15 @@ public struct ArrayTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndElement, - \Self.element, - \Self.unexpectedBetweenElementAndRightSquare, - \Self.rightSquare, - \Self.unexpectedAfterRightSquare - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndElement, + \Self.element, + \Self.unexpectedBetweenElementAndRightSquare, + \Self.rightSquare, + \Self.unexpectedAfterRightSquare + ]) } // MARK: - ArrowExprSyntax @@ -1606,7 +1590,7 @@ public struct ArrayTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSynt public struct ArrowExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .arrowExpr else { return nil } @@ -1702,15 +1686,13 @@ public struct ArrowExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeEffectSpecifiers, - \Self.effectSpecifiers, - \Self.unexpectedBetweenEffectSpecifiersAndArrow, - \Self.arrow, - \Self.unexpectedAfterArrow - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeEffectSpecifiers, + \Self.effectSpecifiers, + \Self.unexpectedBetweenEffectSpecifiersAndArrow, + \Self.arrow, + \Self.unexpectedAfterArrow + ]) } // MARK: - AsExprSyntax @@ -1739,7 +1721,7 @@ public struct ArrowExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt public struct AsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .asExpr else { return nil } @@ -1888,19 +1870,17 @@ public struct AsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndAsKeyword, - \Self.asKeyword, - \Self.unexpectedBetweenAsKeywordAndQuestionOrExclamationMark, - \Self.questionOrExclamationMark, - \Self.unexpectedBetweenQuestionOrExclamationMarkAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndAsKeyword, + \Self.asKeyword, + \Self.unexpectedBetweenAsKeywordAndQuestionOrExclamationMark, + \Self.questionOrExclamationMark, + \Self.unexpectedBetweenQuestionOrExclamationMarkAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } // MARK: - AssignmentExprSyntax @@ -1911,7 +1891,7 @@ public struct AsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN public struct AssignmentExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .assignmentExpr else { return nil } @@ -1975,9 +1955,7 @@ public struct AssignmentExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeEqual, \Self.equal, \Self.unexpectedAfterEqual]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeEqual, \Self.equal, \Self.unexpectedAfterEqual]) } // MARK: - AssociatedTypeDeclSyntax @@ -2020,7 +1998,7 @@ public struct AssignmentExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp public struct AssociatedTypeDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .associatedTypeDecl else { return nil } @@ -2309,25 +2287,23 @@ public struct AssociatedTypeDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndAssociatedtypeKeyword, - \Self.associatedtypeKeyword, - \Self.unexpectedBetweenAssociatedtypeKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndInitializer, - \Self.initializer, - \Self.unexpectedBetweenInitializerAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedAfterGenericWhereClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndAssociatedtypeKeyword, + \Self.associatedtypeKeyword, + \Self.unexpectedBetweenAssociatedtypeKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndInitializer, + \Self.initializer, + \Self.unexpectedBetweenInitializerAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedAfterGenericWhereClause + ]) } // MARK: - AttributeSyntax @@ -2494,7 +2470,7 @@ public struct AttributeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr self = .documentationArguments(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(LabeledExprListSyntax.self) { self = .argumentList(node) return @@ -3046,7 +3022,7 @@ public struct AttributeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .attribute else { return nil } @@ -3236,21 +3212,19 @@ public struct AttributeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAtSign, - \Self.atSign, - \Self.unexpectedBetweenAtSignAndAttributeName, - \Self.attributeName, - \Self.unexpectedBetweenAttributeNameAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAtSign, + \Self.atSign, + \Self.unexpectedBetweenAtSignAndAttributeName, + \Self.attributeName, + \Self.unexpectedBetweenAttributeNameAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - AttributedTypeSyntax @@ -3263,7 +3237,7 @@ public struct AttributeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr public struct AttributedTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .attributedType else { return nil } @@ -3440,17 +3414,15 @@ public struct AttributedTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTyp } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSpecifiers, - \Self.specifiers, - \Self.unexpectedBetweenSpecifiersAndAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndBaseType, - \Self.baseType, - \Self.unexpectedAfterBaseType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeSpecifiers, + \Self.specifiers, + \Self.unexpectedBetweenSpecifiersAndAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndBaseType, + \Self.baseType, + \Self.unexpectedAfterBaseType + ]) } // MARK: - AvailabilityArgumentSyntax @@ -3494,7 +3466,7 @@ public struct AvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafS self = .availabilityLabeledArgument(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(TokenSyntax.self) { self = .token(node) return @@ -3583,7 +3555,7 @@ public struct AvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafS public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .availabilityArgument else { return nil } @@ -3684,15 +3656,13 @@ public struct AvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeArgument, - \Self.argument, - \Self.unexpectedBetweenArgumentAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeArgument, + \Self.argument, + \Self.unexpectedBetweenArgumentAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - AvailabilityConditionSyntax @@ -3710,7 +3680,7 @@ public struct AvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafS public struct AvailabilityConditionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .availabilityCondition else { return nil } @@ -3889,19 +3859,17 @@ public struct AvailabilityConditionSyntax: SyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAvailabilityKeyword, - \Self.availabilityKeyword, - \Self.unexpectedBetweenAvailabilityKeywordAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndAvailabilityArguments, - \Self.availabilityArguments, - \Self.unexpectedBetweenAvailabilityArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAvailabilityKeyword, + \Self.availabilityKeyword, + \Self.unexpectedBetweenAvailabilityKeywordAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndAvailabilityArguments, + \Self.availabilityArguments, + \Self.unexpectedBetweenAvailabilityArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - AvailabilityLabeledArgumentSyntax @@ -3939,7 +3907,7 @@ public struct AvailabilityLabeledArgumentSyntax: SyntaxProtocol, SyntaxHashable, self = .version(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(SimpleStringLiteralExprSyntax.self) { self = .string(node) return @@ -4002,7 +3970,7 @@ public struct AvailabilityLabeledArgumentSyntax: SyntaxProtocol, SyntaxHashable, public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .availabilityLabeledArgument else { return nil } @@ -4138,17 +4106,15 @@ public struct AvailabilityLabeledArgumentSyntax: SyntaxProtocol, SyntaxHashable, } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedAfterValue - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedAfterValue + ]) } // MARK: - AwaitExprSyntax @@ -4160,7 +4126,7 @@ public struct AvailabilityLabeledArgumentSyntax: SyntaxProtocol, SyntaxHashable, public struct AwaitExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .awaitExpr else { return nil } @@ -4256,15 +4222,13 @@ public struct AwaitExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAwaitKeyword, - \Self.awaitKeyword, - \Self.unexpectedBetweenAwaitKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAwaitKeyword, + \Self.awaitKeyword, + \Self.unexpectedBetweenAwaitKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - BackDeployedAttributeArgumentsSyntax @@ -4283,7 +4247,7 @@ public struct AwaitExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt public struct BackDeployedAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .backDeployedAttributeArguments else { return nil } @@ -4441,17 +4405,15 @@ public struct BackDeployedAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashab } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBeforeLabel, - \Self.beforeLabel, - \Self.unexpectedBetweenBeforeLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndPlatforms, - \Self.platforms, - \Self.unexpectedAfterPlatforms - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBeforeLabel, + \Self.beforeLabel, + \Self.unexpectedBetweenBeforeLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndPlatforms, + \Self.platforms, + \Self.unexpectedAfterPlatforms + ]) } // MARK: - BinaryOperatorExprSyntax @@ -4468,7 +4430,7 @@ public struct BackDeployedAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashab public struct BinaryOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .binaryOperatorExpr else { return nil } @@ -4532,9 +4494,7 @@ public struct BinaryOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeOperator, \Self.operator, \Self.unexpectedAfterOperator]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeOperator, \Self.operator, \Self.unexpectedAfterOperator]) } // MARK: - BooleanLiteralExprSyntax @@ -4545,7 +4505,7 @@ public struct BinaryOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea public struct BooleanLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .booleanLiteralExpr else { return nil } @@ -4611,9 +4571,7 @@ public struct BooleanLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeLiteral, \Self.literal, \Self.unexpectedAfterLiteral]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeLiteral, \Self.literal, \Self.unexpectedAfterLiteral]) } // MARK: - BorrowExprSyntax @@ -4625,7 +4583,7 @@ public struct BooleanLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea public struct BorrowExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .borrowExpr else { return nil } @@ -4721,15 +4679,13 @@ public struct BorrowExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBorrowKeyword, - \Self.borrowKeyword, - \Self.unexpectedBetweenBorrowKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBorrowKeyword, + \Self.borrowKeyword, + \Self.unexpectedBetweenBorrowKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - BreakStmtSyntax @@ -4741,7 +4697,7 @@ public struct BorrowExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyn public struct BreakStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .breakStmt else { return nil } @@ -4840,13 +4796,11 @@ public struct BreakStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBreakKeyword, - \Self.breakKeyword, - \Self.unexpectedBetweenBreakKeywordAndLabel, - \Self.label, - \Self.unexpectedAfterLabel - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBreakKeyword, + \Self.breakKeyword, + \Self.unexpectedBetweenBreakKeywordAndLabel, + \Self.label, + \Self.unexpectedAfterLabel + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesC.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesC.swift index 7fd92ff992c..bfdce0dd3ce 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesC.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesC.swift @@ -12,20 +12,20 @@ // //===----------------------------------------------------------------------===// -// MARK: - CanImportExprSyntax +// MARK: - _CanImportExprSyntax /// ### Children /// /// - `canImportKeyword`: `canImport` /// - `leftParen`: `(` /// - `importPath`: `` -/// - `versionInfo`: ``CanImportVersionInfoSyntax``? +/// - `versionInfo`: `_CanImportVersionInfoSyntax`? /// - `rightParen`: `)` -public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { +public struct _CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { - guard node.raw.kind == .canImportExpr else { + public init?(_ node: __shared some SyntaxProtocol) { + guard node.raw.kind == ._canImportExpr else { return nil } self._syntaxNode = node._syntaxNode @@ -43,7 +43,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr _ unexpectedBetweenLeftParenAndImportPath: UnexpectedNodesSyntax? = nil, importPath: TokenSyntax, _ unexpectedBetweenImportPathAndVersionInfo: UnexpectedNodesSyntax? = nil, - versionInfo: CanImportVersionInfoSyntax? = nil, + versionInfo: _CanImportVersionInfoSyntax? = nil, _ unexpectedBetweenVersionInfoAndRightParen: UnexpectedNodesSyntax? = nil, rightParen: TokenSyntax = .rightParenToken(), _ unexpectedAfterRightParen: UnexpectedNodesSyntax? = nil, @@ -79,7 +79,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr unexpectedAfterRightParen?.raw ] let raw = RawSyntax.makeLayout( - kind: SyntaxKind.canImportExpr, + kind: SyntaxKind._canImportExpr, from: layout, arena: arena, leadingTrivia: leadingTrivia, @@ -95,7 +95,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 0)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -107,7 +107,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -116,7 +116,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 2)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -128,7 +128,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 3)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -137,7 +137,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 4)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -149,7 +149,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 5)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 5, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 5, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -158,16 +158,16 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 6)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 6, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 6, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } - public var versionInfo: CanImportVersionInfoSyntax? { + public var versionInfo: _CanImportVersionInfoSyntax? { get { - return Syntax(self).child(at: 7)?.cast(CanImportVersionInfoSyntax.self) + return Syntax(self).child(at: 7)?.cast(_CanImportVersionInfoSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 7, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 7, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -176,7 +176,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 8)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 8, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 8, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -188,7 +188,7 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 9)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 9, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 9, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } @@ -197,28 +197,26 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr return Syntax(self).child(at: 10)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 10, with: Syntax(value), arena: SyntaxArena()).cast(CanImportExprSyntax.self) + self = Syntax(self).replacingChild(at: 10, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportExprSyntax.self) } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCanImportKeyword, - \Self.canImportKeyword, - \Self.unexpectedBetweenCanImportKeywordAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndImportPath, - \Self.importPath, - \Self.unexpectedBetweenImportPathAndVersionInfo, - \Self.versionInfo, - \Self.unexpectedBetweenVersionInfoAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCanImportKeyword, + \Self.canImportKeyword, + \Self.unexpectedBetweenCanImportKeywordAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndImportPath, + \Self.importPath, + \Self.unexpectedBetweenImportPathAndVersionInfo, + \Self.versionInfo, + \Self.unexpectedBetweenVersionInfoAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } -// MARK: - CanImportVersionInfoSyntax +// MARK: - _CanImportVersionInfoSyntax /// ### Children /// @@ -229,12 +227,12 @@ public struct CanImportExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExpr /// /// ### Contained in /// -/// - ``CanImportExprSyntax``.``CanImportExprSyntax/versionInfo`` -public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { +/// - `_CanImportExprSyntax`.`_CanImportExprSyntax/versionInfo` +public struct _CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { - guard node.raw.kind == .canImportVersionInfo else { + public init?(_ node: __shared some SyntaxProtocol) { + guard node.raw.kind == ._canImportVersionInfo else { return nil } self._syntaxNode = node._syntaxNode @@ -282,7 +280,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L unexpectedAfterVersion?.raw ] let raw = RawSyntax.makeLayout( - kind: SyntaxKind.canImportVersionInfo, + kind: SyntaxKind._canImportVersionInfo, from: layout, arena: arena, leadingTrivia: leadingTrivia, @@ -298,7 +296,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 0)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -310,7 +308,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -319,7 +317,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 2)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -333,7 +331,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 3)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -342,7 +340,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 4)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -354,7 +352,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 5)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 5, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 5, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -363,7 +361,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 6)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 6, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 6, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -372,7 +370,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 7)!.cast(VersionTupleSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 7, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 7, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } @@ -381,23 +379,21 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L return Syntax(self).child(at: 8)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 8, with: Syntax(value), arena: SyntaxArena()).cast(CanImportVersionInfoSyntax.self) + self = Syntax(self).replacingChild(at: 8, with: Syntax(value), arena: SyntaxArena()).cast(_CanImportVersionInfoSyntax.self) } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndVersion, - \Self.version, - \Self.unexpectedAfterVersion - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndVersion, + \Self.version, + \Self.unexpectedAfterVersion + ]) } // MARK: - CatchClauseSyntax @@ -414,7 +410,7 @@ public struct CanImportVersionInfoSyntax: ExprSyntaxProtocol, SyntaxHashable, _L public struct CatchClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .catchClause else { return nil } @@ -561,17 +557,15 @@ public struct CatchClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCatchKeyword, - \Self.catchKeyword, - \Self.unexpectedBetweenCatchKeywordAndCatchItems, - \Self.catchItems, - \Self.unexpectedBetweenCatchItemsAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCatchKeyword, + \Self.catchKeyword, + \Self.unexpectedBetweenCatchKeywordAndCatchItems, + \Self.catchItems, + \Self.unexpectedBetweenCatchItemsAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - CatchItemSyntax @@ -588,7 +582,7 @@ public struct CatchClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode public struct CatchItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .catchItem else { return nil } @@ -708,17 +702,15 @@ public struct CatchItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndWhereClause, - \Self.whereClause, - \Self.unexpectedBetweenWhereClauseAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndWhereClause, + \Self.whereClause, + \Self.unexpectedBetweenWhereClauseAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ClassDeclSyntax @@ -760,7 +752,7 @@ public struct CatchItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr public struct ClassDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .classDecl else { return nil } @@ -1075,27 +1067,25 @@ public struct ClassDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndClassKeyword, - \Self.classKeyword, - \Self.unexpectedBetweenClassKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, - \Self.memberBlock, - \Self.unexpectedAfterMemberBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndClassKeyword, + \Self.classKeyword, + \Self.unexpectedBetweenClassKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, + \Self.memberBlock, + \Self.unexpectedAfterMemberBlock + ]) } // MARK: - ClassRestrictionTypeSyntax @@ -1106,7 +1096,7 @@ public struct ClassDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynt public struct ClassRestrictionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .classRestrictionType else { return nil } @@ -1170,9 +1160,7 @@ public struct ClassRestrictionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeClassKeyword, \Self.classKeyword, \Self.unexpectedAfterClassKeyword]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeClassKeyword, \Self.classKeyword, \Self.unexpectedAfterClassKeyword]) } // MARK: - ClosureCaptureClauseSyntax @@ -1189,7 +1177,7 @@ public struct ClassRestrictionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _L public struct ClosureCaptureClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureCaptureClause else { return nil } @@ -1339,17 +1327,15 @@ public struct ClosureCaptureClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndItems, - \Self.items, - \Self.unexpectedBetweenItemsAndRightSquare, - \Self.rightSquare, - \Self.unexpectedAfterRightSquare - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndItems, + \Self.items, + \Self.unexpectedBetweenItemsAndRightSquare, + \Self.rightSquare, + \Self.unexpectedAfterRightSquare + ]) } // MARK: - ClosureCaptureSpecifierSyntax @@ -1367,7 +1353,7 @@ public struct ClosureCaptureClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafS public struct ClosureCaptureSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureCaptureSpecifier else { return nil } @@ -1524,19 +1510,17 @@ public struct ClosureCaptureSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSpecifier, - \Self.specifier, - \Self.unexpectedBetweenSpecifierAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndDetail, - \Self.detail, - \Self.unexpectedBetweenDetailAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeSpecifier, + \Self.specifier, + \Self.unexpectedBetweenSpecifierAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndDetail, + \Self.detail, + \Self.unexpectedBetweenDetailAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - ClosureCaptureSyntax @@ -1555,7 +1539,7 @@ public struct ClosureCaptureSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _Le public struct ClosureCaptureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureCapture else { return nil } @@ -1729,21 +1713,19 @@ public struct ClosureCaptureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSpecifier, - \Self.specifier, - \Self.unexpectedBetweenSpecifierAndName, - \Self.name, - \Self.unexpectedBetweenNameAndEqual, - \Self.equal, - \Self.unexpectedBetweenEqualAndExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeSpecifier, + \Self.specifier, + \Self.unexpectedBetweenSpecifierAndName, + \Self.name, + \Self.unexpectedBetweenNameAndEqual, + \Self.equal, + \Self.unexpectedBetweenEqualAndExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ClosureExprSyntax @@ -1765,7 +1747,7 @@ public struct ClosureCaptureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public struct ClosureExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureExpr else { return nil } @@ -1939,19 +1921,17 @@ public struct ClosureExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftBrace, - \Self.leftBrace, - \Self.unexpectedBetweenLeftBraceAndSignature, - \Self.signature, - \Self.unexpectedBetweenSignatureAndStatements, - \Self.statements, - \Self.unexpectedBetweenStatementsAndRightBrace, - \Self.rightBrace, - \Self.unexpectedAfterRightBrace - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftBrace, + \Self.leftBrace, + \Self.unexpectedBetweenLeftBraceAndSignature, + \Self.signature, + \Self.unexpectedBetweenSignatureAndStatements, + \Self.statements, + \Self.unexpectedBetweenStatementsAndRightBrace, + \Self.rightBrace, + \Self.unexpectedAfterRightBrace + ]) } // MARK: - ClosureParameterClauseSyntax @@ -1968,7 +1948,7 @@ public struct ClosureExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy public struct ClosureParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureParameterClause else { return nil } @@ -2126,17 +2106,15 @@ public struct ClosureParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndParameters, - \Self.parameters, - \Self.unexpectedBetweenParametersAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndParameters, + \Self.parameters, + \Self.unexpectedBetweenParametersAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - ClosureParameterSyntax @@ -2158,7 +2136,7 @@ public struct ClosureParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Lea public struct ClosureParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureParameter else { return nil } @@ -2485,27 +2463,25 @@ public struct ClosureParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndFirstName, - \Self.firstName, - \Self.unexpectedBetweenFirstNameAndSecondName, - \Self.secondName, - \Self.unexpectedBetweenSecondNameAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndType, - \Self.type, - \Self.unexpectedBetweenTypeAndEllipsis, - \Self.ellipsis, - \Self.unexpectedBetweenEllipsisAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndFirstName, + \Self.firstName, + \Self.unexpectedBetweenFirstNameAndSecondName, + \Self.secondName, + \Self.unexpectedBetweenSecondNameAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndType, + \Self.type, + \Self.unexpectedBetweenTypeAndEllipsis, + \Self.ellipsis, + \Self.unexpectedBetweenEllipsisAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ClosureShorthandParameterSyntax @@ -2521,7 +2497,7 @@ public struct ClosureParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public struct ClosureShorthandParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureShorthandParameter else { return nil } @@ -2622,15 +2598,13 @@ public struct ClosureShorthandParameterSyntax: SyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ClosureSignatureSyntax @@ -2669,7 +2643,7 @@ public struct ClosureSignatureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta self = .parameterClause(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(ClosureShorthandParameterListSyntax.self) { self = .simpleInput(node) return @@ -2732,7 +2706,7 @@ public struct ClosureSignatureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .closureSignature else { return nil } @@ -2951,23 +2925,21 @@ public struct ClosureSignatureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndCapture, - \Self.capture, - \Self.unexpectedBetweenCaptureAndParameterClause, - \Self.parameterClause, - \Self.unexpectedBetweenParameterClauseAndEffectSpecifiers, - \Self.effectSpecifiers, - \Self.unexpectedBetweenEffectSpecifiersAndReturnClause, - \Self.returnClause, - \Self.unexpectedBetweenReturnClauseAndInKeyword, - \Self.inKeyword, - \Self.unexpectedAfterInKeyword - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndCapture, + \Self.capture, + \Self.unexpectedBetweenCaptureAndParameterClause, + \Self.parameterClause, + \Self.unexpectedBetweenParameterClauseAndEffectSpecifiers, + \Self.effectSpecifiers, + \Self.unexpectedBetweenEffectSpecifiersAndReturnClause, + \Self.returnClause, + \Self.unexpectedBetweenReturnClauseAndInKeyword, + \Self.inKeyword, + \Self.unexpectedAfterInKeyword + ]) } // MARK: - CodeBlockItemSyntax @@ -3011,7 +2983,7 @@ public struct CodeBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo self = .expr(ExprSyntax(node)) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(DeclSyntax.self) { self = .decl(node) return @@ -3100,7 +3072,7 @@ public struct CodeBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .codeBlockItem else { return nil } @@ -3201,15 +3173,13 @@ public struct CodeBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeItem, - \Self.item, - \Self.unexpectedBetweenItemAndSemicolon, - \Self.semicolon, - \Self.unexpectedAfterSemicolon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeItem, + \Self.item, + \Self.unexpectedBetweenItemAndSemicolon, + \Self.semicolon, + \Self.unexpectedAfterSemicolon + ]) } // MARK: - CodeBlockSyntax @@ -3238,7 +3208,7 @@ public struct CodeBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo public struct CodeBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .codeBlock else { return nil } @@ -3394,17 +3364,15 @@ public struct CodeBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftBrace, - \Self.leftBrace, - \Self.unexpectedBetweenLeftBraceAndStatements, - \Self.statements, - \Self.unexpectedBetweenStatementsAndRightBrace, - \Self.rightBrace, - \Self.unexpectedAfterRightBrace - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftBrace, + \Self.leftBrace, + \Self.unexpectedBetweenLeftBraceAndStatements, + \Self.statements, + \Self.unexpectedBetweenStatementsAndRightBrace, + \Self.rightBrace, + \Self.unexpectedAfterRightBrace + ]) } // MARK: - CompositionTypeElementSyntax @@ -3420,7 +3388,7 @@ public struct CodeBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodePr public struct CompositionTypeElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .compositionTypeElement else { return nil } @@ -3513,15 +3481,13 @@ public struct CompositionTypeElementSyntax: SyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeType, - \Self.type, - \Self.unexpectedBetweenTypeAndAmpersand, - \Self.ampersand, - \Self.unexpectedAfterAmpersand - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeType, + \Self.type, + \Self.unexpectedBetweenTypeAndAmpersand, + \Self.ampersand, + \Self.unexpectedAfterAmpersand + ]) } // MARK: - CompositionTypeSyntax @@ -3532,7 +3498,7 @@ public struct CompositionTypeElementSyntax: SyntaxProtocol, SyntaxHashable, _Lea public struct CompositionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .compositionType else { return nil } @@ -3620,9 +3586,7 @@ public struct CompositionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTy } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeElements, \Self.elements, \Self.unexpectedAfterElements]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeElements, \Self.elements, \Self.unexpectedAfterElements]) } // MARK: - ConditionElementSyntax @@ -3671,7 +3635,7 @@ public struct ConditionElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta self = .optionalBinding(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(ExprSyntax.self) { self = .expression(node) return @@ -3791,7 +3755,7 @@ public struct ConditionElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .conditionElement else { return nil } @@ -3887,15 +3851,13 @@ public struct ConditionElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCondition, - \Self.condition, - \Self.unexpectedBetweenConditionAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCondition, + \Self.condition, + \Self.unexpectedBetweenConditionAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ConformanceRequirementSyntax @@ -3912,7 +3874,7 @@ public struct ConditionElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public struct ConformanceRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .conformanceRequirement else { return nil } @@ -4032,17 +3994,15 @@ public struct ConformanceRequirementSyntax: SyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftType, - \Self.leftType, - \Self.unexpectedBetweenLeftTypeAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndRightType, - \Self.rightType, - \Self.unexpectedAfterRightType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftType, + \Self.leftType, + \Self.unexpectedBetweenLeftTypeAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndRightType, + \Self.rightType, + \Self.unexpectedAfterRightType + ]) } // MARK: - ConsumeExprSyntax @@ -4054,7 +4014,7 @@ public struct ConformanceRequirementSyntax: SyntaxProtocol, SyntaxHashable, _Lea public struct ConsumeExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .consumeExpr else { return nil } @@ -4152,15 +4112,13 @@ public struct ConsumeExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeConsumeKeyword, - \Self.consumeKeyword, - \Self.unexpectedBetweenConsumeKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeConsumeKeyword, + \Self.consumeKeyword, + \Self.unexpectedBetweenConsumeKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - ContinueStmtSyntax @@ -4172,7 +4130,7 @@ public struct ConsumeExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy public struct ContinueStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .continueStmt else { return nil } @@ -4271,15 +4229,13 @@ public struct ContinueStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeContinueKeyword, - \Self.continueKeyword, - \Self.unexpectedBetweenContinueKeywordAndLabel, - \Self.label, - \Self.unexpectedAfterLabel - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeContinueKeyword, + \Self.continueKeyword, + \Self.unexpectedBetweenContinueKeywordAndLabel, + \Self.label, + \Self.unexpectedAfterLabel + ]) } // MARK: - ConventionAttributeArgumentsSyntax @@ -4300,7 +4256,7 @@ public struct ContinueStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtS public struct ConventionAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .conventionAttributeArguments else { return nil } @@ -4480,21 +4436,19 @@ public struct ConventionAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeConventionLabel, - \Self.conventionLabel, - \Self.unexpectedBetweenConventionLabelAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndCTypeLabel, - \Self.cTypeLabel, - \Self.unexpectedBetweenCTypeLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndCTypeString, - \Self.cTypeString, - \Self.unexpectedAfterCTypeString - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeConventionLabel, + \Self.conventionLabel, + \Self.unexpectedBetweenConventionLabelAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndCTypeLabel, + \Self.cTypeLabel, + \Self.unexpectedBetweenCTypeLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndCTypeString, + \Self.cTypeString, + \Self.unexpectedAfterCTypeString + ]) } // MARK: - ConventionWitnessMethodAttributeArgumentsSyntax @@ -4513,7 +4467,7 @@ public struct ConventionAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .conventionWitnessMethodAttributeArguments else { return nil } @@ -4522,6 +4476,9 @@ public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, S /// - Parameters: /// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. + /// - witnessMethodLabel: The `witnessMethod` label. + /// - colon: The colon separating the `witnessMethod` label and the original protocol name. + /// - protocolName: The original protocol name. /// - trailingTrivia: Trivia to be appended to the trailing trivia of the node’s last token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. public init( leadingTrivia: Trivia? = nil, @@ -4576,6 +4533,8 @@ public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, S } } + /// The `witnessMethod` label. + /// /// ### Tokens /// /// For syntax trees generated by the parser, this is guaranteed to be `witness_method`. @@ -4597,6 +4556,8 @@ public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, S } } + /// The colon separating the `witnessMethod` label and the original protocol name. + /// /// ### Tokens /// /// For syntax trees generated by the parser, this is guaranteed to be `:`. @@ -4618,6 +4579,8 @@ public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, S } } + /// The original protocol name. + /// /// ### Tokens /// /// For syntax trees generated by the parser, this is guaranteed to be ``. @@ -4639,17 +4602,15 @@ public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, S } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWitnessMethodLabel, - \Self.witnessMethodLabel, - \Self.unexpectedBetweenWitnessMethodLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndProtocolName, - \Self.protocolName, - \Self.unexpectedAfterProtocolName - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWitnessMethodLabel, + \Self.witnessMethodLabel, + \Self.unexpectedBetweenWitnessMethodLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndProtocolName, + \Self.protocolName, + \Self.unexpectedAfterProtocolName + ]) } // MARK: - CopyExprSyntax @@ -4661,7 +4622,7 @@ public struct ConventionWitnessMethodAttributeArgumentsSyntax: SyntaxProtocol, S public struct CopyExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .copyExpr else { return nil } @@ -4757,13 +4718,11 @@ public struct CopyExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCopyKeyword, - \Self.copyKeyword, - \Self.unexpectedBetweenCopyKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCopyKeyword, + \Self.copyKeyword, + \Self.unexpectedBetweenCopyKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesD.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesD.swift index ce9c9bac45f..0715eb04d44 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesD.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesD.swift @@ -26,7 +26,7 @@ public struct DeclModifierDetailSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .declModifierDetail else { return nil } @@ -152,24 +152,22 @@ public struct DeclModifierDetailSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndDetail, - \Self.detail, - \Self.unexpectedBetweenDetailAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndDetail, + \Self.detail, + \Self.unexpectedBetweenDetailAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - DeclModifierSyntax /// ### Children /// -/// - `name`: (`__consuming` | `__setter_access` | `_const` | `_local` | `actor` | `async` | `borrowing` | `class` | `consuming` | `convenience` | `distributed` | `dynamic` | `fileprivate` | `final` | `indirect` | `infix` | `internal` | `isolated` | `lazy` | `mutating` | `nonisolated` | `nonmutating` | `open` | `optional` | `override` | `package` | `postfix` | `prefix` | `private` | `public` | `reasync` | `_resultDependsOnSelf` | `required` | `static` | `transferring` | `unowned` | `weak`) +/// - `name`: (`__consuming` | `__setter_access` | `_const` | `_local` | `actor` | `async` | `borrowing` | `class` | `consuming` | `convenience` | `distributed` | `dynamic` | `fileprivate` | `final` | `indirect` | `infix` | `internal` | `isolated` | `lazy` | `mutating` | `nonisolated` | `nonmutating` | `open` | `optional` | `override` | `package` | `postfix` | `prefix` | `private` | `public` | `reasync` | `_resultDependsOnSelf` | `required` | `static` | `unowned` | `weak` | `sending`) /// - `detail`: ``DeclModifierDetailSyntax``? /// /// ### Contained in @@ -179,7 +177,7 @@ public struct DeclModifierDetailSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn public struct DeclModifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .declModifier else { return nil } @@ -273,9 +271,9 @@ public struct DeclModifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod /// - `_resultDependsOnSelf` /// - `required` /// - `static` - /// - `transferring` /// - `unowned` /// - `weak` + /// - `sending` public var name: TokenSyntax { get { return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) @@ -312,15 +310,13 @@ public struct DeclModifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndDetail, - \Self.detail, - \Self.unexpectedAfterDetail - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndDetail, + \Self.detail, + \Self.unexpectedAfterDetail + ]) } // MARK: - DeclNameArgumentSyntax @@ -336,7 +332,7 @@ public struct DeclModifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod public struct DeclNameArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .declNameArgument else { return nil } @@ -432,15 +428,13 @@ public struct DeclNameArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndColon, - \Self.colon, - \Self.unexpectedAfterColon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndColon, + \Self.colon, + \Self.unexpectedAfterColon + ]) } // MARK: - DeclNameArgumentsSyntax @@ -457,7 +451,7 @@ public struct DeclNameArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public struct DeclNameArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .declNameArguments else { return nil } @@ -607,17 +601,15 @@ public struct DeclNameArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - DeclReferenceExprSyntax @@ -637,7 +629,7 @@ public struct DeclNameArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct DeclReferenceExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .declReferenceExpr else { return nil } @@ -742,15 +734,13 @@ public struct DeclReferenceExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBaseName, - \Self.baseName, - \Self.unexpectedBetweenBaseNameAndArgumentNames, - \Self.argumentNames, - \Self.unexpectedAfterArgumentNames - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBaseName, + \Self.baseName, + \Self.unexpectedBetweenBaseNameAndArgumentNames, + \Self.argumentNames, + \Self.unexpectedAfterArgumentNames + ]) } // MARK: - DeferStmtSyntax @@ -762,7 +752,7 @@ public struct DeclReferenceExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf public struct DeferStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .deferStmt else { return nil } @@ -858,15 +848,13 @@ public struct DeferStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDeferKeyword, - \Self.deferKeyword, - \Self.unexpectedBetweenDeferKeywordAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDeferKeyword, + \Self.deferKeyword, + \Self.unexpectedBetweenDeferKeywordAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - DeinitializerDeclSyntax @@ -890,7 +878,7 @@ public struct DeferStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt public struct DeinitializerDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .deinitializerDecl else { return nil } @@ -1121,21 +1109,19 @@ public struct DeinitializerDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndDeinitKeyword, - \Self.deinitKeyword, - \Self.unexpectedBetweenDeinitKeywordAndEffectSpecifiers, - \Self.effectSpecifiers, - \Self.unexpectedBetweenEffectSpecifiersAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndDeinitKeyword, + \Self.deinitKeyword, + \Self.unexpectedBetweenDeinitKeywordAndEffectSpecifiers, + \Self.effectSpecifiers, + \Self.unexpectedBetweenEffectSpecifiersAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - DeinitializerEffectSpecifiersSyntax @@ -1150,7 +1136,7 @@ public struct DeinitializerDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Leaf public struct DeinitializerEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .deinitializerEffectSpecifiers else { return nil } @@ -1217,9 +1203,7 @@ public struct DeinitializerEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashabl } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeAsyncSpecifier, \Self.asyncSpecifier, \Self.unexpectedAfterAsyncSpecifier]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeAsyncSpecifier, \Self.asyncSpecifier, \Self.unexpectedAfterAsyncSpecifier]) } // MARK: - DerivativeAttributeArgumentsSyntax @@ -1242,7 +1226,7 @@ public struct DeinitializerEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashabl public struct DerivativeAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .derivativeAttributeArguments else { return nil } @@ -1486,25 +1470,23 @@ public struct DerivativeAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeOfLabel, - \Self.ofLabel, - \Self.unexpectedBetweenOfLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndOriginalDeclName, - \Self.originalDeclName, - \Self.unexpectedBetweenOriginalDeclNameAndPeriod, - \Self.period, - \Self.unexpectedBetweenPeriodAndAccessorSpecifier, - \Self.accessorSpecifier, - \Self.unexpectedBetweenAccessorSpecifierAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndArguments, - \Self.arguments, - \Self.unexpectedAfterArguments - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeOfLabel, + \Self.ofLabel, + \Self.unexpectedBetweenOfLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndOriginalDeclName, + \Self.originalDeclName, + \Self.unexpectedBetweenOriginalDeclNameAndPeriod, + \Self.period, + \Self.unexpectedBetweenPeriodAndAccessorSpecifier, + \Self.accessorSpecifier, + \Self.unexpectedBetweenAccessorSpecifierAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndArguments, + \Self.arguments, + \Self.unexpectedAfterArguments + ]) } // MARK: - DesignatedTypeSyntax @@ -1520,7 +1502,7 @@ public struct DerivativeAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable public struct DesignatedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .designatedType else { return nil } @@ -1616,15 +1598,13 @@ public struct DesignatedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeadingComma, - \Self.leadingComma, - \Self.unexpectedBetweenLeadingCommaAndName, - \Self.name, - \Self.unexpectedAfterName - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeadingComma, + \Self.leadingComma, + \Self.unexpectedBetweenLeadingCommaAndName, + \Self.name, + \Self.unexpectedAfterName + ]) } // MARK: - DictionaryElementSyntax @@ -1644,7 +1624,7 @@ public struct DesignatedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public struct DictionaryElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .dictionaryElement else { return nil } @@ -1791,19 +1771,17 @@ public struct DictionaryElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeKey, - \Self.key, - \Self.unexpectedBetweenKeyAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedBetweenValueAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeKey, + \Self.key, + \Self.unexpectedBetweenKeyAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedBetweenValueAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - DictionaryExprSyntax @@ -1837,7 +1815,7 @@ public struct DictionaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp self = .elements(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(TokenSyntax.self) { self = .colon(node) return @@ -1900,7 +1878,7 @@ public struct DictionaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .dictionaryExpr else { return nil } @@ -2023,17 +2001,15 @@ public struct DictionaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndContent, - \Self.content, - \Self.unexpectedBetweenContentAndRightSquare, - \Self.rightSquare, - \Self.unexpectedAfterRightSquare - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndContent, + \Self.content, + \Self.unexpectedBetweenContentAndRightSquare, + \Self.rightSquare, + \Self.unexpectedAfterRightSquare + ]) } // MARK: - DictionaryTypeSyntax @@ -2048,7 +2024,7 @@ public struct DictionaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp public struct DictionaryTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .dictionaryType else { return nil } @@ -2222,21 +2198,19 @@ public struct DictionaryTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTyp } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndKey, - \Self.key, - \Self.unexpectedBetweenKeyAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedBetweenValueAndRightSquare, - \Self.rightSquare, - \Self.unexpectedAfterRightSquare - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndKey, + \Self.key, + \Self.unexpectedBetweenKeyAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedBetweenValueAndRightSquare, + \Self.rightSquare, + \Self.unexpectedAfterRightSquare + ]) } // MARK: - DifferentiabilityArgumentSyntax @@ -2255,7 +2229,7 @@ public struct DictionaryTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTyp public struct DifferentiabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .differentiabilityArgument else { return nil } @@ -2357,15 +2331,13 @@ public struct DifferentiabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeArgument, - \Self.argument, - \Self.unexpectedBetweenArgumentAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeArgument, + \Self.argument, + \Self.unexpectedBetweenArgumentAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - DifferentiabilityArgumentsSyntax @@ -2384,7 +2356,7 @@ public struct DifferentiabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _ public struct DifferentiabilityArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .differentiabilityArguments else { return nil } @@ -2536,17 +2508,15 @@ public struct DifferentiabilityArgumentsSyntax: SyntaxProtocol, SyntaxHashable, } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - DifferentiabilityWithRespectToArgumentSyntax @@ -2585,7 +2555,7 @@ public struct DifferentiabilityWithRespectToArgumentSyntax: SyntaxProtocol, Synt self = .argumentList(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(DifferentiabilityArgumentSyntax.self) { self = .argument(node) return @@ -2648,7 +2618,7 @@ public struct DifferentiabilityWithRespectToArgumentSyntax: SyntaxProtocol, Synt public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .differentiabilityWithRespectToArgument else { return nil } @@ -2777,17 +2747,15 @@ public struct DifferentiabilityWithRespectToArgumentSyntax: SyntaxProtocol, Synt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWrtLabel, - \Self.wrtLabel, - \Self.unexpectedBetweenWrtLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndArguments, - \Self.arguments, - \Self.unexpectedAfterArguments - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWrtLabel, + \Self.wrtLabel, + \Self.unexpectedBetweenWrtLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndArguments, + \Self.arguments, + \Self.unexpectedAfterArguments + ]) } // MARK: - DifferentiableAttributeArgumentsSyntax @@ -2808,7 +2776,7 @@ public struct DifferentiabilityWithRespectToArgumentSyntax: SyntaxProtocol, Synt public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .differentiableAttributeArguments else { return nil } @@ -2817,7 +2785,9 @@ public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHash /// - Parameters: /// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. + /// - kindSpecifier: The differentiability kind, if it exists. /// - kindSpecifierComma: The comma following the differentiability kind, if it exists. + /// - arguments: The differentiability arguments, if any exists. /// - argumentsComma: The comma following the differentiability arguments clause, if it exists. /// - genericWhereClause: A `where` clause that places additional constraints on generic parameters like `where T: Differentiable`. /// - trailingTrivia: Trivia to be appended to the trailing trivia of the node’s last token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. @@ -2886,6 +2856,8 @@ public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHash } } + /// The differentiability kind, if it exists. + /// /// ### Tokens /// /// For syntax trees generated by the parser, this is guaranteed to be one of the following kinds: @@ -2933,6 +2905,7 @@ public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHash } } + /// The differentiability arguments, if any exists. public var arguments: DifferentiabilityWithRespectToArgumentSyntax? { get { return Syntax(self).child(at: 5)?.cast(DifferentiabilityWithRespectToArgumentSyntax.self) @@ -2993,21 +2966,19 @@ public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHash } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeKindSpecifier, - \Self.kindSpecifier, - \Self.unexpectedBetweenKindSpecifierAndKindSpecifierComma, - \Self.kindSpecifierComma, - \Self.unexpectedBetweenKindSpecifierCommaAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndArgumentsComma, - \Self.argumentsComma, - \Self.unexpectedBetweenArgumentsCommaAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedAfterGenericWhereClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeKindSpecifier, + \Self.kindSpecifier, + \Self.unexpectedBetweenKindSpecifierAndKindSpecifierComma, + \Self.kindSpecifierComma, + \Self.unexpectedBetweenKindSpecifierCommaAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndArgumentsComma, + \Self.argumentsComma, + \Self.unexpectedBetweenArgumentsCommaAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedAfterGenericWhereClause + ]) } // MARK: - DiscardAssignmentExprSyntax @@ -3031,7 +3002,7 @@ public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHash public struct DiscardAssignmentExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .discardAssignmentExpr else { return nil } @@ -3095,9 +3066,7 @@ public struct DiscardAssignmentExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeWildcard, \Self.wildcard, \Self.unexpectedAfterWildcard]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeWildcard, \Self.wildcard, \Self.unexpectedAfterWildcard]) } // MARK: - DiscardStmtSyntax @@ -3109,7 +3078,7 @@ public struct DiscardAssignmentExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _ public struct DiscardStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .discardStmt else { return nil } @@ -3205,15 +3174,13 @@ public struct DiscardStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDiscardKeyword, - \Self.discardKeyword, - \Self.unexpectedBetweenDiscardKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDiscardKeyword, + \Self.discardKeyword, + \Self.unexpectedBetweenDiscardKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - DoExprSyntax @@ -3253,7 +3220,7 @@ public struct DiscardStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSy public struct DoExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .doExpr else { return nil } @@ -3400,17 +3367,15 @@ public struct DoExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDoKeyword, - \Self.doKeyword, - \Self.unexpectedBetweenDoKeywordAndBody, - \Self.body, - \Self.unexpectedBetweenBodyAndCatchClauses, - \Self.catchClauses, - \Self.unexpectedAfterCatchClauses - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDoKeyword, + \Self.doKeyword, + \Self.unexpectedBetweenDoKeywordAndBody, + \Self.body, + \Self.unexpectedBetweenBodyAndCatchClauses, + \Self.catchClauses, + \Self.unexpectedAfterCatchClauses + ]) } // MARK: - DoStmtSyntax @@ -3424,7 +3389,7 @@ public struct DoExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN public struct DoStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .doStmt else { return nil } @@ -3597,19 +3562,17 @@ public struct DoStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDoKeyword, - \Self.doKeyword, - \Self.unexpectedBetweenDoKeywordAndThrowsClause, - \Self.throwsClause, - \Self.unexpectedBetweenThrowsClauseAndBody, - \Self.body, - \Self.unexpectedBetweenBodyAndCatchClauses, - \Self.catchClauses, - \Self.unexpectedAfterCatchClauses - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDoKeyword, + \Self.doKeyword, + \Self.unexpectedBetweenDoKeywordAndThrowsClause, + \Self.throwsClause, + \Self.unexpectedBetweenThrowsClauseAndBody, + \Self.body, + \Self.unexpectedBetweenBodyAndCatchClauses, + \Self.catchClauses, + \Self.unexpectedAfterCatchClauses + ]) } // MARK: - DocumentationAttributeArgumentSyntax @@ -3646,7 +3609,7 @@ public struct DocumentationAttributeArgumentSyntax: SyntaxProtocol, SyntaxHashab self = .string(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(TokenSyntax.self) { self = .token(node) return @@ -3709,7 +3672,7 @@ public struct DocumentationAttributeArgumentSyntax: SyntaxProtocol, SyntaxHashab public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .documentationAttributeArgument else { return nil } @@ -3864,19 +3827,17 @@ public struct DocumentationAttributeArgumentSyntax: SyntaxProtocol, SyntaxHashab } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedBetweenValueAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedBetweenValueAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - DynamicReplacementAttributeArgumentsSyntax @@ -3895,7 +3856,7 @@ public struct DocumentationAttributeArgumentSyntax: SyntaxProtocol, SyntaxHashab public struct DynamicReplacementAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .dynamicReplacementAttributeArguments else { return nil } @@ -4018,15 +3979,13 @@ public struct DynamicReplacementAttributeArgumentsSyntax: SyntaxProtocol, Syntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeForLabel, - \Self.forLabel, - \Self.unexpectedBetweenForLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndDeclName, - \Self.declName, - \Self.unexpectedAfterDeclName - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeForLabel, + \Self.forLabel, + \Self.unexpectedBetweenForLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndDeclName, + \Self.declName, + \Self.unexpectedAfterDeclName + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesEF.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesEF.swift index a436eb7f23d..c5104bff73f 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesEF.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesEF.swift @@ -26,7 +26,7 @@ public struct EditorPlaceholderDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .editorPlaceholderDecl else { return nil } @@ -207,17 +207,15 @@ public struct EditorPlaceholderDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndPlaceholder, - \Self.placeholder, - \Self.unexpectedAfterPlaceholder - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndPlaceholder, + \Self.placeholder, + \Self.unexpectedAfterPlaceholder + ]) } // MARK: - EditorPlaceholderExprSyntax @@ -230,7 +228,7 @@ public struct EditorPlaceholderDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _ public struct EditorPlaceholderExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .editorPlaceholderExpr else { return nil } @@ -294,9 +292,7 @@ public struct EditorPlaceholderExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) } // MARK: - EnumCaseDeclSyntax @@ -312,7 +308,7 @@ public struct EditorPlaceholderExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _ public struct EnumCaseDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .enumCaseDecl else { return nil } @@ -546,19 +542,17 @@ public struct EnumCaseDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndCaseKeyword, - \Self.caseKeyword, - \Self.unexpectedBetweenCaseKeywordAndElements, - \Self.elements, - \Self.unexpectedAfterElements - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndCaseKeyword, + \Self.caseKeyword, + \Self.unexpectedBetweenCaseKeywordAndElements, + \Self.elements, + \Self.unexpectedAfterElements + ]) } // MARK: - EnumCaseElementSyntax @@ -578,7 +572,7 @@ public struct EnumCaseDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS public struct EnumCaseElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .enumCaseElement else { return nil } @@ -735,19 +729,17 @@ public struct EnumCaseElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndParameterClause, - \Self.parameterClause, - \Self.unexpectedBetweenParameterClauseAndRawValue, - \Self.rawValue, - \Self.unexpectedBetweenRawValueAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndParameterClause, + \Self.parameterClause, + \Self.unexpectedBetweenParameterClauseAndRawValue, + \Self.rawValue, + \Self.unexpectedBetweenRawValueAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - EnumCaseParameterClauseSyntax @@ -764,7 +756,7 @@ public struct EnumCaseElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax public struct EnumCaseParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .enumCaseParameterClause else { return nil } @@ -922,17 +914,15 @@ public struct EnumCaseParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndParameters, - \Self.parameters, - \Self.unexpectedBetweenParametersAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndParameters, + \Self.parameters, + \Self.unexpectedBetweenParametersAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - EnumCaseParameterSyntax @@ -953,7 +943,7 @@ public struct EnumCaseParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Le public struct EnumCaseParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .enumCaseParameter else { return nil } @@ -1219,25 +1209,23 @@ public struct EnumCaseParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndFirstName, - \Self.firstName, - \Self.unexpectedBetweenFirstNameAndSecondName, - \Self.secondName, - \Self.unexpectedBetweenSecondNameAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndType, - \Self.type, - \Self.unexpectedBetweenTypeAndDefaultValue, - \Self.defaultValue, - \Self.unexpectedBetweenDefaultValueAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndFirstName, + \Self.firstName, + \Self.unexpectedBetweenFirstNameAndSecondName, + \Self.secondName, + \Self.unexpectedBetweenSecondNameAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndType, + \Self.type, + \Self.unexpectedBetweenTypeAndDefaultValue, + \Self.defaultValue, + \Self.unexpectedBetweenDefaultValueAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - EnumDeclSyntax @@ -1257,7 +1245,7 @@ public struct EnumCaseParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct EnumDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .enumDecl else { return nil } @@ -1572,27 +1560,25 @@ public struct EnumDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndEnumKeyword, - \Self.enumKeyword, - \Self.unexpectedBetweenEnumKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, - \Self.memberBlock, - \Self.unexpectedAfterMemberBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndEnumKeyword, + \Self.enumKeyword, + \Self.unexpectedBetweenEnumKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, + \Self.memberBlock, + \Self.unexpectedAfterMemberBlock + ]) } // MARK: - ExposeAttributeArgumentsSyntax @@ -1611,7 +1597,7 @@ public struct EnumDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynta public struct ExposeAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .exposeAttributeArguments else { return nil } @@ -1731,17 +1717,15 @@ public struct ExposeAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLanguage, - \Self.language, - \Self.unexpectedBetweenLanguageAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndCxxName, - \Self.cxxName, - \Self.unexpectedAfterCxxName - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLanguage, + \Self.language, + \Self.unexpectedBetweenLanguageAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndCxxName, + \Self.cxxName, + \Self.unexpectedAfterCxxName + ]) } // MARK: - ExpressionPatternSyntax @@ -1766,7 +1750,7 @@ public struct ExposeAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _L public struct ExpressionPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .expressionPattern else { return nil } @@ -1827,9 +1811,7 @@ public struct ExpressionPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeExpression, \Self.expression, \Self.unexpectedAfterExpression]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeExpression, \Self.expression, \Self.unexpectedAfterExpression]) } // MARK: - ExpressionSegmentSyntax @@ -1852,7 +1834,7 @@ public struct ExpressionPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _L public struct ExpressionSegmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .expressionSegment else { return nil } @@ -2056,21 +2038,19 @@ public struct ExpressionSegmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBackslash, - \Self.backslash, - \Self.unexpectedBetweenBackslashAndPounds, - \Self.pounds, - \Self.unexpectedBetweenPoundsAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndExpressions, - \Self.expressions, - \Self.unexpectedBetweenExpressionsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBackslash, + \Self.backslash, + \Self.unexpectedBetweenBackslashAndPounds, + \Self.pounds, + \Self.unexpectedBetweenPoundsAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndExpressions, + \Self.expressions, + \Self.unexpectedBetweenExpressionsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - ExpressionStmtSyntax @@ -2081,7 +2061,7 @@ public struct ExpressionSegmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct ExpressionStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .expressionStmt else { return nil } @@ -2142,9 +2122,7 @@ public struct ExpressionStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStm } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeExpression, \Self.expression, \Self.unexpectedAfterExpression]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeExpression, \Self.expression, \Self.unexpectedAfterExpression]) } // MARK: - ExtensionDeclSyntax @@ -2161,7 +2139,7 @@ public struct ExpressionStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStm public struct ExtensionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .extensionDecl else { return nil } @@ -2437,25 +2415,23 @@ public struct ExtensionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDecl } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndExtensionKeyword, - \Self.extensionKeyword, - \Self.unexpectedBetweenExtensionKeywordAndExtendedType, - \Self.extendedType, - \Self.unexpectedBetweenExtendedTypeAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, - \Self.memberBlock, - \Self.unexpectedAfterMemberBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndExtensionKeyword, + \Self.extensionKeyword, + \Self.unexpectedBetweenExtensionKeywordAndExtendedType, + \Self.extendedType, + \Self.unexpectedBetweenExtendedTypeAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, + \Self.memberBlock, + \Self.unexpectedAfterMemberBlock + ]) } // MARK: - FallThroughStmtSyntax @@ -2466,7 +2442,7 @@ public struct ExtensionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDecl public struct FallThroughStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .fallThroughStmt else { return nil } @@ -2530,9 +2506,7 @@ public struct FallThroughStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafSt } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeFallthroughKeyword, \Self.fallthroughKeyword, \Self.unexpectedAfterFallthroughKeyword]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeFallthroughKeyword, \Self.fallthroughKeyword, \Self.unexpectedAfterFallthroughKeyword]) } // MARK: - FloatLiteralExprSyntax @@ -2543,7 +2517,7 @@ public struct FallThroughStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafSt public struct FloatLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .floatLiteralExpr else { return nil } @@ -2607,9 +2581,7 @@ public struct FloatLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeLiteral, \Self.literal, \Self.unexpectedAfterLiteral]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeLiteral, \Self.literal, \Self.unexpectedAfterLiteral]) } // MARK: - ForStmtSyntax @@ -2629,7 +2601,7 @@ public struct FloatLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE public struct ForStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .forStmt else { return nil } @@ -2929,31 +2901,29 @@ public struct ForStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeForKeyword, - \Self.forKeyword, - \Self.unexpectedBetweenForKeywordAndTryKeyword, - \Self.tryKeyword, - \Self.unexpectedBetweenTryKeywordAndAwaitKeyword, - \Self.awaitKeyword, - \Self.unexpectedBetweenAwaitKeywordAndCaseKeyword, - \Self.caseKeyword, - \Self.unexpectedBetweenCaseKeywordAndPattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndTypeAnnotation, - \Self.typeAnnotation, - \Self.unexpectedBetweenTypeAnnotationAndInKeyword, - \Self.inKeyword, - \Self.unexpectedBetweenInKeywordAndSequence, - \Self.sequence, - \Self.unexpectedBetweenSequenceAndWhereClause, - \Self.whereClause, - \Self.unexpectedBetweenWhereClauseAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeForKeyword, + \Self.forKeyword, + \Self.unexpectedBetweenForKeywordAndTryKeyword, + \Self.tryKeyword, + \Self.unexpectedBetweenTryKeywordAndAwaitKeyword, + \Self.awaitKeyword, + \Self.unexpectedBetweenAwaitKeywordAndCaseKeyword, + \Self.caseKeyword, + \Self.unexpectedBetweenCaseKeywordAndPattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndTypeAnnotation, + \Self.typeAnnotation, + \Self.unexpectedBetweenTypeAnnotationAndInKeyword, + \Self.inKeyword, + \Self.unexpectedBetweenInKeywordAndSequence, + \Self.sequence, + \Self.unexpectedBetweenSequenceAndWhereClause, + \Self.whereClause, + \Self.unexpectedBetweenWhereClauseAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - ForceUnwrapExprSyntax @@ -2965,7 +2935,7 @@ public struct ForStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntax public struct ForceUnwrapExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .forceUnwrapExpr else { return nil } @@ -3061,15 +3031,13 @@ public struct ForceUnwrapExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafEx } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndExclamationMark, - \Self.exclamationMark, - \Self.unexpectedAfterExclamationMark - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndExclamationMark, + \Self.exclamationMark, + \Self.unexpectedAfterExclamationMark + ]) } // MARK: - FunctionCallExprSyntax @@ -3085,7 +3053,7 @@ public struct ForceUnwrapExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafEx public struct FunctionCallExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionCallExpr else { return nil } @@ -3334,23 +3302,21 @@ public struct FunctionCallExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCalledExpression, - \Self.calledExpression, - \Self.unexpectedBetweenCalledExpressionAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedBetweenRightParenAndTrailingClosure, - \Self.trailingClosure, - \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, - \Self.additionalTrailingClosures, - \Self.unexpectedAfterAdditionalTrailingClosures - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCalledExpression, + \Self.calledExpression, + \Self.unexpectedBetweenCalledExpressionAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedBetweenRightParenAndTrailingClosure, + \Self.trailingClosure, + \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, + \Self.additionalTrailingClosures, + \Self.unexpectedAfterAdditionalTrailingClosures + ]) } // MARK: - FunctionDeclSyntax @@ -3368,7 +3334,7 @@ public struct FunctionCallExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE public struct FunctionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionDecl else { return nil } @@ -3678,27 +3644,25 @@ public struct FunctionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndFuncKeyword, - \Self.funcKeyword, - \Self.unexpectedBetweenFuncKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndSignature, - \Self.signature, - \Self.unexpectedBetweenSignatureAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndFuncKeyword, + \Self.funcKeyword, + \Self.unexpectedBetweenFuncKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndSignature, + \Self.signature, + \Self.unexpectedBetweenSignatureAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - FunctionEffectSpecifiersSyntax @@ -3714,7 +3678,7 @@ public struct FunctionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS public struct FunctionEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionEffectSpecifiers else { return nil } @@ -3817,15 +3781,13 @@ public struct FunctionEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAsyncSpecifier, - \Self.asyncSpecifier, - \Self.unexpectedBetweenAsyncSpecifierAndThrowsClause, - \Self.throwsClause, - \Self.unexpectedAfterThrowsClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAsyncSpecifier, + \Self.asyncSpecifier, + \Self.unexpectedBetweenAsyncSpecifierAndThrowsClause, + \Self.throwsClause, + \Self.unexpectedAfterThrowsClause + ]) } // MARK: - FunctionParameterClauseSyntax @@ -3843,7 +3805,7 @@ public struct FunctionEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _L public struct FunctionParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionParameterClause else { return nil } @@ -3993,17 +3955,15 @@ public struct FunctionParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndParameters, - \Self.parameters, - \Self.unexpectedBetweenParametersAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndParameters, + \Self.parameters, + \Self.unexpectedBetweenParametersAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - FunctionParameterSyntax @@ -4026,7 +3986,7 @@ public struct FunctionParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Le public struct FunctionParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionParameter else { return nil } @@ -4360,29 +4320,27 @@ public struct FunctionParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndFirstName, - \Self.firstName, - \Self.unexpectedBetweenFirstNameAndSecondName, - \Self.secondName, - \Self.unexpectedBetweenSecondNameAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndType, - \Self.type, - \Self.unexpectedBetweenTypeAndEllipsis, - \Self.ellipsis, - \Self.unexpectedBetweenEllipsisAndDefaultValue, - \Self.defaultValue, - \Self.unexpectedBetweenDefaultValueAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndFirstName, + \Self.firstName, + \Self.unexpectedBetweenFirstNameAndSecondName, + \Self.secondName, + \Self.unexpectedBetweenSecondNameAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndType, + \Self.type, + \Self.unexpectedBetweenTypeAndEllipsis, + \Self.ellipsis, + \Self.unexpectedBetweenEllipsisAndDefaultValue, + \Self.defaultValue, + \Self.unexpectedBetweenDefaultValueAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - FunctionSignatureSyntax @@ -4401,7 +4359,7 @@ public struct FunctionParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct FunctionSignatureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionSignature else { return nil } @@ -4518,17 +4476,15 @@ public struct FunctionSignatureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeParameterClause, - \Self.parameterClause, - \Self.unexpectedBetweenParameterClauseAndEffectSpecifiers, - \Self.effectSpecifiers, - \Self.unexpectedBetweenEffectSpecifiersAndReturnClause, - \Self.returnClause, - \Self.unexpectedAfterReturnClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeParameterClause, + \Self.parameterClause, + \Self.unexpectedBetweenParameterClauseAndEffectSpecifiers, + \Self.effectSpecifiers, + \Self.unexpectedBetweenEffectSpecifiersAndReturnClause, + \Self.returnClause, + \Self.unexpectedAfterReturnClause + ]) } // MARK: - FunctionTypeSyntax @@ -4543,7 +4499,7 @@ public struct FunctionSignatureSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct FunctionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .functionType else { return nil } @@ -4741,19 +4697,17 @@ public struct FunctionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndParameters, - \Self.parameters, - \Self.unexpectedBetweenParametersAndRightParen, - \Self.rightParen, - \Self.unexpectedBetweenRightParenAndEffectSpecifiers, - \Self.effectSpecifiers, - \Self.unexpectedBetweenEffectSpecifiersAndReturnClause, - \Self.returnClause, - \Self.unexpectedAfterReturnClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndParameters, + \Self.parameters, + \Self.unexpectedBetweenParametersAndRightParen, + \Self.rightParen, + \Self.unexpectedBetweenRightParenAndEffectSpecifiers, + \Self.effectSpecifiers, + \Self.unexpectedBetweenEffectSpecifiersAndReturnClause, + \Self.returnClause, + \Self.unexpectedAfterReturnClause + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesGHI.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesGHI.swift index 6c968b558dc..2a4290515da 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesGHI.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesGHI.swift @@ -31,7 +31,7 @@ public struct GenericArgumentClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericArgumentClause else { return nil } @@ -181,17 +181,15 @@ public struct GenericArgumentClauseSyntax: SyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftAngle, - \Self.leftAngle, - \Self.unexpectedBetweenLeftAngleAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightAngle, - \Self.rightAngle, - \Self.unexpectedAfterRightAngle - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftAngle, + \Self.leftAngle, + \Self.unexpectedBetweenLeftAngleAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightAngle, + \Self.rightAngle, + \Self.unexpectedAfterRightAngle + ]) } // MARK: - GenericArgumentSyntax @@ -207,7 +205,7 @@ public struct GenericArgumentClauseSyntax: SyntaxProtocol, SyntaxHashable, _Leaf public struct GenericArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericArgument else { return nil } @@ -303,15 +301,13 @@ public struct GenericArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeArgument, - \Self.argument, - \Self.unexpectedBetweenArgumentAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeArgument, + \Self.argument, + \Self.unexpectedBetweenArgumentAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - GenericParameterClauseSyntax @@ -340,7 +336,7 @@ public struct GenericArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax public struct GenericParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericParameterClause else { return nil } @@ -524,19 +520,17 @@ public struct GenericParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftAngle, - \Self.leftAngle, - \Self.unexpectedBetweenLeftAngleAndParameters, - \Self.parameters, - \Self.unexpectedBetweenParametersAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndRightAngle, - \Self.rightAngle, - \Self.unexpectedAfterRightAngle - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftAngle, + \Self.leftAngle, + \Self.unexpectedBetweenLeftAngleAndParameters, + \Self.parameters, + \Self.unexpectedBetweenParametersAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndRightAngle, + \Self.rightAngle, + \Self.unexpectedAfterRightAngle + ]) } // MARK: - GenericParameterSyntax @@ -556,7 +550,7 @@ public struct GenericParameterClauseSyntax: SyntaxProtocol, SyntaxHashable, _Lea public struct GenericParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericParameter else { return nil } @@ -784,23 +778,21 @@ public struct GenericParameterSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndEachKeyword, - \Self.eachKeyword, - \Self.unexpectedBetweenEachKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndInheritedType, - \Self.inheritedType, - \Self.unexpectedBetweenInheritedTypeAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndEachKeyword, + \Self.eachKeyword, + \Self.unexpectedBetweenEachKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndInheritedType, + \Self.inheritedType, + \Self.unexpectedBetweenInheritedTypeAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - GenericRequirementSyntax @@ -842,7 +834,7 @@ public struct GenericRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn self = .layoutRequirement(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(SameTypeRequirementSyntax.self) { self = .sameTypeRequirement(node) return @@ -931,7 +923,7 @@ public struct GenericRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericRequirement else { return nil } @@ -1027,15 +1019,13 @@ public struct GenericRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeRequirement, - \Self.requirement, - \Self.unexpectedBetweenRequirementAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeRequirement, + \Self.requirement, + \Self.unexpectedBetweenRequirementAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - GenericSpecializationExprSyntax @@ -1047,7 +1037,7 @@ public struct GenericRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn public struct GenericSpecializationExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericSpecializationExpr else { return nil } @@ -1140,15 +1130,13 @@ public struct GenericSpecializationExprSyntax: ExprSyntaxProtocol, SyntaxHashabl } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndGenericArgumentClause, - \Self.genericArgumentClause, - \Self.unexpectedAfterGenericArgumentClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndGenericArgumentClause, + \Self.genericArgumentClause, + \Self.unexpectedAfterGenericArgumentClause + ]) } // MARK: - GenericWhereClauseSyntax @@ -1180,7 +1168,7 @@ public struct GenericSpecializationExprSyntax: ExprSyntaxProtocol, SyntaxHashabl public struct GenericWhereClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .genericWhereClause else { return nil } @@ -1308,15 +1296,13 @@ public struct GenericWhereClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWhereKeyword, - \Self.whereKeyword, - \Self.unexpectedBetweenWhereKeywordAndRequirements, - \Self.requirements, - \Self.unexpectedAfterRequirements - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWhereKeyword, + \Self.whereKeyword, + \Self.unexpectedBetweenWhereKeywordAndRequirements, + \Self.requirements, + \Self.unexpectedAfterRequirements + ]) } // MARK: - GuardStmtSyntax @@ -1330,7 +1316,7 @@ public struct GenericWhereClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn public struct GuardStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .guardStmt else { return nil } @@ -1504,19 +1490,17 @@ public struct GuardStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeGuardKeyword, - \Self.guardKeyword, - \Self.unexpectedBetweenGuardKeywordAndConditions, - \Self.conditions, - \Self.unexpectedBetweenConditionsAndElseKeyword, - \Self.elseKeyword, - \Self.unexpectedBetweenElseKeywordAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeGuardKeyword, + \Self.guardKeyword, + \Self.unexpectedBetweenGuardKeywordAndConditions, + \Self.conditions, + \Self.unexpectedBetweenConditionsAndElseKeyword, + \Self.elseKeyword, + \Self.unexpectedBetweenElseKeywordAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - IdentifierPatternSyntax @@ -1538,7 +1522,7 @@ public struct GuardStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt public struct IdentifierPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .identifierPattern else { return nil } @@ -1607,9 +1591,7 @@ public struct IdentifierPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeIdentifier, \Self.identifier, \Self.unexpectedAfterIdentifier]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeIdentifier, \Self.identifier, \Self.unexpectedAfterIdentifier]) } // MARK: - IdentifierTypeSyntax @@ -1621,7 +1603,7 @@ public struct IdentifierPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _L public struct IdentifierTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .identifierType else { return nil } @@ -1721,15 +1703,13 @@ public struct IdentifierTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTyp } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericArgumentClause, - \Self.genericArgumentClause, - \Self.unexpectedAfterGenericArgumentClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericArgumentClause, + \Self.genericArgumentClause, + \Self.unexpectedAfterGenericArgumentClause + ]) } // MARK: - IfConfigClauseSyntax @@ -1786,7 +1766,7 @@ public struct IfConfigClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN self = .attributes(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(CodeBlockItemListSyntax.self) { self = .statements(node) return @@ -1933,7 +1913,7 @@ public struct IfConfigClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .ifConfigClause else { return nil } @@ -2056,17 +2036,15 @@ public struct IfConfigClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePoundKeyword, - \Self.poundKeyword, - \Self.unexpectedBetweenPoundKeywordAndCondition, - \Self.condition, - \Self.unexpectedBetweenConditionAndElements, - \Self.elements, - \Self.unexpectedAfterElements - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePoundKeyword, + \Self.poundKeyword, + \Self.unexpectedBetweenPoundKeywordAndCondition, + \Self.condition, + \Self.unexpectedBetweenConditionAndElements, + \Self.elements, + \Self.unexpectedAfterElements + ]) } // MARK: - IfConfigDeclSyntax @@ -2084,7 +2062,7 @@ public struct IfConfigClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public struct IfConfigDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .ifConfigDecl else { return nil } @@ -2207,15 +2185,13 @@ public struct IfConfigDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeClauses, - \Self.clauses, - \Self.unexpectedBetweenClausesAndPoundEndif, - \Self.poundEndif, - \Self.unexpectedAfterPoundEndif - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeClauses, + \Self.clauses, + \Self.unexpectedBetweenClausesAndPoundEndif, + \Self.poundEndif, + \Self.unexpectedAfterPoundEndif + ]) } // MARK: - IfExprSyntax @@ -2253,7 +2229,7 @@ public struct IfExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN self = .codeBlock(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(IfExprSyntax.self) { self = .ifExpr(node) return @@ -2316,7 +2292,7 @@ public struct IfExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .ifExpr else { return nil } @@ -2514,21 +2490,19 @@ public struct IfExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeIfKeyword, - \Self.ifKeyword, - \Self.unexpectedBetweenIfKeywordAndConditions, - \Self.conditions, - \Self.unexpectedBetweenConditionsAndBody, - \Self.body, - \Self.unexpectedBetweenBodyAndElseKeyword, - \Self.elseKeyword, - \Self.unexpectedBetweenElseKeywordAndElseBody, - \Self.elseBody, - \Self.unexpectedAfterElseBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeIfKeyword, + \Self.ifKeyword, + \Self.unexpectedBetweenIfKeywordAndConditions, + \Self.conditions, + \Self.unexpectedBetweenConditionsAndBody, + \Self.body, + \Self.unexpectedBetweenBodyAndElseKeyword, + \Self.elseKeyword, + \Self.unexpectedBetweenElseKeywordAndElseBody, + \Self.elseBody, + \Self.unexpectedAfterElseBody + ]) } // MARK: - ImplementsAttributeArgumentsSyntax @@ -2547,7 +2521,7 @@ public struct IfExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN public struct ImplementsAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .implementsAttributeArguments else { return nil } @@ -2674,17 +2648,15 @@ public struct ImplementsAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeType, - \Self.type, - \Self.unexpectedBetweenTypeAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndDeclName, - \Self.declName, - \Self.unexpectedAfterDeclName - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeType, + \Self.type, + \Self.unexpectedBetweenTypeAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndDeclName, + \Self.declName, + \Self.unexpectedAfterDeclName + ]) } // MARK: - ImplicitlyUnwrappedOptionalTypeSyntax @@ -2696,7 +2668,7 @@ public struct ImplementsAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable public struct ImplicitlyUnwrappedOptionalTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .implicitlyUnwrappedOptionalType else { return nil } @@ -2792,15 +2764,13 @@ public struct ImplicitlyUnwrappedOptionalTypeSyntax: TypeSyntaxProtocol, SyntaxH } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWrappedType, - \Self.wrappedType, - \Self.unexpectedBetweenWrappedTypeAndExclamationMark, - \Self.exclamationMark, - \Self.unexpectedAfterExclamationMark - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWrappedType, + \Self.wrappedType, + \Self.unexpectedBetweenWrappedTypeAndExclamationMark, + \Self.exclamationMark, + \Self.unexpectedAfterExclamationMark + ]) } // MARK: - ImportDeclSyntax @@ -2823,7 +2793,7 @@ public struct ImplicitlyUnwrappedOptionalTypeSyntax: TypeSyntaxProtocol, SyntaxH public struct ImportDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .importDecl else { return nil } @@ -3098,21 +3068,19 @@ public struct ImportDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndImportKeyword, - \Self.importKeyword, - \Self.unexpectedBetweenImportKeywordAndImportKindSpecifier, - \Self.importKindSpecifier, - \Self.unexpectedBetweenImportKindSpecifierAndPath, - \Self.path, - \Self.unexpectedAfterPath - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndImportKeyword, + \Self.importKeyword, + \Self.unexpectedBetweenImportKeywordAndImportKindSpecifier, + \Self.importKindSpecifier, + \Self.unexpectedBetweenImportKindSpecifierAndPath, + \Self.path, + \Self.unexpectedAfterPath + ]) } // MARK: - ImportPathComponentSyntax @@ -3128,7 +3096,7 @@ public struct ImportDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyn public struct ImportPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .importPathComponent else { return nil } @@ -3231,15 +3199,13 @@ public struct ImportPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndTrailingPeriod, - \Self.trailingPeriod, - \Self.unexpectedAfterTrailingPeriod - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndTrailingPeriod, + \Self.trailingPeriod, + \Self.unexpectedAfterTrailingPeriod + ]) } // MARK: - InOutExprSyntax @@ -3253,7 +3219,7 @@ public struct ImportPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy public struct InOutExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .inOutExpr else { return nil } @@ -3349,15 +3315,13 @@ public struct InOutExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAmpersand, - \Self.ampersand, - \Self.unexpectedBetweenAmpersandAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAmpersand, + \Self.ampersand, + \Self.unexpectedBetweenAmpersandAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - InfixOperatorExprSyntax @@ -3376,7 +3340,7 @@ public struct InOutExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt public struct InfixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .infixOperatorExpr else { return nil } @@ -3493,17 +3457,15 @@ public struct InfixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftOperand, - \Self.leftOperand, - \Self.unexpectedBetweenLeftOperandAndOperator, - \Self.operator, - \Self.unexpectedBetweenOperatorAndRightOperand, - \Self.rightOperand, - \Self.unexpectedAfterRightOperand - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftOperand, + \Self.leftOperand, + \Self.unexpectedBetweenLeftOperandAndOperator, + \Self.operator, + \Self.unexpectedBetweenOperatorAndRightOperand, + \Self.rightOperand, + \Self.unexpectedAfterRightOperand + ]) } // MARK: - InheritanceClauseSyntax @@ -3525,7 +3487,7 @@ public struct InfixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf public struct InheritanceClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .inheritanceClause else { return nil } @@ -3648,15 +3610,13 @@ public struct InheritanceClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeColon, - \Self.colon, - \Self.unexpectedBetweenColonAndInheritedTypes, - \Self.inheritedTypes, - \Self.unexpectedAfterInheritedTypes - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeColon, + \Self.colon, + \Self.unexpectedBetweenColonAndInheritedTypes, + \Self.inheritedTypes, + \Self.unexpectedAfterInheritedTypes + ]) } // MARK: - InheritedTypeSyntax @@ -3672,7 +3632,7 @@ public struct InheritanceClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct InheritedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .inheritedType else { return nil } @@ -3768,15 +3728,13 @@ public struct InheritedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeType, - \Self.type, - \Self.unexpectedBetweenTypeAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeType, + \Self.type, + \Self.unexpectedBetweenTypeAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - InitializerClauseSyntax @@ -3798,7 +3756,7 @@ public struct InheritedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo public struct InitializerClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .initializerClause else { return nil } @@ -3894,15 +3852,13 @@ public struct InitializerClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeEqual, - \Self.equal, - \Self.unexpectedBetweenEqualAndValue, - \Self.value, - \Self.unexpectedAfterValue - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeEqual, + \Self.equal, + \Self.unexpectedBetweenEqualAndValue, + \Self.value, + \Self.unexpectedAfterValue + ]) } // MARK: - InitializerDeclSyntax @@ -3931,7 +3887,7 @@ public struct InitializerClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct InitializerDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .initializerDecl else { return nil } @@ -4248,27 +4204,25 @@ public struct InitializerDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDe } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndInitKeyword, - \Self.initKeyword, - \Self.unexpectedBetweenInitKeywordAndOptionalMark, - \Self.optionalMark, - \Self.unexpectedBetweenOptionalMarkAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndSignature, - \Self.signature, - \Self.unexpectedBetweenSignatureAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndInitKeyword, + \Self.initKeyword, + \Self.unexpectedBetweenInitKeywordAndOptionalMark, + \Self.optionalMark, + \Self.unexpectedBetweenOptionalMarkAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndSignature, + \Self.signature, + \Self.unexpectedBetweenSignatureAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - IntegerLiteralExprSyntax @@ -4279,7 +4233,7 @@ public struct InitializerDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDe public struct IntegerLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .integerLiteralExpr else { return nil } @@ -4343,9 +4297,7 @@ public struct IntegerLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeLiteral, \Self.literal, \Self.unexpectedAfterLiteral]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeLiteral, \Self.literal, \Self.unexpectedAfterLiteral]) } // MARK: - IsExprSyntax @@ -4369,7 +4321,7 @@ public struct IntegerLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea public struct IsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .isExpr else { return nil } @@ -4496,17 +4448,15 @@ public struct IsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndIsKeyword, - \Self.isKeyword, - \Self.unexpectedBetweenIsKeywordAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndIsKeyword, + \Self.isKeyword, + \Self.unexpectedBetweenIsKeywordAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } // MARK: - IsTypePatternSyntax @@ -4518,7 +4468,7 @@ public struct IsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxN public struct IsTypePatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .isTypePattern else { return nil } @@ -4614,13 +4564,11 @@ public struct IsTypePatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafP } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeIsKeyword, - \Self.isKeyword, - \Self.unexpectedBetweenIsKeywordAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeIsKeyword, + \Self.isKeyword, + \Self.unexpectedBetweenIsKeywordAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesJKLMN.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesJKLMN.swift index 605ea5af339..d4f30a1e54b 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesJKLMN.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesJKLMN.swift @@ -53,7 +53,7 @@ public struct KeyPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta self = .optional(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(KeyPathPropertyComponentSyntax.self) { self = .property(node) return @@ -142,7 +142,7 @@ public struct KeyPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .keyPathComponent else { return nil } @@ -238,15 +238,13 @@ public struct KeyPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePeriod, - \Self.period, - \Self.unexpectedBetweenPeriodAndComponent, - \Self.component, - \Self.unexpectedAfterComponent - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePeriod, + \Self.period, + \Self.unexpectedBetweenPeriodAndComponent, + \Self.component, + \Self.unexpectedAfterComponent + ]) } // MARK: - KeyPathExprSyntax @@ -267,7 +265,7 @@ public struct KeyPathComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public struct KeyPathExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .keyPathExpr else { return nil } @@ -414,17 +412,15 @@ public struct KeyPathExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBackslash, - \Self.backslash, - \Self.unexpectedBetweenBackslashAndRoot, - \Self.root, - \Self.unexpectedBetweenRootAndComponents, - \Self.components, - \Self.unexpectedAfterComponents - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBackslash, + \Self.backslash, + \Self.unexpectedBetweenBackslashAndRoot, + \Self.root, + \Self.unexpectedBetweenRootAndComponents, + \Self.components, + \Self.unexpectedAfterComponents + ]) } // MARK: - KeyPathOptionalComponentSyntax @@ -441,7 +437,7 @@ public struct KeyPathExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy public struct KeyPathOptionalComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .keyPathOptionalComponent else { return nil } @@ -507,9 +503,7 @@ public struct KeyPathOptionalComponentSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeQuestionOrExclamationMark, \Self.questionOrExclamationMark, \Self.unexpectedAfterQuestionOrExclamationMark]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeQuestionOrExclamationMark, \Self.questionOrExclamationMark, \Self.unexpectedAfterQuestionOrExclamationMark]) } // MARK: - KeyPathPropertyComponentSyntax @@ -527,7 +521,7 @@ public struct KeyPathOptionalComponentSyntax: SyntaxProtocol, SyntaxHashable, _L public struct KeyPathPropertyComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .keyPathPropertyComponent else { return nil } @@ -620,15 +614,13 @@ public struct KeyPathPropertyComponentSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDeclName, - \Self.declName, - \Self.unexpectedBetweenDeclNameAndGenericArgumentClause, - \Self.genericArgumentClause, - \Self.unexpectedAfterGenericArgumentClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDeclName, + \Self.declName, + \Self.unexpectedBetweenDeclNameAndGenericArgumentClause, + \Self.genericArgumentClause, + \Self.unexpectedAfterGenericArgumentClause + ]) } // MARK: - KeyPathSubscriptComponentSyntax @@ -647,7 +639,7 @@ public struct KeyPathPropertyComponentSyntax: SyntaxProtocol, SyntaxHashable, _L public struct KeyPathSubscriptComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .keyPathSubscriptComponent else { return nil } @@ -797,17 +789,15 @@ public struct KeyPathSubscriptComponentSyntax: SyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightSquare, - \Self.rightSquare, - \Self.unexpectedAfterRightSquare - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightSquare, + \Self.rightSquare, + \Self.unexpectedAfterRightSquare + ]) } // MARK: - LabeledExprSyntax @@ -831,7 +821,7 @@ public struct KeyPathSubscriptComponentSyntax: SyntaxProtocol, SyntaxHashable, _ public struct LabeledExprSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .labeledExpr else { return nil } @@ -983,19 +973,17 @@ public struct LabeledExprSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - LabeledSpecializeArgumentSyntax @@ -1015,7 +1003,7 @@ public struct LabeledExprSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode public struct LabeledSpecializeArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .labeledSpecializeArgument else { return nil } @@ -1182,19 +1170,17 @@ public struct LabeledSpecializeArgumentSyntax: SyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedBetweenValueAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedBetweenValueAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - LabeledStmtSyntax @@ -1207,7 +1193,7 @@ public struct LabeledSpecializeArgumentSyntax: SyntaxProtocol, SyntaxHashable, _ public struct LabeledStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .labeledStmt else { return nil } @@ -1330,17 +1316,15 @@ public struct LabeledStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndStatement, - \Self.statement, - \Self.unexpectedAfterStatement - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndStatement, + \Self.statement, + \Self.unexpectedAfterStatement + ]) } // MARK: - LayoutRequirementSyntax @@ -1362,7 +1346,7 @@ public struct LabeledStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSy public struct LayoutRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .layoutRequirement else { return nil } @@ -1629,27 +1613,25 @@ public struct LayoutRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeType, - \Self.type, - \Self.unexpectedBetweenTypeAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndLayoutSpecifier, - \Self.layoutSpecifier, - \Self.unexpectedBetweenLayoutSpecifierAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndSize, - \Self.size, - \Self.unexpectedBetweenSizeAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndAlignment, - \Self.alignment, - \Self.unexpectedBetweenAlignmentAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeType, + \Self.type, + \Self.unexpectedBetweenTypeAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndLayoutSpecifier, + \Self.layoutSpecifier, + \Self.unexpectedBetweenLayoutSpecifierAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndSize, + \Self.size, + \Self.unexpectedBetweenSizeAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndAlignment, + \Self.alignment, + \Self.unexpectedBetweenAlignmentAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - LifetimeSpecifierArgumentSyntax @@ -1671,7 +1653,7 @@ public struct LayoutRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct LifetimeSpecifierArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .lifetimeSpecifierArgument else { return nil } @@ -1779,39 +1761,40 @@ public struct LifetimeSpecifierArgumentSyntax: SyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeParameter, - \Self.parameter, - \Self.unexpectedBetweenParameterAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeParameter, + \Self.parameter, + \Self.unexpectedBetweenParameterAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } -// MARK: - LifetimeSpecifierArgumentsSyntax +// MARK: - LifetimeTypeSpecifierSyntax -/// An optional argument passed to a type parameter. -/// -/// ### Example -/// `borrow(data)` in `func foo(data: Array) -> borrow(data) ComplexReferenceType` +/// A specifier that specifies function parameter on whose lifetime a type depends /// /// - Experiment: Requires experimental feature `nonescapableTypes`. /// /// ### Children /// +/// - `dependsOnKeyword`: `dependsOn` /// - `leftParen`: `(` +/// - `scopedKeyword`: `scoped`? /// - `arguments`: `LifetimeSpecifierArgumentListSyntax` /// - `rightParen`: `)` +/// +/// ### Contained in +/// +/// - ``TypeSpecifierListSyntax`` #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) #endif -public struct LifetimeSpecifierArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { +public struct LifetimeTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { - guard node.raw.kind == .lifetimeSpecifierArguments else { + public init?(_ node: __shared some SyntaxProtocol) { + guard node.raw.kind == .lifetimeTypeSpecifier else { return nil } self._syntaxNode = node._syntaxNode @@ -1819,13 +1802,18 @@ public struct LifetimeSpecifierArgumentsSyntax: SyntaxProtocol, SyntaxHashable, /// - Parameters: /// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. - /// - arguments: The function parameters that the lifetime of the annotated type depends on. + /// - dependsOnKeyword: lifetime dependence specifier on the return type + /// - scopedKeyword: lifetime of return value is scoped to the lifetime of the original value /// - trailingTrivia: Trivia to be appended to the trailing trivia of the node’s last token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. public init( leadingTrivia: Trivia? = nil, - _ unexpectedBeforeLeftParen: UnexpectedNodesSyntax? = nil, + _ unexpectedBeforeDependsOnKeyword: UnexpectedNodesSyntax? = nil, + dependsOnKeyword: TokenSyntax = .keyword(.dependsOn), + _ unexpectedBetweenDependsOnKeywordAndLeftParen: UnexpectedNodesSyntax? = nil, leftParen: TokenSyntax = .leftParenToken(), - _ unexpectedBetweenLeftParenAndArguments: UnexpectedNodesSyntax? = nil, + _ unexpectedBetweenLeftParenAndScopedKeyword: UnexpectedNodesSyntax? = nil, + scopedKeyword: TokenSyntax? = nil, + _ unexpectedBetweenScopedKeywordAndArguments: UnexpectedNodesSyntax? = nil, arguments: LifetimeSpecifierArgumentListSyntax, _ unexpectedBetweenArgumentsAndRightParen: UnexpectedNodesSyntax? = nil, rightParen: TokenSyntax = .rightParenToken(), @@ -1836,25 +1824,33 @@ public struct LifetimeSpecifierArgumentsSyntax: SyntaxProtocol, SyntaxHashable, // Extend the lifetime of all parameters so their arenas don't get destroyed // before they can be added as children of the new arena. self = withExtendedLifetime((SyntaxArena(), ( - unexpectedBeforeLeftParen, + unexpectedBeforeDependsOnKeyword, + dependsOnKeyword, + unexpectedBetweenDependsOnKeywordAndLeftParen, leftParen, - unexpectedBetweenLeftParenAndArguments, + unexpectedBetweenLeftParenAndScopedKeyword, + scopedKeyword, + unexpectedBetweenScopedKeywordAndArguments, arguments, unexpectedBetweenArgumentsAndRightParen, rightParen, unexpectedAfterRightParen ))) { (arena, _) in let layout: [RawSyntax?] = [ - unexpectedBeforeLeftParen?.raw, + unexpectedBeforeDependsOnKeyword?.raw, + dependsOnKeyword.raw, + unexpectedBetweenDependsOnKeywordAndLeftParen?.raw, leftParen.raw, - unexpectedBetweenLeftParenAndArguments?.raw, + unexpectedBetweenLeftParenAndScopedKeyword?.raw, + scopedKeyword?.raw, + unexpectedBetweenScopedKeywordAndArguments?.raw, arguments.raw, unexpectedBetweenArgumentsAndRightParen?.raw, rightParen.raw, unexpectedAfterRightParen?.raw ] let raw = RawSyntax.makeLayout( - kind: SyntaxKind.lifetimeSpecifierArguments, + kind: SyntaxKind.lifetimeTypeSpecifier, from: layout, arena: arena, leadingTrivia: leadingTrivia, @@ -1865,248 +1861,161 @@ public struct LifetimeSpecifierArgumentsSyntax: SyntaxProtocol, SyntaxHashable, } } - public var unexpectedBeforeLeftParen: UnexpectedNodesSyntax? { + public var unexpectedBeforeDependsOnKeyword: UnexpectedNodesSyntax? { get { return Syntax(self).child(at: 0)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) + self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } + /// lifetime dependence specifier on the return type + /// /// ### Tokens /// - /// For syntax trees generated by the parser, this is guaranteed to be `(`. - public var leftParen: TokenSyntax { + /// For syntax trees generated by the parser, this is guaranteed to be `dependsOn`. + public var dependsOnKeyword: TokenSyntax { get { return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) + self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - public var unexpectedBetweenLeftParenAndArguments: UnexpectedNodesSyntax? { + public var unexpectedBetweenDependsOnKeywordAndLeftParen: UnexpectedNodesSyntax? { get { return Syntax(self).child(at: 2)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) + self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - /// The function parameters that the lifetime of the annotated type depends on. - public var arguments: LifetimeSpecifierArgumentListSyntax { + /// ### Tokens + /// + /// For syntax trees generated by the parser, this is guaranteed to be `(`. + public var leftParen: TokenSyntax { get { - return Syntax(self).child(at: 3)!.cast(LifetimeSpecifierArgumentListSyntax.self) + return Syntax(self).child(at: 3)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) - } - } - - /// Adds the provided `element` to the node's `arguments` - /// collection. - /// - /// - param element: The new `Arguments` to add to the node's - /// `arguments` collection. - /// - returns: A copy of the receiver with the provided `Arguments` - /// appended to its `arguments` collection. - @available(*, deprecated, message: "Use node.arguments.append(newElement) instead") - public func addArguments(_ element: LifetimeSpecifierArgumentSyntax) -> LifetimeSpecifierArgumentsSyntax { - var collection: RawSyntax - let arena = SyntaxArena() - if let col = raw.layoutView!.children[3] { - collection = col.layoutView!.appending(element.raw, arena: arena) - } else { - collection = RawSyntax.makeLayout(kind: SyntaxKind.lifetimeSpecifierArgumentList, - from: [element.raw], arena: arena) + self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } - return Syntax(self) - .replacingChild( - at: 3, - with: collection, - rawNodeArena: arena, - allocationArena: arena - ) - .cast(LifetimeSpecifierArgumentsSyntax.self) } - public var unexpectedBetweenArgumentsAndRightParen: UnexpectedNodesSyntax? { + public var unexpectedBetweenLeftParenAndScopedKeyword: UnexpectedNodesSyntax? { get { return Syntax(self).child(at: 4)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) + self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } + /// lifetime of return value is scoped to the lifetime of the original value + /// /// ### Tokens /// - /// For syntax trees generated by the parser, this is guaranteed to be `)`. - public var rightParen: TokenSyntax { + /// For syntax trees generated by the parser, this is guaranteed to be `scoped`. + public var scopedKeyword: TokenSyntax? { get { - return Syntax(self).child(at: 5)!.cast(TokenSyntax.self) + return Syntax(self).child(at: 5)?.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 5, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) + self = Syntax(self).replacingChild(at: 5, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - public var unexpectedAfterRightParen: UnexpectedNodesSyntax? { + public var unexpectedBetweenScopedKeywordAndArguments: UnexpectedNodesSyntax? { get { return Syntax(self).child(at: 6)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 6, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeSpecifierArgumentsSyntax.self) + self = Syntax(self).replacingChild(at: 6, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } -} - -// MARK: - LifetimeTypeSpecifierSyntax - -/// A specifier that specifies function parameter on whose lifetime a type depends -/// -/// - Experiment: Requires experimental feature `nonescapableTypes`. -/// -/// ### Children -/// -/// - `specifier`: (`_copy` | `_consume` | `_borrow` | `_mutate`) -/// - `arguments`: `LifetimeSpecifierArgumentsSyntax` -/// -/// ### Contained in -/// -/// - ``TypeSpecifierListSyntax`` -#if compiler(>=5.8) -@_spi(ExperimentalLanguageFeatures) -#endif -public struct LifetimeTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { - public let _syntaxNode: Syntax - - public init?(_ node: some SyntaxProtocol) { - guard node.raw.kind == .lifetimeTypeSpecifier else { - return nil - } - self._syntaxNode = node._syntaxNode - } - - /// - Parameters: - /// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. - /// - specifier: The specifier token that's attached to the type. - /// - trailingTrivia: Trivia to be appended to the trailing trivia of the node’s last token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. - public init( - leadingTrivia: Trivia? = nil, - _ unexpectedBeforeSpecifier: UnexpectedNodesSyntax? = nil, - specifier: TokenSyntax, - _ unexpectedBetweenSpecifierAndArguments: UnexpectedNodesSyntax? = nil, - arguments: LifetimeSpecifierArgumentsSyntax, - _ unexpectedAfterArguments: UnexpectedNodesSyntax? = nil, - trailingTrivia: Trivia? = nil - - ) { - // Extend the lifetime of all parameters so their arenas don't get destroyed - // before they can be added as children of the new arena. - self = withExtendedLifetime((SyntaxArena(), ( - unexpectedBeforeSpecifier, - specifier, - unexpectedBetweenSpecifierAndArguments, - arguments, - unexpectedAfterArguments - ))) { (arena, _) in - let layout: [RawSyntax?] = [ - unexpectedBeforeSpecifier?.raw, - specifier.raw, - unexpectedBetweenSpecifierAndArguments?.raw, - arguments.raw, - unexpectedAfterArguments?.raw - ] - let raw = RawSyntax.makeLayout( - kind: SyntaxKind.lifetimeTypeSpecifier, - from: layout, - arena: arena, - leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia - - ) - return Syntax.forRoot(raw, rawNodeArena: arena).cast(Self.self) - } - } - - public var unexpectedBeforeSpecifier: UnexpectedNodesSyntax? { + public var arguments: LifetimeSpecifierArgumentListSyntax { get { - return Syntax(self).child(at: 0)?.cast(UnexpectedNodesSyntax.self) + return Syntax(self).child(at: 7)!.cast(LifetimeSpecifierArgumentListSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 0, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) + self = Syntax(self).replacingChild(at: 7, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - /// The specifier token that's attached to the type. + /// Adds the provided `element` to the node's `arguments` + /// collection. /// - /// ### Tokens - /// - /// For syntax trees generated by the parser, this is guaranteed to be one of the following kinds: - /// - `_copy` - /// - `_consume` - /// - `_borrow` - /// - `_mutate` - public var specifier: TokenSyntax { - get { - return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) - } - set(value) { - self = Syntax(self).replacingChild(at: 1, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) + /// - param element: The new `Arguments` to add to the node's + /// `arguments` collection. + /// - returns: A copy of the receiver with the provided `Arguments` + /// appended to its `arguments` collection. + @available(*, deprecated, message: "Use node.arguments.append(newElement) instead") + public func addArguments(_ element: LifetimeSpecifierArgumentSyntax) -> LifetimeTypeSpecifierSyntax { + var collection: RawSyntax + let arena = SyntaxArena() + if let col = raw.layoutView!.children[7] { + collection = col.layoutView!.appending(element.raw, arena: arena) + } else { + collection = RawSyntax.makeLayout(kind: SyntaxKind.lifetimeSpecifierArgumentList, + from: [element.raw], arena: arena) } + return Syntax(self) + .replacingChild( + at: 7, + with: collection, + rawNodeArena: arena, + allocationArena: arena + ) + .cast(LifetimeTypeSpecifierSyntax.self) } - public var unexpectedBetweenSpecifierAndArguments: UnexpectedNodesSyntax? { + public var unexpectedBetweenArgumentsAndRightParen: UnexpectedNodesSyntax? { get { - return Syntax(self).child(at: 2)?.cast(UnexpectedNodesSyntax.self) + return Syntax(self).child(at: 8)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 2, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) + self = Syntax(self).replacingChild(at: 8, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - public var arguments: LifetimeSpecifierArgumentsSyntax { + /// ### Tokens + /// + /// For syntax trees generated by the parser, this is guaranteed to be `)`. + public var rightParen: TokenSyntax { get { - return Syntax(self).child(at: 3)!.cast(LifetimeSpecifierArgumentsSyntax.self) + return Syntax(self).child(at: 9)!.cast(TokenSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 3, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) + self = Syntax(self).replacingChild(at: 9, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - public var unexpectedAfterArguments: UnexpectedNodesSyntax? { + public var unexpectedAfterRightParen: UnexpectedNodesSyntax? { get { - return Syntax(self).child(at: 4)?.cast(UnexpectedNodesSyntax.self) + return Syntax(self).child(at: 10)?.cast(UnexpectedNodesSyntax.self) } set(value) { - self = Syntax(self).replacingChild(at: 4, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) + self = Syntax(self).replacingChild(at: 10, with: Syntax(value), arena: SyntaxArena()).cast(LifetimeTypeSpecifierSyntax.self) } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSpecifier, - \Self.specifier, - \Self.unexpectedBetweenSpecifierAndArguments, - \Self.arguments, - \Self.unexpectedAfterArguments - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDependsOnKeyword, + \Self.dependsOnKeyword, + \Self.unexpectedBetweenDependsOnKeywordAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndScopedKeyword, + \Self.scopedKeyword, + \Self.unexpectedBetweenScopedKeywordAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - MacroDeclSyntax @@ -2124,7 +2033,7 @@ public struct LifetimeTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _Leaf public struct MacroDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .macroDecl else { return nil } @@ -2425,27 +2334,25 @@ public struct MacroDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndMacroKeyword, - \Self.macroKeyword, - \Self.unexpectedBetweenMacroKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndSignature, - \Self.signature, - \Self.unexpectedBetweenSignatureAndDefinition, - \Self.definition, - \Self.unexpectedBetweenDefinitionAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedAfterGenericWhereClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndMacroKeyword, + \Self.macroKeyword, + \Self.unexpectedBetweenMacroKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndSignature, + \Self.signature, + \Self.unexpectedBetweenSignatureAndDefinition, + \Self.definition, + \Self.unexpectedBetweenDefinitionAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedAfterGenericWhereClause + ]) } // MARK: - MacroExpansionDeclSyntax @@ -2467,7 +2374,7 @@ public struct MacroDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSynt public struct MacroExpansionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .macroExpansionDecl else { return nil } @@ -2875,31 +2782,29 @@ public struct MacroExpansionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndPound, - \Self.pound, - \Self.unexpectedBetweenPoundAndMacroName, - \Self.macroName, - \Self.unexpectedBetweenMacroNameAndGenericArgumentClause, - \Self.genericArgumentClause, - \Self.unexpectedBetweenGenericArgumentClauseAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedBetweenRightParenAndTrailingClosure, - \Self.trailingClosure, - \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, - \Self.additionalTrailingClosures, - \Self.unexpectedAfterAdditionalTrailingClosures - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndPound, + \Self.pound, + \Self.unexpectedBetweenPoundAndMacroName, + \Self.macroName, + \Self.unexpectedBetweenMacroNameAndGenericArgumentClause, + \Self.genericArgumentClause, + \Self.unexpectedBetweenGenericArgumentClauseAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedBetweenRightParenAndTrailingClosure, + \Self.trailingClosure, + \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, + \Self.additionalTrailingClosures, + \Self.unexpectedAfterAdditionalTrailingClosures + ]) } // MARK: - MacroExpansionExprSyntax @@ -2919,7 +2824,7 @@ public struct MacroExpansionDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Lea public struct MacroExpansionExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .macroExpansionExpr else { return nil } @@ -3225,27 +3130,25 @@ public struct MacroExpansionExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePound, - \Self.pound, - \Self.unexpectedBetweenPoundAndMacroName, - \Self.macroName, - \Self.unexpectedBetweenMacroNameAndGenericArgumentClause, - \Self.genericArgumentClause, - \Self.unexpectedBetweenGenericArgumentClauseAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedBetweenRightParenAndTrailingClosure, - \Self.trailingClosure, - \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, - \Self.additionalTrailingClosures, - \Self.unexpectedAfterAdditionalTrailingClosures - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePound, + \Self.pound, + \Self.unexpectedBetweenPoundAndMacroName, + \Self.macroName, + \Self.unexpectedBetweenMacroNameAndGenericArgumentClause, + \Self.genericArgumentClause, + \Self.unexpectedBetweenGenericArgumentClauseAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedBetweenRightParenAndTrailingClosure, + \Self.trailingClosure, + \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, + \Self.additionalTrailingClosures, + \Self.unexpectedAfterAdditionalTrailingClosures + ]) } // MARK: - MatchingPatternConditionSyntax @@ -3263,7 +3166,7 @@ public struct MacroExpansionExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea public struct MatchingPatternConditionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .matchingPatternCondition else { return nil } @@ -3407,19 +3310,17 @@ public struct MatchingPatternConditionSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCaseKeyword, - \Self.caseKeyword, - \Self.unexpectedBetweenCaseKeywordAndPattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndTypeAnnotation, - \Self.typeAnnotation, - \Self.unexpectedBetweenTypeAnnotationAndInitializer, - \Self.initializer, - \Self.unexpectedAfterInitializer - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCaseKeyword, + \Self.caseKeyword, + \Self.unexpectedBetweenCaseKeywordAndPattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndTypeAnnotation, + \Self.typeAnnotation, + \Self.unexpectedBetweenTypeAnnotationAndInitializer, + \Self.initializer, + \Self.unexpectedAfterInitializer + ]) } // MARK: - MemberAccessExprSyntax @@ -3434,7 +3335,7 @@ public struct MatchingPatternConditionSyntax: SyntaxProtocol, SyntaxHashable, _L public struct MemberAccessExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .memberAccessExpr else { return nil } @@ -3558,17 +3459,15 @@ public struct MemberAccessExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBase, - \Self.base, - \Self.unexpectedBetweenBaseAndPeriod, - \Self.period, - \Self.unexpectedBetweenPeriodAndDeclName, - \Self.declName, - \Self.unexpectedAfterDeclName - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBase, + \Self.base, + \Self.unexpectedBetweenBaseAndPeriod, + \Self.period, + \Self.unexpectedBetweenPeriodAndDeclName, + \Self.declName, + \Self.unexpectedAfterDeclName + ]) } // MARK: - MemberBlockItemSyntax @@ -3586,7 +3485,7 @@ public struct MemberAccessExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE public struct MemberBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .memberBlockItem else { return nil } @@ -3687,15 +3586,13 @@ public struct MemberBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDecl, - \Self.decl, - \Self.unexpectedBetweenDeclAndSemicolon, - \Self.semicolon, - \Self.unexpectedAfterSemicolon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDecl, + \Self.decl, + \Self.unexpectedBetweenDeclAndSemicolon, + \Self.semicolon, + \Self.unexpectedAfterSemicolon + ]) } // MARK: - MemberBlockSyntax @@ -3717,7 +3614,7 @@ public struct MemberBlockItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax public struct MemberBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .memberBlock else { return nil } @@ -3867,17 +3764,15 @@ public struct MemberBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftBrace, - \Self.leftBrace, - \Self.unexpectedBetweenLeftBraceAndMembers, - \Self.members, - \Self.unexpectedBetweenMembersAndRightBrace, - \Self.rightBrace, - \Self.unexpectedAfterRightBrace - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftBrace, + \Self.leftBrace, + \Self.unexpectedBetweenLeftBraceAndMembers, + \Self.members, + \Self.unexpectedBetweenMembersAndRightBrace, + \Self.rightBrace, + \Self.unexpectedAfterRightBrace + ]) } // MARK: - MemberTypeSyntax @@ -3891,7 +3786,7 @@ public struct MemberBlockSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode public struct MemberTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .memberType else { return nil } @@ -4040,19 +3935,17 @@ public struct MemberTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBaseType, - \Self.baseType, - \Self.unexpectedBetweenBaseTypeAndPeriod, - \Self.period, - \Self.unexpectedBetweenPeriodAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericArgumentClause, - \Self.genericArgumentClause, - \Self.unexpectedAfterGenericArgumentClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBaseType, + \Self.baseType, + \Self.unexpectedBetweenBaseTypeAndPeriod, + \Self.period, + \Self.unexpectedBetweenPeriodAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericArgumentClause, + \Self.genericArgumentClause, + \Self.unexpectedAfterGenericArgumentClause + ]) } // MARK: - MetatypeTypeSyntax @@ -4065,7 +3958,7 @@ public struct MemberTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyn public struct MetatypeTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .metatypeType else { return nil } @@ -4190,17 +4083,15 @@ public struct MetatypeTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBaseType, - \Self.baseType, - \Self.unexpectedBetweenBaseTypeAndPeriod, - \Self.period, - \Self.unexpectedBetweenPeriodAndMetatypeSpecifier, - \Self.metatypeSpecifier, - \Self.unexpectedAfterMetatypeSpecifier - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBaseType, + \Self.baseType, + \Self.unexpectedBetweenBaseTypeAndPeriod, + \Self.period, + \Self.unexpectedBetweenPeriodAndMetatypeSpecifier, + \Self.metatypeSpecifier, + \Self.unexpectedAfterMetatypeSpecifier + ]) } // MARK: - MissingDeclSyntax @@ -4215,7 +4106,7 @@ public struct MetatypeTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeS public struct MissingDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .missingDecl else { return nil } @@ -4398,17 +4289,15 @@ public struct MissingDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndPlaceholder, - \Self.placeholder, - \Self.unexpectedAfterPlaceholder - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndPlaceholder, + \Self.placeholder, + \Self.unexpectedAfterPlaceholder + ]) } // MARK: - MissingExprSyntax @@ -4421,7 +4310,7 @@ public struct MissingDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSy public struct MissingExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .missingExpr else { return nil } @@ -4490,9 +4379,7 @@ public struct MissingExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) } // MARK: - MissingPatternSyntax @@ -4505,7 +4392,7 @@ public struct MissingExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy public struct MissingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .missingPattern else { return nil } @@ -4574,9 +4461,7 @@ public struct MissingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) } // MARK: - MissingStmtSyntax @@ -4589,7 +4474,7 @@ public struct MissingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _Leaf public struct MissingStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .missingStmt else { return nil } @@ -4658,9 +4543,7 @@ public struct MissingStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSy } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) } // MARK: - MissingSyntax @@ -4673,7 +4556,7 @@ public struct MissingStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSy public struct MissingSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .missing else { return nil } @@ -4742,9 +4625,7 @@ public struct MissingSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProt } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) } // MARK: - MissingTypeSyntax @@ -4757,7 +4638,7 @@ public struct MissingSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProt public struct MissingTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .missingType else { return nil } @@ -4826,9 +4707,7 @@ public struct MissingTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSy } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePlaceholder, \Self.placeholder, \Self.unexpectedAfterPlaceholder]) } // MARK: - MultipleTrailingClosureElementSyntax @@ -4845,7 +4724,7 @@ public struct MissingTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSy public struct MultipleTrailingClosureElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .multipleTrailingClosureElement else { return nil } @@ -4970,17 +4849,15 @@ public struct MultipleTrailingClosureElementSyntax: SyntaxProtocol, SyntaxHashab } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndClosure, - \Self.closure, - \Self.unexpectedAfterClosure - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndClosure, + \Self.closure, + \Self.unexpectedAfterClosure + ]) } // MARK: - NamedOpaqueReturnTypeSyntax @@ -4992,7 +4869,7 @@ public struct MultipleTrailingClosureElementSyntax: SyntaxProtocol, SyntaxHashab public struct NamedOpaqueReturnTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .namedOpaqueReturnType else { return nil } @@ -5087,15 +4964,13 @@ public struct NamedOpaqueReturnTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } // MARK: - NilLiteralExprSyntax @@ -5106,7 +4981,7 @@ public struct NamedOpaqueReturnTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _ public struct NilLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .nilLiteralExpr else { return nil } @@ -5170,7 +5045,5 @@ public struct NilLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExp } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeNilKeyword, \Self.nilKeyword, \Self.unexpectedAfterNilKeyword]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeNilKeyword, \Self.nilKeyword, \Self.unexpectedAfterNilKeyword]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesOP.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesOP.swift index 1403ee2ea3f..76a1e9e0384 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesOP.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesOP.swift @@ -27,7 +27,7 @@ public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .objCSelectorPiece else { return nil } @@ -36,6 +36,8 @@ public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt /// - Parameters: /// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. + /// - name: The identifier name for a nullary selection, if it exists. + /// - colon: The colon separating the label and the value or a colon representing an unlabeled argument /// - trailingTrivia: Trivia to be appended to the trailing trivia of the node’s last token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. public init( leadingTrivia: Trivia? = nil, @@ -84,6 +86,7 @@ public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } + /// The identifier name for a nullary selection, if it exists. public var name: TokenSyntax? { get { return Syntax(self).child(at: 1)?.cast(TokenSyntax.self) @@ -102,6 +105,8 @@ public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } + /// The colon separating the label and the value or a colon representing an unlabeled argument + /// /// ### Tokens /// /// For syntax trees generated by the parser, this is guaranteed to be `:`. @@ -123,15 +128,13 @@ public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndColon, - \Self.colon, - \Self.unexpectedAfterColon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndColon, + \Self.colon, + \Self.unexpectedAfterColon + ]) } // MARK: - OpaqueReturnTypeOfAttributeArgumentsSyntax @@ -150,7 +153,7 @@ public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct OpaqueReturnTypeOfAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .opaqueReturnTypeOfAttributeArguments else { return nil } @@ -278,17 +281,15 @@ public struct OpaqueReturnTypeOfAttributeArgumentsSyntax: SyntaxProtocol, Syntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeMangledName, - \Self.mangledName, - \Self.unexpectedBetweenMangledNameAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndOrdinal, - \Self.ordinal, - \Self.unexpectedAfterOrdinal - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeMangledName, + \Self.mangledName, + \Self.unexpectedBetweenMangledNameAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndOrdinal, + \Self.ordinal, + \Self.unexpectedAfterOrdinal + ]) } // MARK: - OperatorDeclSyntax @@ -304,7 +305,7 @@ public struct OpaqueReturnTypeOfAttributeArgumentsSyntax: SyntaxProtocol, Syntax public struct OperatorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .operatorDecl else { return nil } @@ -465,19 +466,17 @@ public struct OperatorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeFixitySpecifier, - \Self.fixitySpecifier, - \Self.unexpectedBetweenFixitySpecifierAndOperatorKeyword, - \Self.operatorKeyword, - \Self.unexpectedBetweenOperatorKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndOperatorPrecedenceAndTypes, - \Self.operatorPrecedenceAndTypes, - \Self.unexpectedAfterOperatorPrecedenceAndTypes - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeFixitySpecifier, + \Self.fixitySpecifier, + \Self.unexpectedBetweenFixitySpecifierAndOperatorKeyword, + \Self.operatorKeyword, + \Self.unexpectedBetweenOperatorKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndOperatorPrecedenceAndTypes, + \Self.operatorPrecedenceAndTypes, + \Self.unexpectedAfterOperatorPrecedenceAndTypes + ]) } // MARK: - OperatorPrecedenceAndTypesSyntax @@ -496,7 +495,7 @@ public struct OperatorDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS public struct OperatorPrecedenceAndTypesSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .operatorPrecedenceAndTypes else { return nil } @@ -651,17 +650,15 @@ public struct OperatorPrecedenceAndTypesSyntax: SyntaxProtocol, SyntaxHashable, } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeColon, - \Self.colon, - \Self.unexpectedBetweenColonAndPrecedenceGroup, - \Self.precedenceGroup, - \Self.unexpectedBetweenPrecedenceGroupAndDesignatedTypes, - \Self.designatedTypes, - \Self.unexpectedAfterDesignatedTypes - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeColon, + \Self.colon, + \Self.unexpectedBetweenColonAndPrecedenceGroup, + \Self.precedenceGroup, + \Self.unexpectedBetweenPrecedenceGroupAndDesignatedTypes, + \Self.designatedTypes, + \Self.unexpectedAfterDesignatedTypes + ]) } // MARK: - OptionalBindingConditionSyntax @@ -679,7 +676,7 @@ public struct OperatorPrecedenceAndTypesSyntax: SyntaxProtocol, SyntaxHashable, public struct OptionalBindingConditionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .optionalBindingCondition else { return nil } @@ -829,19 +826,17 @@ public struct OptionalBindingConditionSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBindingSpecifier, - \Self.bindingSpecifier, - \Self.unexpectedBetweenBindingSpecifierAndPattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndTypeAnnotation, - \Self.typeAnnotation, - \Self.unexpectedBetweenTypeAnnotationAndInitializer, - \Self.initializer, - \Self.unexpectedAfterInitializer - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBindingSpecifier, + \Self.bindingSpecifier, + \Self.unexpectedBetweenBindingSpecifierAndPattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndTypeAnnotation, + \Self.typeAnnotation, + \Self.unexpectedBetweenTypeAnnotationAndInitializer, + \Self.initializer, + \Self.unexpectedAfterInitializer + ]) } // MARK: - OptionalChainingExprSyntax @@ -853,7 +848,7 @@ public struct OptionalBindingConditionSyntax: SyntaxProtocol, SyntaxHashable, _L public struct OptionalChainingExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .optionalChainingExpr else { return nil } @@ -949,15 +944,13 @@ public struct OptionalChainingExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndQuestionMark, - \Self.questionMark, - \Self.unexpectedAfterQuestionMark - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndQuestionMark, + \Self.questionMark, + \Self.unexpectedAfterQuestionMark + ]) } // MARK: - OptionalTypeSyntax @@ -969,7 +962,7 @@ public struct OptionalChainingExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _L public struct OptionalTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .optionalType else { return nil } @@ -1065,15 +1058,13 @@ public struct OptionalTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWrappedType, - \Self.wrappedType, - \Self.unexpectedBetweenWrappedTypeAndQuestionMark, - \Self.questionMark, - \Self.unexpectedAfterQuestionMark - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWrappedType, + \Self.wrappedType, + \Self.unexpectedBetweenWrappedTypeAndQuestionMark, + \Self.questionMark, + \Self.unexpectedAfterQuestionMark + ]) } // MARK: - OriginallyDefinedInAttributeArgumentsSyntax @@ -1094,7 +1085,7 @@ public struct OptionalTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeS public struct OriginallyDefinedInAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .originallyDefinedInAttributeArguments else { return nil } @@ -1295,21 +1286,19 @@ public struct OriginallyDefinedInAttributeArgumentsSyntax: SyntaxProtocol, Synta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeModuleLabel, - \Self.moduleLabel, - \Self.unexpectedBetweenModuleLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndModuleName, - \Self.moduleName, - \Self.unexpectedBetweenModuleNameAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndPlatforms, - \Self.platforms, - \Self.unexpectedAfterPlatforms - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeModuleLabel, + \Self.moduleLabel, + \Self.unexpectedBetweenModuleLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndModuleName, + \Self.moduleName, + \Self.unexpectedBetweenModuleNameAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndPlatforms, + \Self.platforms, + \Self.unexpectedAfterPlatforms + ]) } // MARK: - PackElementExprSyntax @@ -1323,7 +1312,7 @@ public struct OriginallyDefinedInAttributeArgumentsSyntax: SyntaxProtocol, Synta public struct PackElementExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .packElementExpr else { return nil } @@ -1419,15 +1408,13 @@ public struct PackElementExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafEx } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeEachKeyword, - \Self.eachKeyword, - \Self.unexpectedBetweenEachKeywordAndPack, - \Self.pack, - \Self.unexpectedAfterPack - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeEachKeyword, + \Self.eachKeyword, + \Self.unexpectedBetweenEachKeywordAndPack, + \Self.pack, + \Self.unexpectedAfterPack + ]) } // MARK: - PackElementTypeSyntax @@ -1439,7 +1426,7 @@ public struct PackElementExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafEx public struct PackElementTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .packElementType else { return nil } @@ -1535,15 +1522,13 @@ public struct PackElementTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeEachKeyword, - \Self.eachKeyword, - \Self.unexpectedBetweenEachKeywordAndPack, - \Self.pack, - \Self.unexpectedAfterPack - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeEachKeyword, + \Self.eachKeyword, + \Self.unexpectedBetweenEachKeywordAndPack, + \Self.pack, + \Self.unexpectedAfterPack + ]) } // MARK: - PackExpansionExprSyntax @@ -1557,7 +1542,7 @@ public struct PackElementTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTy public struct PackExpansionExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .packExpansionExpr else { return nil } @@ -1653,15 +1638,13 @@ public struct PackExpansionExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeRepeatKeyword, - \Self.repeatKeyword, - \Self.unexpectedBetweenRepeatKeywordAndRepetitionPattern, - \Self.repetitionPattern, - \Self.unexpectedAfterRepetitionPattern - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeRepeatKeyword, + \Self.repeatKeyword, + \Self.unexpectedBetweenRepeatKeywordAndRepetitionPattern, + \Self.repetitionPattern, + \Self.unexpectedAfterRepetitionPattern + ]) } // MARK: - PackExpansionTypeSyntax @@ -1673,7 +1656,7 @@ public struct PackExpansionExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf public struct PackExpansionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .packExpansionType else { return nil } @@ -1769,15 +1752,13 @@ public struct PackExpansionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeRepeatKeyword, - \Self.repeatKeyword, - \Self.unexpectedBetweenRepeatKeywordAndRepetitionPattern, - \Self.repetitionPattern, - \Self.unexpectedAfterRepetitionPattern - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeRepeatKeyword, + \Self.repeatKeyword, + \Self.unexpectedBetweenRepeatKeywordAndRepetitionPattern, + \Self.repetitionPattern, + \Self.unexpectedAfterRepetitionPattern + ]) } // MARK: - PatternBindingSyntax @@ -1798,7 +1779,7 @@ public struct PackExpansionTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _Leaf public struct PatternBindingSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .patternBinding else { return nil } @@ -1986,21 +1967,19 @@ public struct PatternBindingSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndTypeAnnotation, - \Self.typeAnnotation, - \Self.unexpectedBetweenTypeAnnotationAndInitializer, - \Self.initializer, - \Self.unexpectedBetweenInitializerAndAccessorBlock, - \Self.accessorBlock, - \Self.unexpectedBetweenAccessorBlockAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndTypeAnnotation, + \Self.typeAnnotation, + \Self.unexpectedBetweenTypeAnnotationAndInitializer, + \Self.initializer, + \Self.unexpectedBetweenInitializerAndAccessorBlock, + \Self.accessorBlock, + \Self.unexpectedBetweenAccessorBlockAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - PatternExprSyntax @@ -2011,7 +1990,7 @@ public struct PatternBindingSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public struct PatternExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .patternExpr else { return nil } @@ -2072,9 +2051,7 @@ public struct PatternExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforePattern, \Self.pattern, \Self.unexpectedAfterPattern]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforePattern, \Self.pattern, \Self.unexpectedAfterPattern]) } // MARK: - PlatformVersionItemSyntax @@ -2092,7 +2069,7 @@ public struct PatternExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy public struct PlatformVersionItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .platformVersionItem else { return nil } @@ -2101,6 +2078,7 @@ public struct PlatformVersionItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy /// - Parameters: /// - leadingTrivia: Trivia to be prepended to the leading trivia of the node’s first token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. + /// - platformVersion: The platform/version pair, e.g. `iOS 10.1` /// - trailingComma: A trailing comma if the argument is followed by another argument /// - trailingTrivia: Trivia to be appended to the trailing trivia of the node’s last token. If the node is empty, there is no token to attach the trivia to and the parameter is ignored. public init( @@ -2150,6 +2128,7 @@ public struct PlatformVersionItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } + /// The platform/version pair, e.g. `iOS 10.1` public var platformVersion: PlatformVersionSyntax { get { return Syntax(self).child(at: 1)!.cast(PlatformVersionSyntax.self) @@ -2191,15 +2170,13 @@ public struct PlatformVersionItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePlatformVersion, - \Self.platformVersion, - \Self.unexpectedBetweenPlatformVersionAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePlatformVersion, + \Self.platformVersion, + \Self.unexpectedBetweenPlatformVersionAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - PlatformVersionSyntax @@ -2218,7 +2195,7 @@ public struct PlatformVersionItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy public struct PlatformVersionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .platformVersion else { return nil } @@ -2323,15 +2300,13 @@ public struct PlatformVersionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePlatform, - \Self.platform, - \Self.unexpectedBetweenPlatformAndVersion, - \Self.version, - \Self.unexpectedAfterVersion - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePlatform, + \Self.platform, + \Self.unexpectedBetweenPlatformAndVersion, + \Self.version, + \Self.unexpectedAfterVersion + ]) } // MARK: - PostfixIfConfigExprSyntax @@ -2343,7 +2318,7 @@ public struct PlatformVersionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax public struct PostfixIfConfigExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .postfixIfConfigExpr else { return nil } @@ -2436,15 +2411,13 @@ public struct PostfixIfConfigExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBase, - \Self.base, - \Self.unexpectedBetweenBaseAndConfig, - \Self.config, - \Self.unexpectedAfterConfig - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBase, + \Self.base, + \Self.unexpectedBetweenBaseAndConfig, + \Self.config, + \Self.unexpectedAfterConfig + ]) } // MARK: - PostfixOperatorExprSyntax @@ -2456,7 +2429,7 @@ public struct PostfixIfConfigExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Le public struct PostfixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .postfixOperatorExpr else { return nil } @@ -2552,15 +2525,13 @@ public struct PostfixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndOperator, - \Self.operator, - \Self.unexpectedAfterOperator - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndOperator, + \Self.operator, + \Self.unexpectedAfterOperator + ]) } // MARK: - PoundSourceLocationArgumentsSyntax @@ -2581,7 +2552,7 @@ public struct PostfixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Le public struct PoundSourceLocationArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .poundSourceLocationArguments else { return nil } @@ -2812,25 +2783,23 @@ public struct PoundSourceLocationArgumentsSyntax: SyntaxProtocol, SyntaxHashable } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeFileLabel, - \Self.fileLabel, - \Self.unexpectedBetweenFileLabelAndFileColon, - \Self.fileColon, - \Self.unexpectedBetweenFileColonAndFileName, - \Self.fileName, - \Self.unexpectedBetweenFileNameAndComma, - \Self.comma, - \Self.unexpectedBetweenCommaAndLineLabel, - \Self.lineLabel, - \Self.unexpectedBetweenLineLabelAndLineColon, - \Self.lineColon, - \Self.unexpectedBetweenLineColonAndLineNumber, - \Self.lineNumber, - \Self.unexpectedAfterLineNumber - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeFileLabel, + \Self.fileLabel, + \Self.unexpectedBetweenFileLabelAndFileColon, + \Self.fileColon, + \Self.unexpectedBetweenFileColonAndFileName, + \Self.fileName, + \Self.unexpectedBetweenFileNameAndComma, + \Self.comma, + \Self.unexpectedBetweenCommaAndLineLabel, + \Self.lineLabel, + \Self.unexpectedBetweenLineLabelAndLineColon, + \Self.lineColon, + \Self.unexpectedBetweenLineColonAndLineNumber, + \Self.lineNumber, + \Self.unexpectedAfterLineNumber + ]) } // MARK: - PoundSourceLocationSyntax @@ -2844,7 +2813,7 @@ public struct PoundSourceLocationArgumentsSyntax: SyntaxProtocol, SyntaxHashable public struct PoundSourceLocationSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .poundSourceLocation else { return nil } @@ -2994,19 +2963,17 @@ public struct PoundSourceLocationSyntax: DeclSyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePoundSourceLocation, - \Self.poundSourceLocation, - \Self.unexpectedBetweenPoundSourceLocationAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePoundSourceLocation, + \Self.poundSourceLocation, + \Self.unexpectedBetweenPoundSourceLocationAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - PrecedenceGroupAssignmentSyntax @@ -3025,7 +2992,7 @@ public struct PoundSourceLocationSyntax: DeclSyntaxProtocol, SyntaxHashable, _Le public struct PrecedenceGroupAssignmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .precedenceGroupAssignment else { return nil } @@ -3156,17 +3123,15 @@ public struct PrecedenceGroupAssignmentSyntax: SyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAssignmentLabel, - \Self.assignmentLabel, - \Self.unexpectedBetweenAssignmentLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedAfterValue - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAssignmentLabel, + \Self.assignmentLabel, + \Self.unexpectedBetweenAssignmentLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedAfterValue + ]) } // MARK: - PrecedenceGroupAssociativitySyntax @@ -3185,7 +3150,7 @@ public struct PrecedenceGroupAssignmentSyntax: SyntaxProtocol, SyntaxHashable, _ public struct PrecedenceGroupAssociativitySyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .precedenceGroupAssociativity else { return nil } @@ -3317,17 +3282,15 @@ public struct PrecedenceGroupAssociativitySyntax: SyntaxProtocol, SyntaxHashable } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAssociativityLabel, - \Self.associativityLabel, - \Self.unexpectedBetweenAssociativityLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndValue, - \Self.value, - \Self.unexpectedAfterValue - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAssociativityLabel, + \Self.associativityLabel, + \Self.unexpectedBetweenAssociativityLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndValue, + \Self.value, + \Self.unexpectedAfterValue + ]) } // MARK: - PrecedenceGroupDeclSyntax @@ -3346,7 +3309,7 @@ public struct PrecedenceGroupAssociativitySyntax: SyntaxProtocol, SyntaxHashable public struct PrecedenceGroupDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .precedenceGroupDecl else { return nil } @@ -3661,25 +3624,23 @@ public struct PrecedenceGroupDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndPrecedencegroupKeyword, - \Self.precedencegroupKeyword, - \Self.unexpectedBetweenPrecedencegroupKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndLeftBrace, - \Self.leftBrace, - \Self.unexpectedBetweenLeftBraceAndGroupAttributes, - \Self.groupAttributes, - \Self.unexpectedBetweenGroupAttributesAndRightBrace, - \Self.rightBrace, - \Self.unexpectedAfterRightBrace - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndPrecedencegroupKeyword, + \Self.precedencegroupKeyword, + \Self.unexpectedBetweenPrecedencegroupKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndLeftBrace, + \Self.leftBrace, + \Self.unexpectedBetweenLeftBraceAndGroupAttributes, + \Self.groupAttributes, + \Self.unexpectedBetweenGroupAttributesAndRightBrace, + \Self.rightBrace, + \Self.unexpectedAfterRightBrace + ]) } // MARK: - PrecedenceGroupNameSyntax @@ -3695,7 +3656,7 @@ public struct PrecedenceGroupDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _Le public struct PrecedenceGroupNameSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .precedenceGroupName else { return nil } @@ -3794,15 +3755,13 @@ public struct PrecedenceGroupNameSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - PrecedenceGroupRelationSyntax @@ -3821,7 +3780,7 @@ public struct PrecedenceGroupNameSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy public struct PrecedenceGroupRelationSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .precedenceGroupRelation else { return nil } @@ -3978,17 +3937,15 @@ public struct PrecedenceGroupRelationSyntax: SyntaxProtocol, SyntaxHashable, _Le } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeHigherThanOrLowerThanLabel, - \Self.higherThanOrLowerThanLabel, - \Self.unexpectedBetweenHigherThanOrLowerThanLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndPrecedenceGroups, - \Self.precedenceGroups, - \Self.unexpectedAfterPrecedenceGroups - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeHigherThanOrLowerThanLabel, + \Self.higherThanOrLowerThanLabel, + \Self.unexpectedBetweenHigherThanOrLowerThanLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndPrecedenceGroups, + \Self.precedenceGroups, + \Self.unexpectedAfterPrecedenceGroups + ]) } // MARK: - PrefixOperatorExprSyntax @@ -4012,7 +3969,7 @@ public struct PrecedenceGroupRelationSyntax: SyntaxProtocol, SyntaxHashable, _Le public struct PrefixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .prefixOperatorExpr else { return nil } @@ -4108,15 +4065,13 @@ public struct PrefixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeOperator, - \Self.operator, - \Self.unexpectedBetweenOperatorAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeOperator, + \Self.operator, + \Self.unexpectedBetweenOperatorAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - PrimaryAssociatedTypeClauseSyntax @@ -4133,7 +4088,7 @@ public struct PrefixOperatorExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Lea public struct PrimaryAssociatedTypeClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .primaryAssociatedTypeClause else { return nil } @@ -4283,17 +4238,15 @@ public struct PrimaryAssociatedTypeClauseSyntax: SyntaxProtocol, SyntaxHashable, } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftAngle, - \Self.leftAngle, - \Self.unexpectedBetweenLeftAngleAndPrimaryAssociatedTypes, - \Self.primaryAssociatedTypes, - \Self.unexpectedBetweenPrimaryAssociatedTypesAndRightAngle, - \Self.rightAngle, - \Self.unexpectedAfterRightAngle - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftAngle, + \Self.leftAngle, + \Self.unexpectedBetweenLeftAngleAndPrimaryAssociatedTypes, + \Self.primaryAssociatedTypes, + \Self.unexpectedBetweenPrimaryAssociatedTypesAndRightAngle, + \Self.rightAngle, + \Self.unexpectedAfterRightAngle + ]) } // MARK: - PrimaryAssociatedTypeSyntax @@ -4309,7 +4262,7 @@ public struct PrimaryAssociatedTypeClauseSyntax: SyntaxProtocol, SyntaxHashable, public struct PrimaryAssociatedTypeSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .primaryAssociatedType else { return nil } @@ -4408,15 +4361,13 @@ public struct PrimaryAssociatedTypeSyntax: SyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeName, - \Self.name, - \Self.unexpectedBetweenNameAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeName, + \Self.name, + \Self.unexpectedBetweenNameAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - ProtocolDeclSyntax @@ -4444,7 +4395,7 @@ public struct PrimaryAssociatedTypeSyntax: SyntaxProtocol, SyntaxHashable, _Leaf public struct ProtocolDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .protocolDecl else { return nil } @@ -4759,25 +4710,23 @@ public struct ProtocolDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndProtocolKeyword, - \Self.protocolKeyword, - \Self.unexpectedBetweenProtocolKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndPrimaryAssociatedTypeClause, - \Self.primaryAssociatedTypeClause, - \Self.unexpectedBetweenPrimaryAssociatedTypeClauseAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, - \Self.memberBlock, - \Self.unexpectedAfterMemberBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndProtocolKeyword, + \Self.protocolKeyword, + \Self.unexpectedBetweenProtocolKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndPrimaryAssociatedTypeClause, + \Self.primaryAssociatedTypeClause, + \Self.unexpectedBetweenPrimaryAssociatedTypeClauseAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, + \Self.memberBlock, + \Self.unexpectedAfterMemberBlock + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesQRS.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesQRS.swift index c58d6442104..0df6173d922 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesQRS.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesQRS.swift @@ -24,7 +24,7 @@ public struct RegexLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .regexLiteralExpr else { return nil } @@ -204,21 +204,19 @@ public struct RegexLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeOpeningPounds, - \Self.openingPounds, - \Self.unexpectedBetweenOpeningPoundsAndOpeningSlash, - \Self.openingSlash, - \Self.unexpectedBetweenOpeningSlashAndRegex, - \Self.regex, - \Self.unexpectedBetweenRegexAndClosingSlash, - \Self.closingSlash, - \Self.unexpectedBetweenClosingSlashAndClosingPounds, - \Self.closingPounds, - \Self.unexpectedAfterClosingPounds - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeOpeningPounds, + \Self.openingPounds, + \Self.unexpectedBetweenOpeningPoundsAndOpeningSlash, + \Self.openingSlash, + \Self.unexpectedBetweenOpeningSlashAndRegex, + \Self.regex, + \Self.unexpectedBetweenRegexAndClosingSlash, + \Self.closingSlash, + \Self.unexpectedBetweenClosingSlashAndClosingPounds, + \Self.closingPounds, + \Self.unexpectedAfterClosingPounds + ]) } // MARK: - RepeatStmtSyntax @@ -232,7 +230,7 @@ public struct RegexLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE public struct RepeatStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .repeatStmt else { return nil } @@ -379,19 +377,17 @@ public struct RepeatStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeRepeatKeyword, - \Self.repeatKeyword, - \Self.unexpectedBetweenRepeatKeywordAndBody, - \Self.body, - \Self.unexpectedBetweenBodyAndWhileKeyword, - \Self.whileKeyword, - \Self.unexpectedBetweenWhileKeywordAndCondition, - \Self.condition, - \Self.unexpectedAfterCondition - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeRepeatKeyword, + \Self.repeatKeyword, + \Self.unexpectedBetweenRepeatKeywordAndBody, + \Self.body, + \Self.unexpectedBetweenBodyAndWhileKeyword, + \Self.whileKeyword, + \Self.unexpectedBetweenWhileKeywordAndCondition, + \Self.condition, + \Self.unexpectedAfterCondition + ]) } // MARK: - ReturnClauseSyntax @@ -410,7 +406,7 @@ public struct RepeatStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyn public struct ReturnClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .returnClause else { return nil } @@ -506,15 +502,13 @@ public struct ReturnClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeArrow, - \Self.arrow, - \Self.unexpectedBetweenArrowAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeArrow, + \Self.arrow, + \Self.unexpectedBetweenArrowAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } // MARK: - ReturnStmtSyntax @@ -526,7 +520,7 @@ public struct ReturnClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod public struct ReturnStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .returnStmt else { return nil } @@ -622,15 +616,13 @@ public struct ReturnStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeReturnKeyword, - \Self.returnKeyword, - \Self.unexpectedBetweenReturnKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeReturnKeyword, + \Self.returnKeyword, + \Self.unexpectedBetweenReturnKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - SameTypeRequirementSyntax @@ -647,7 +639,7 @@ public struct ReturnStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyn public struct SameTypeRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .sameTypeRequirement else { return nil } @@ -770,17 +762,15 @@ public struct SameTypeRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftType, - \Self.leftType, - \Self.unexpectedBetweenLeftTypeAndEqual, - \Self.equal, - \Self.unexpectedBetweenEqualAndRightType, - \Self.rightType, - \Self.unexpectedAfterRightType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftType, + \Self.leftType, + \Self.unexpectedBetweenLeftTypeAndEqual, + \Self.equal, + \Self.unexpectedBetweenEqualAndRightType, + \Self.rightType, + \Self.unexpectedAfterRightType + ]) } // MARK: - SequenceExprSyntax @@ -799,7 +789,7 @@ public struct SameTypeRequirementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy public struct SequenceExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .sequenceExpr else { return nil } @@ -887,9 +877,7 @@ public struct SequenceExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprS } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeElements, \Self.elements, \Self.unexpectedAfterElements]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeElements, \Self.elements, \Self.unexpectedAfterElements]) } // MARK: - SimpleStringLiteralExprSyntax @@ -909,7 +897,7 @@ public struct SequenceExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprS public struct SimpleStringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .simpleStringLiteralExpr else { return nil } @@ -1071,17 +1059,15 @@ public struct SimpleStringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeOpeningQuote, - \Self.openingQuote, - \Self.unexpectedBetweenOpeningQuoteAndSegments, - \Self.segments, - \Self.unexpectedBetweenSegmentsAndClosingQuote, - \Self.closingQuote, - \Self.unexpectedAfterClosingQuote - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeOpeningQuote, + \Self.openingQuote, + \Self.unexpectedBetweenOpeningQuoteAndSegments, + \Self.segments, + \Self.unexpectedBetweenSegmentsAndClosingQuote, + \Self.closingQuote, + \Self.unexpectedAfterClosingQuote + ]) } // MARK: - SimpleTypeSpecifierSyntax @@ -1090,7 +1076,7 @@ public struct SimpleStringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, /// /// ### Children /// -/// - `specifier`: (`inout` | `__shared` | `__owned` | `isolated` | `_const` | `borrowing` | `consuming` | `transferring` | `_resultDependsOn`) +/// - `specifier`: (`inout` | `__shared` | `__owned` | `isolated` | `_const` | `borrowing` | `consuming` | `_resultDependsOn` | `sending`) /// /// ### Contained in /// @@ -1098,7 +1084,7 @@ public struct SimpleStringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, public struct SimpleTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .simpleTypeSpecifier else { return nil } @@ -1154,8 +1140,8 @@ public struct SimpleTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy /// - `_const` /// - `borrowing` /// - `consuming` - /// - `transferring` /// - `_resultDependsOn` + /// - `sending` public var specifier: TokenSyntax { get { return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) @@ -1174,9 +1160,7 @@ public struct SimpleTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeSpecifier, \Self.specifier, \Self.unexpectedAfterSpecifier]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeSpecifier, \Self.specifier, \Self.unexpectedAfterSpecifier]) } // MARK: - SomeOrAnyTypeSyntax @@ -1188,7 +1172,7 @@ public struct SimpleTypeSpecifierSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy public struct SomeOrAnyTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .someOrAnyType else { return nil } @@ -1286,15 +1270,13 @@ public struct SomeOrAnyTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafType } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSomeOrAnySpecifier, - \Self.someOrAnySpecifier, - \Self.unexpectedBetweenSomeOrAnySpecifierAndConstraint, - \Self.constraint, - \Self.unexpectedAfterConstraint - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeSomeOrAnySpecifier, + \Self.someOrAnySpecifier, + \Self.unexpectedBetweenSomeOrAnySpecifierAndConstraint, + \Self.constraint, + \Self.unexpectedAfterConstraint + ]) } // MARK: - SourceFileSyntax @@ -1307,7 +1289,7 @@ public struct SomeOrAnyTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafType public struct SourceFileSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .sourceFile else { return nil } @@ -1460,17 +1442,15 @@ public struct SourceFileSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeP } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeShebang, - \Self.shebang, - \Self.unexpectedBetweenShebangAndStatements, - \Self.statements, - \Self.unexpectedBetweenStatementsAndEndOfFileToken, - \Self.endOfFileToken, - \Self.unexpectedAfterEndOfFileToken - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeShebang, + \Self.shebang, + \Self.unexpectedBetweenShebangAndStatements, + \Self.statements, + \Self.unexpectedBetweenStatementsAndEndOfFileToken, + \Self.endOfFileToken, + \Self.unexpectedAfterEndOfFileToken + ]) } // MARK: - SpecializeAvailabilityArgumentSyntax @@ -1490,7 +1470,7 @@ public struct SourceFileSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeP public struct SpecializeAvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .specializeAvailabilityArgument else { return nil } @@ -1673,19 +1653,17 @@ public struct SpecializeAvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashab } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAvailabilityLabel, - \Self.availabilityLabel, - \Self.unexpectedBetweenAvailabilityLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndAvailabilityArguments, - \Self.availabilityArguments, - \Self.unexpectedBetweenAvailabilityArgumentsAndSemicolon, - \Self.semicolon, - \Self.unexpectedAfterSemicolon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAvailabilityLabel, + \Self.availabilityLabel, + \Self.unexpectedBetweenAvailabilityLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndAvailabilityArguments, + \Self.availabilityArguments, + \Self.unexpectedBetweenAvailabilityArgumentsAndSemicolon, + \Self.semicolon, + \Self.unexpectedAfterSemicolon + ]) } // MARK: - SpecializeTargetFunctionArgumentSyntax @@ -1705,7 +1683,7 @@ public struct SpecializeAvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashab public struct SpecializeTargetFunctionArgumentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .specializeTargetFunctionArgument else { return nil } @@ -1866,19 +1844,17 @@ public struct SpecializeTargetFunctionArgumentSyntax: SyntaxProtocol, SyntaxHash } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeTargetLabel, - \Self.targetLabel, - \Self.unexpectedBetweenTargetLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndDeclName, - \Self.declName, - \Self.unexpectedBetweenDeclNameAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeTargetLabel, + \Self.targetLabel, + \Self.unexpectedBetweenTargetLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndDeclName, + \Self.declName, + \Self.unexpectedBetweenDeclNameAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - StringLiteralExprSyntax @@ -1912,7 +1888,7 @@ public struct SpecializeTargetFunctionArgumentSyntax: SyntaxProtocol, SyntaxHash public struct StringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .stringLiteralExpr else { return nil } @@ -2122,21 +2098,19 @@ public struct StringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeOpeningPounds, - \Self.openingPounds, - \Self.unexpectedBetweenOpeningPoundsAndOpeningQuote, - \Self.openingQuote, - \Self.unexpectedBetweenOpeningQuoteAndSegments, - \Self.segments, - \Self.unexpectedBetweenSegmentsAndClosingQuote, - \Self.closingQuote, - \Self.unexpectedBetweenClosingQuoteAndClosingPounds, - \Self.closingPounds, - \Self.unexpectedAfterClosingPounds - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeOpeningPounds, + \Self.openingPounds, + \Self.unexpectedBetweenOpeningPoundsAndOpeningQuote, + \Self.openingQuote, + \Self.unexpectedBetweenOpeningQuoteAndSegments, + \Self.segments, + \Self.unexpectedBetweenSegmentsAndClosingQuote, + \Self.closingQuote, + \Self.unexpectedBetweenClosingQuoteAndClosingPounds, + \Self.closingPounds, + \Self.unexpectedAfterClosingPounds + ]) } // MARK: - StringSegmentSyntax @@ -2156,7 +2130,7 @@ public struct StringLiteralExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf public struct StringSegmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .stringSegment else { return nil } @@ -2220,9 +2194,7 @@ public struct StringSegmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeContent, \Self.content, \Self.unexpectedAfterContent]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeContent, \Self.content, \Self.unexpectedAfterContent]) } // MARK: - StructDeclSyntax @@ -2298,7 +2270,7 @@ public struct StringSegmentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNo public struct StructDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .structDecl else { return nil } @@ -2613,27 +2585,25 @@ public struct StructDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndStructKeyword, - \Self.structKeyword, - \Self.unexpectedBetweenStructKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, - \Self.inheritanceClause, - \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, - \Self.memberBlock, - \Self.unexpectedAfterMemberBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndStructKeyword, + \Self.structKeyword, + \Self.unexpectedBetweenStructKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndInheritanceClause, + \Self.inheritanceClause, + \Self.unexpectedBetweenInheritanceClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndMemberBlock, + \Self.memberBlock, + \Self.unexpectedAfterMemberBlock + ]) } // MARK: - SubscriptCallExprSyntax @@ -2649,7 +2619,7 @@ public struct StructDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyn public struct SubscriptCallExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .subscriptCallExpr else { return nil } @@ -2898,23 +2868,21 @@ public struct SubscriptCallExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCalledExpression, - \Self.calledExpression, - \Self.unexpectedBetweenCalledExpressionAndLeftSquare, - \Self.leftSquare, - \Self.unexpectedBetweenLeftSquareAndArguments, - \Self.arguments, - \Self.unexpectedBetweenArgumentsAndRightSquare, - \Self.rightSquare, - \Self.unexpectedBetweenRightSquareAndTrailingClosure, - \Self.trailingClosure, - \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, - \Self.additionalTrailingClosures, - \Self.unexpectedAfterAdditionalTrailingClosures - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCalledExpression, + \Self.calledExpression, + \Self.unexpectedBetweenCalledExpressionAndLeftSquare, + \Self.leftSquare, + \Self.unexpectedBetweenLeftSquareAndArguments, + \Self.arguments, + \Self.unexpectedBetweenArgumentsAndRightSquare, + \Self.rightSquare, + \Self.unexpectedBetweenRightSquareAndTrailingClosure, + \Self.trailingClosure, + \Self.unexpectedBetweenTrailingClosureAndAdditionalTrailingClosures, + \Self.additionalTrailingClosures, + \Self.unexpectedAfterAdditionalTrailingClosures + ]) } // MARK: - SubscriptDeclSyntax @@ -2932,7 +2900,7 @@ public struct SubscriptCallExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _Leaf public struct SubscriptDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .subscriptDecl else { return nil } @@ -3230,27 +3198,25 @@ public struct SubscriptDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDecl } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndSubscriptKeyword, - \Self.subscriptKeyword, - \Self.unexpectedBetweenSubscriptKeywordAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndParameterClause, - \Self.parameterClause, - \Self.unexpectedBetweenParameterClauseAndReturnClause, - \Self.returnClause, - \Self.unexpectedBetweenReturnClauseAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedBetweenGenericWhereClauseAndAccessorBlock, - \Self.accessorBlock, - \Self.unexpectedAfterAccessorBlock - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndSubscriptKeyword, + \Self.subscriptKeyword, + \Self.unexpectedBetweenSubscriptKeywordAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndParameterClause, + \Self.parameterClause, + \Self.unexpectedBetweenParameterClauseAndReturnClause, + \Self.returnClause, + \Self.unexpectedBetweenReturnClauseAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedBetweenGenericWhereClauseAndAccessorBlock, + \Self.accessorBlock, + \Self.unexpectedAfterAccessorBlock + ]) } // MARK: - SuperExprSyntax @@ -3261,7 +3227,7 @@ public struct SubscriptDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDecl public struct SuperExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .superExpr else { return nil } @@ -3325,9 +3291,7 @@ public struct SuperExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeSuperKeyword, \Self.superKeyword, \Self.unexpectedAfterSuperKeyword]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeSuperKeyword, \Self.superKeyword, \Self.unexpectedAfterSuperKeyword]) } // MARK: - SuppressedTypeSyntax @@ -3339,7 +3303,7 @@ public struct SuperExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt public struct SuppressedTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .suppressedType else { return nil } @@ -3435,15 +3399,13 @@ public struct SuppressedTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTyp } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWithoutTilde, - \Self.withoutTilde, - \Self.unexpectedBetweenWithoutTildeAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWithoutTilde, + \Self.withoutTilde, + \Self.unexpectedBetweenWithoutTildeAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } // MARK: - SwitchCaseItemSyntax @@ -3460,7 +3422,7 @@ public struct SuppressedTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTyp public struct SwitchCaseItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .switchCaseItem else { return nil } @@ -3580,17 +3542,15 @@ public struct SwitchCaseItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndWhereClause, - \Self.whereClause, - \Self.unexpectedBetweenWhereClauseAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndWhereClause, + \Self.whereClause, + \Self.unexpectedBetweenWhereClauseAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - SwitchCaseLabelSyntax @@ -3607,7 +3567,7 @@ public struct SwitchCaseItemSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public struct SwitchCaseLabelSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .switchCaseLabel else { return nil } @@ -3757,17 +3717,15 @@ public struct SwitchCaseLabelSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCaseKeyword, - \Self.caseKeyword, - \Self.unexpectedBetweenCaseKeywordAndCaseItems, - \Self.caseItems, - \Self.unexpectedBetweenCaseItemsAndColon, - \Self.colon, - \Self.unexpectedAfterColon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCaseKeyword, + \Self.caseKeyword, + \Self.unexpectedBetweenCaseKeywordAndCaseItems, + \Self.caseItems, + \Self.unexpectedBetweenCaseItemsAndColon, + \Self.colon, + \Self.unexpectedAfterColon + ]) } // MARK: - SwitchCaseSyntax @@ -3803,7 +3761,7 @@ public struct SwitchCaseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeP self = .case(node) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(SwitchDefaultLabelSyntax.self) { self = .default(node) return @@ -3866,7 +3824,7 @@ public struct SwitchCaseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeP public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .switchCase else { return nil } @@ -4012,17 +3970,15 @@ public struct SwitchCaseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeP } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttribute, - \Self.attribute, - \Self.unexpectedBetweenAttributeAndLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndStatements, - \Self.statements, - \Self.unexpectedAfterStatements - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttribute, + \Self.attribute, + \Self.unexpectedBetweenAttributeAndLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndStatements, + \Self.statements, + \Self.unexpectedAfterStatements + ]) } // MARK: - SwitchDefaultLabelSyntax @@ -4038,7 +3994,7 @@ public struct SwitchCaseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeP public struct SwitchDefaultLabelSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .switchDefaultLabel else { return nil } @@ -4137,15 +4093,13 @@ public struct SwitchDefaultLabelSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeDefaultKeyword, - \Self.defaultKeyword, - \Self.unexpectedBetweenDefaultKeywordAndColon, - \Self.colon, - \Self.unexpectedAfterColon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeDefaultKeyword, + \Self.defaultKeyword, + \Self.unexpectedBetweenDefaultKeywordAndColon, + \Self.colon, + \Self.unexpectedAfterColon + ]) } // MARK: - SwitchExprSyntax @@ -4173,7 +4127,7 @@ public struct SwitchDefaultLabelSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyn public struct SwitchExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .switchExpr else { return nil } @@ -4387,19 +4341,17 @@ public struct SwitchExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyn } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSwitchKeyword, - \Self.switchKeyword, - \Self.unexpectedBetweenSwitchKeywordAndSubject, - \Self.subject, - \Self.unexpectedBetweenSubjectAndLeftBrace, - \Self.leftBrace, - \Self.unexpectedBetweenLeftBraceAndCases, - \Self.cases, - \Self.unexpectedBetweenCasesAndRightBrace, - \Self.rightBrace, - \Self.unexpectedAfterRightBrace - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeSwitchKeyword, + \Self.switchKeyword, + \Self.unexpectedBetweenSwitchKeywordAndSubject, + \Self.subject, + \Self.unexpectedBetweenSubjectAndLeftBrace, + \Self.leftBrace, + \Self.unexpectedBetweenLeftBraceAndCases, + \Self.cases, + \Self.unexpectedBetweenCasesAndRightBrace, + \Self.rightBrace, + \Self.unexpectedAfterRightBrace + ]) } diff --git a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesTUVWXYZ.swift b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesTUVWXYZ.swift index e9e1eb7a67a..61a0750101c 100644 --- a/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesTUVWXYZ.swift +++ b/Sources/SwiftSyntax/generated/syntaxNodes/SyntaxNodesTUVWXYZ.swift @@ -35,7 +35,7 @@ public struct TernaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .ternaryExpr else { return nil } @@ -206,21 +206,19 @@ public struct TernaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeCondition, - \Self.condition, - \Self.unexpectedBetweenConditionAndQuestionMark, - \Self.questionMark, - \Self.unexpectedBetweenQuestionMarkAndThenExpression, - \Self.thenExpression, - \Self.unexpectedBetweenThenExpressionAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndElseExpression, - \Self.elseExpression, - \Self.unexpectedAfterElseExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeCondition, + \Self.condition, + \Self.unexpectedBetweenConditionAndQuestionMark, + \Self.questionMark, + \Self.unexpectedBetweenQuestionMarkAndThenExpression, + \Self.thenExpression, + \Self.unexpectedBetweenThenExpressionAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndElseExpression, + \Self.elseExpression, + \Self.unexpectedAfterElseExpression + ]) } // MARK: - ThenStmtSyntax @@ -245,7 +243,7 @@ public struct TernaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSy public struct ThenStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .thenStmt else { return nil } @@ -341,15 +339,13 @@ public struct ThenStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeThenKeyword, - \Self.thenKeyword, - \Self.unexpectedBetweenThenKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeThenKeyword, + \Self.thenKeyword, + \Self.unexpectedBetweenThenKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - ThrowStmtSyntax @@ -361,7 +357,7 @@ public struct ThenStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynta public struct ThrowStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .throwStmt else { return nil } @@ -457,15 +453,13 @@ public struct ThrowStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeThrowKeyword, - \Self.throwKeyword, - \Self.unexpectedBetweenThrowKeywordAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeThrowKeyword, + \Self.throwKeyword, + \Self.unexpectedBetweenThrowKeywordAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - ThrowsClauseSyntax @@ -486,7 +480,7 @@ public struct ThrowStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt public struct ThrowsClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .throwsClause else { return nil } @@ -649,19 +643,17 @@ public struct ThrowsClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeThrowsSpecifier, - \Self.throwsSpecifier, - \Self.unexpectedBetweenThrowsSpecifierAndLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndType, - \Self.type, - \Self.unexpectedBetweenTypeAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeThrowsSpecifier, + \Self.throwsSpecifier, + \Self.unexpectedBetweenThrowsSpecifierAndLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndType, + \Self.type, + \Self.unexpectedBetweenTypeAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - TryExprSyntax @@ -690,7 +682,7 @@ public struct ThrowsClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod public struct TryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .tryExpr else { return nil } @@ -815,17 +807,15 @@ public struct TryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntax } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeTryKeyword, - \Self.tryKeyword, - \Self.unexpectedBetweenTryKeywordAndQuestionOrExclamationMark, - \Self.questionOrExclamationMark, - \Self.unexpectedBetweenQuestionOrExclamationMarkAndExpression, - \Self.expression, - \Self.unexpectedAfterExpression - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeTryKeyword, + \Self.tryKeyword, + \Self.unexpectedBetweenTryKeywordAndQuestionOrExclamationMark, + \Self.questionOrExclamationMark, + \Self.unexpectedBetweenQuestionOrExclamationMarkAndExpression, + \Self.expression, + \Self.unexpectedAfterExpression + ]) } // MARK: - TupleExprSyntax @@ -838,7 +828,7 @@ public struct TryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntax public struct TupleExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .tupleExpr else { return nil } @@ -988,17 +978,15 @@ public struct TupleExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndElements, - \Self.elements, - \Self.unexpectedBetweenElementsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndElements, + \Self.elements, + \Self.unexpectedBetweenElementsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - TuplePatternElementSyntax @@ -1018,7 +1006,7 @@ public struct TupleExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynt public struct TuplePatternElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .tuplePatternElement else { return nil } @@ -1179,19 +1167,17 @@ public struct TuplePatternElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLabel, - \Self.label, - \Self.unexpectedBetweenLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndPattern, - \Self.pattern, - \Self.unexpectedBetweenPatternAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLabel, + \Self.label, + \Self.unexpectedBetweenLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndPattern, + \Self.pattern, + \Self.unexpectedBetweenPatternAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - TuplePatternSyntax @@ -1215,7 +1201,7 @@ public struct TuplePatternElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSy public struct TuplePatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .tuplePattern else { return nil } @@ -1371,17 +1357,15 @@ public struct TuplePatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPa } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndElements, - \Self.elements, - \Self.unexpectedBetweenElementsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndElements, + \Self.elements, + \Self.unexpectedBetweenElementsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - TupleTypeElementSyntax @@ -1402,7 +1386,7 @@ public struct TuplePatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPa public struct TupleTypeElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .tupleTypeElement else { return nil } @@ -1637,25 +1621,23 @@ public struct TupleTypeElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeInoutKeyword, - \Self.inoutKeyword, - \Self.unexpectedBetweenInoutKeywordAndFirstName, - \Self.firstName, - \Self.unexpectedBetweenFirstNameAndSecondName, - \Self.secondName, - \Self.unexpectedBetweenSecondNameAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndType, - \Self.type, - \Self.unexpectedBetweenTypeAndEllipsis, - \Self.ellipsis, - \Self.unexpectedBetweenEllipsisAndTrailingComma, - \Self.trailingComma, - \Self.unexpectedAfterTrailingComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeInoutKeyword, + \Self.inoutKeyword, + \Self.unexpectedBetweenInoutKeywordAndFirstName, + \Self.firstName, + \Self.unexpectedBetweenFirstNameAndSecondName, + \Self.secondName, + \Self.unexpectedBetweenSecondNameAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndType, + \Self.type, + \Self.unexpectedBetweenTypeAndEllipsis, + \Self.ellipsis, + \Self.unexpectedBetweenEllipsisAndTrailingComma, + \Self.trailingComma, + \Self.unexpectedAfterTrailingComma + ]) } // MARK: - TupleTypeSyntax @@ -1668,7 +1650,7 @@ public struct TupleTypeElementSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta public struct TupleTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .tupleType else { return nil } @@ -1818,17 +1800,15 @@ public struct TupleTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndElements, - \Self.elements, - \Self.unexpectedBetweenElementsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndElements, + \Self.elements, + \Self.unexpectedBetweenElementsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } // MARK: - TypeAliasDeclSyntax @@ -1845,7 +1825,7 @@ public struct TupleTypeSyntax: TypeSyntaxProtocol, SyntaxHashable, _LeafTypeSynt public struct TypeAliasDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .typeAliasDecl else { return nil } @@ -2122,25 +2102,23 @@ public struct TypeAliasDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDecl } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndTypealiasKeyword, - \Self.typealiasKeyword, - \Self.unexpectedBetweenTypealiasKeywordAndName, - \Self.name, - \Self.unexpectedBetweenNameAndGenericParameterClause, - \Self.genericParameterClause, - \Self.unexpectedBetweenGenericParameterClauseAndInitializer, - \Self.initializer, - \Self.unexpectedBetweenInitializerAndGenericWhereClause, - \Self.genericWhereClause, - \Self.unexpectedAfterGenericWhereClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndTypealiasKeyword, + \Self.typealiasKeyword, + \Self.unexpectedBetweenTypealiasKeywordAndName, + \Self.name, + \Self.unexpectedBetweenNameAndGenericParameterClause, + \Self.genericParameterClause, + \Self.unexpectedBetweenGenericParameterClauseAndInitializer, + \Self.initializer, + \Self.unexpectedBetweenInitializerAndGenericWhereClause, + \Self.genericWhereClause, + \Self.unexpectedAfterGenericWhereClause + ]) } // MARK: - TypeAnnotationSyntax @@ -2159,7 +2137,7 @@ public struct TypeAliasDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDecl public struct TypeAnnotationSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .typeAnnotation else { return nil } @@ -2258,15 +2236,13 @@ public struct TypeAnnotationSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeColon, - \Self.colon, - \Self.unexpectedBetweenColonAndType, - \Self.type, - \Self.unexpectedAfterType - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeColon, + \Self.colon, + \Self.unexpectedBetweenColonAndType, + \Self.type, + \Self.unexpectedAfterType + ]) } // MARK: - TypeEffectSpecifiersSyntax @@ -2284,7 +2260,7 @@ public struct TypeAnnotationSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxN public struct TypeEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .typeEffectSpecifiers else { return nil } @@ -2382,15 +2358,13 @@ public struct TypeEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _LeafS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAsyncSpecifier, - \Self.asyncSpecifier, - \Self.unexpectedBetweenAsyncSpecifierAndThrowsClause, - \Self.throwsClause, - \Self.unexpectedAfterThrowsClause - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAsyncSpecifier, + \Self.asyncSpecifier, + \Self.unexpectedBetweenAsyncSpecifierAndThrowsClause, + \Self.throwsClause, + \Self.unexpectedAfterThrowsClause + ]) } // MARK: - TypeExprSyntax @@ -2401,7 +2375,7 @@ public struct TypeEffectSpecifiersSyntax: SyntaxProtocol, SyntaxHashable, _LeafS public struct TypeExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .typeExpr else { return nil } @@ -2462,9 +2436,7 @@ public struct TypeExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeType, \Self.type, \Self.unexpectedAfterType]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeType, \Self.type, \Self.unexpectedAfterType]) } // MARK: - TypeInitializerClauseSyntax @@ -2481,7 +2453,7 @@ public struct TypeExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSynta public struct TypeInitializerClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .typeInitializerClause else { return nil } @@ -2577,15 +2549,13 @@ public struct TypeInitializerClauseSyntax: SyntaxProtocol, SyntaxHashable, _Leaf } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeEqual, - \Self.equal, - \Self.unexpectedBetweenEqualAndValue, - \Self.value, - \Self.unexpectedAfterValue - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeEqual, + \Self.equal, + \Self.unexpectedBetweenEqualAndValue, + \Self.value, + \Self.unexpectedAfterValue + ]) } // MARK: - UnavailableFromAsyncAttributeArgumentsSyntax @@ -2604,7 +2574,7 @@ public struct TypeInitializerClauseSyntax: SyntaxProtocol, SyntaxHashable, _Leaf public struct UnavailableFromAsyncAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .unavailableFromAsyncAttributeArguments else { return nil } @@ -2727,17 +2697,15 @@ public struct UnavailableFromAsyncAttributeArgumentsSyntax: SyntaxProtocol, Synt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeMessageLabel, - \Self.messageLabel, - \Self.unexpectedBetweenMessageLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndMessage, - \Self.message, - \Self.unexpectedAfterMessage - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeMessageLabel, + \Self.messageLabel, + \Self.unexpectedBetweenMessageLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndMessage, + \Self.message, + \Self.unexpectedAfterMessage + ]) } // MARK: - UnderscorePrivateAttributeArgumentsSyntax @@ -2756,7 +2724,7 @@ public struct UnavailableFromAsyncAttributeArgumentsSyntax: SyntaxProtocol, Synt public struct UnderscorePrivateAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .underscorePrivateAttributeArguments else { return nil } @@ -2879,17 +2847,15 @@ public struct UnderscorePrivateAttributeArgumentsSyntax: SyntaxProtocol, SyntaxH } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeSourceFileLabel, - \Self.sourceFileLabel, - \Self.unexpectedBetweenSourceFileLabelAndColon, - \Self.colon, - \Self.unexpectedBetweenColonAndFilename, - \Self.filename, - \Self.unexpectedAfterFilename - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeSourceFileLabel, + \Self.sourceFileLabel, + \Self.unexpectedBetweenSourceFileLabelAndColon, + \Self.colon, + \Self.unexpectedBetweenColonAndFilename, + \Self.filename, + \Self.unexpectedAfterFilename + ]) } // MARK: - UnresolvedAsExprSyntax @@ -2906,7 +2872,7 @@ public struct UnderscorePrivateAttributeArgumentsSyntax: SyntaxProtocol, SyntaxH public struct UnresolvedAsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .unresolvedAsExpr else { return nil } @@ -3007,15 +2973,13 @@ public struct UnresolvedAsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAsKeyword, - \Self.asKeyword, - \Self.unexpectedBetweenAsKeywordAndQuestionOrExclamationMark, - \Self.questionOrExclamationMark, - \Self.unexpectedAfterQuestionOrExclamationMark - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAsKeyword, + \Self.asKeyword, + \Self.unexpectedBetweenAsKeywordAndQuestionOrExclamationMark, + \Self.questionOrExclamationMark, + \Self.unexpectedAfterQuestionOrExclamationMark + ]) } // MARK: - UnresolvedIsExprSyntax @@ -3031,7 +2995,7 @@ public struct UnresolvedAsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE public struct UnresolvedIsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .unresolvedIsExpr else { return nil } @@ -3095,9 +3059,7 @@ public struct UnresolvedIsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeIsKeyword, \Self.isKeyword, \Self.unexpectedAfterIsKeyword]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeIsKeyword, \Self.isKeyword, \Self.unexpectedAfterIsKeyword]) } // MARK: - UnresolvedTernaryExprSyntax @@ -3116,7 +3078,7 @@ public struct UnresolvedIsExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafE public struct UnresolvedTernaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _LeafExprSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .unresolvedTernaryExpr else { return nil } @@ -3239,29 +3201,27 @@ public struct UnresolvedTernaryExprSyntax: ExprSyntaxProtocol, SyntaxHashable, _ } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeQuestionMark, - \Self.questionMark, - \Self.unexpectedBetweenQuestionMarkAndThenExpression, - \Self.thenExpression, - \Self.unexpectedBetweenThenExpressionAndColon, - \Self.colon, - \Self.unexpectedAfterColon - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeQuestionMark, + \Self.questionMark, + \Self.unexpectedBetweenQuestionMarkAndThenExpression, + \Self.thenExpression, + \Self.unexpectedBetweenThenExpressionAndColon, + \Self.colon, + \Self.unexpectedAfterColon + ]) } // MARK: - ValueBindingPatternSyntax /// ### Children /// -/// - `bindingSpecifier`: (`let` | `var` | `inout` | `_mutating` | `_borrowing` | `_consuming`) +/// - `bindingSpecifier`: (`let` | `var` | `inout` | `_mutating` | `_borrowing` | `_consuming` | `borrowing`) /// - `pattern`: ``PatternSyntax`` public struct ValueBindingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .valueBindingPattern else { return nil } @@ -3327,6 +3287,7 @@ public struct ValueBindingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, /// - `_mutating` /// - `_borrowing` /// - `_consuming` + /// - `borrowing` public var bindingSpecifier: TokenSyntax { get { return Syntax(self).child(at: 1)!.cast(TokenSyntax.self) @@ -3363,15 +3324,13 @@ public struct ValueBindingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeBindingSpecifier, - \Self.bindingSpecifier, - \Self.unexpectedBetweenBindingSpecifierAndPattern, - \Self.pattern, - \Self.unexpectedAfterPattern - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeBindingSpecifier, + \Self.bindingSpecifier, + \Self.unexpectedBetweenBindingSpecifierAndPattern, + \Self.pattern, + \Self.unexpectedAfterPattern + ]) } // MARK: - VariableDeclSyntax @@ -3390,7 +3349,7 @@ public struct ValueBindingPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, public struct VariableDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .variableDecl else { return nil } @@ -3638,19 +3597,17 @@ public struct VariableDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeAttributes, - \Self.attributes, - \Self.unexpectedBetweenAttributesAndModifiers, - \Self.modifiers, - \Self.unexpectedBetweenModifiersAndBindingSpecifier, - \Self.bindingSpecifier, - \Self.unexpectedBetweenBindingSpecifierAndBindings, - \Self.bindings, - \Self.unexpectedAfterBindings - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeAttributes, + \Self.attributes, + \Self.unexpectedBetweenAttributesAndModifiers, + \Self.modifiers, + \Self.unexpectedBetweenModifiersAndBindingSpecifier, + \Self.bindingSpecifier, + \Self.unexpectedBetweenBindingSpecifierAndBindings, + \Self.bindings, + \Self.unexpectedAfterBindings + ]) } // MARK: - VersionComponentSyntax @@ -3668,7 +3625,7 @@ public struct VariableDeclSyntax: DeclSyntaxProtocol, SyntaxHashable, _LeafDeclS public struct VersionComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .versionComponent else { return nil } @@ -3773,15 +3730,13 @@ public struct VersionComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforePeriod, - \Self.period, - \Self.unexpectedBetweenPeriodAndNumber, - \Self.number, - \Self.unexpectedAfterNumber - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforePeriod, + \Self.period, + \Self.unexpectedBetweenPeriodAndNumber, + \Self.number, + \Self.unexpectedAfterNumber + ]) } // MARK: - VersionTupleSyntax @@ -3796,12 +3751,12 @@ public struct VersionComponentSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynta /// ### Contained in /// /// - ``AvailabilityLabeledArgumentSyntax``.``AvailabilityLabeledArgumentSyntax/value`` -/// - ``CanImportVersionInfoSyntax``.``CanImportVersionInfoSyntax/version`` +/// - `_CanImportVersionInfoSyntax`.`_CanImportVersionInfoSyntax/version` /// - ``PlatformVersionSyntax``.``PlatformVersionSyntax/version`` public struct VersionTupleSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .versionTuple else { return nil } @@ -3929,15 +3884,13 @@ public struct VersionTupleSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeMajor, - \Self.major, - \Self.unexpectedBetweenMajorAndComponents, - \Self.components, - \Self.unexpectedAfterComponents - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeMajor, + \Self.major, + \Self.unexpectedBetweenMajorAndComponents, + \Self.components, + \Self.unexpectedAfterComponents + ]) } // MARK: - WhereClauseSyntax @@ -3955,7 +3908,7 @@ public struct VersionTupleSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNod public struct WhereClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .whereClause else { return nil } @@ -4051,15 +4004,13 @@ public struct WhereClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWhereKeyword, - \Self.whereKeyword, - \Self.unexpectedBetweenWhereKeywordAndCondition, - \Self.condition, - \Self.unexpectedAfterCondition - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWhereKeyword, + \Self.whereKeyword, + \Self.unexpectedBetweenWhereKeywordAndCondition, + \Self.condition, + \Self.unexpectedAfterCondition + ]) } // MARK: - WhileStmtSyntax @@ -4072,7 +4023,7 @@ public struct WhereClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNode public struct WhileStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .whileStmt else { return nil } @@ -4219,17 +4170,15 @@ public struct WhileStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeWhileKeyword, - \Self.whileKeyword, - \Self.unexpectedBetweenWhileKeywordAndConditions, - \Self.conditions, - \Self.unexpectedBetweenConditionsAndBody, - \Self.body, - \Self.unexpectedAfterBody - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeWhileKeyword, + \Self.whileKeyword, + \Self.unexpectedBetweenWhileKeywordAndConditions, + \Self.conditions, + \Self.unexpectedBetweenConditionsAndBody, + \Self.body, + \Self.unexpectedAfterBody + ]) } // MARK: - WildcardPatternSyntax @@ -4253,7 +4202,7 @@ public struct WhileStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt public struct WildcardPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _LeafPatternSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .wildcardPattern else { return nil } @@ -4317,9 +4266,7 @@ public struct WildcardPatternSyntax: PatternSyntaxProtocol, SyntaxHashable, _Lea } } - public static var structure: SyntaxNodeStructure { - return .layout([\Self.unexpectedBeforeWildcard, \Self.wildcard, \Self.unexpectedAfterWildcard]) - } + public static let structure: SyntaxNodeStructure = .layout([\Self.unexpectedBeforeWildcard, \Self.wildcard, \Self.unexpectedAfterWildcard]) } // MARK: - YieldStmtSyntax @@ -4350,7 +4297,7 @@ public struct YieldStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt self = .single(ExprSyntax(node)) } - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { if let node = node.as(YieldedExpressionsClauseSyntax.self) { self = .multiple(node) return @@ -4413,7 +4360,7 @@ public struct YieldStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .yieldStmt else { return nil } @@ -4509,15 +4456,13 @@ public struct YieldStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeYieldKeyword, - \Self.yieldKeyword, - \Self.unexpectedBetweenYieldKeywordAndYieldedExpressions, - \Self.yieldedExpressions, - \Self.unexpectedAfterYieldedExpressions - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeYieldKeyword, + \Self.yieldKeyword, + \Self.unexpectedBetweenYieldKeywordAndYieldedExpressions, + \Self.yieldedExpressions, + \Self.unexpectedAfterYieldedExpressions + ]) } // MARK: - YieldedExpressionSyntax @@ -4533,7 +4478,7 @@ public struct YieldStmtSyntax: StmtSyntaxProtocol, SyntaxHashable, _LeafStmtSynt public struct YieldedExpressionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .yieldedExpression else { return nil } @@ -4629,15 +4574,13 @@ public struct YieldedExpressionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeExpression, - \Self.expression, - \Self.unexpectedBetweenExpressionAndComma, - \Self.comma, - \Self.unexpectedAfterComma - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeExpression, + \Self.expression, + \Self.unexpectedBetweenExpressionAndComma, + \Self.comma, + \Self.unexpectedAfterComma + ]) } // MARK: - YieldedExpressionsClauseSyntax @@ -4654,7 +4597,7 @@ public struct YieldedExpressionSyntax: SyntaxProtocol, SyntaxHashable, _LeafSynt public struct YieldedExpressionsClauseSyntax: SyntaxProtocol, SyntaxHashable, _LeafSyntaxNodeProtocol { public let _syntaxNode: Syntax - public init?(_ node: some SyntaxProtocol) { + public init?(_ node: __shared some SyntaxProtocol) { guard node.raw.kind == .yieldedExpressionsClause else { return nil } @@ -4804,15 +4747,13 @@ public struct YieldedExpressionsClauseSyntax: SyntaxProtocol, SyntaxHashable, _L } } - public static var structure: SyntaxNodeStructure { - return .layout([ - \Self.unexpectedBeforeLeftParen, - \Self.leftParen, - \Self.unexpectedBetweenLeftParenAndElements, - \Self.elements, - \Self.unexpectedBetweenElementsAndRightParen, - \Self.rightParen, - \Self.unexpectedAfterRightParen - ]) - } + public static let structure: SyntaxNodeStructure = .layout([ + \Self.unexpectedBeforeLeftParen, + \Self.leftParen, + \Self.unexpectedBetweenLeftParenAndElements, + \Self.elements, + \Self.unexpectedBetweenElementsAndRightParen, + \Self.rightParen, + \Self.unexpectedAfterRightParen + ]) } diff --git a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift index 181bf97a2a6..a4d306bfdb6 100644 --- a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift +++ b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -@_spi(RawSyntax) import SwiftParser +@_spi(RawSyntax) internal import SwiftParser @_spi(RawSyntax) public import SwiftSyntax #else @_spi(RawSyntax) import SwiftParser @@ -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/DeclSyntaxParseable.swift b/Sources/SwiftSyntaxBuilder/DeclSyntaxParseable.swift index 65724daeafa..f5f6e8cb3c4 100644 --- a/Sources/SwiftSyntaxBuilder/DeclSyntaxParseable.swift +++ b/Sources/SwiftSyntaxBuilder/DeclSyntaxParseable.swift @@ -22,7 +22,7 @@ import SwiftSyntax /// - Warning: This protocol is considered an implementation detail. Do not rely /// on it, only the initializer that it adds. public protocol DeclSyntaxParseable: DeclSyntaxProtocol {} -public extension DeclSyntaxParseable { +extension DeclSyntaxParseable { /// Create a syntax node from the given string interpolation. /// /// This initializer throws if the syntax node was not able to be parsed as @@ -30,7 +30,7 @@ public extension DeclSyntaxParseable { /// /// If there are syntax errors in the string, the initializer will return a /// node that contains errors without throwing. - init(_ stringInterpolation: SyntaxNodeString) throws { + public init(_ stringInterpolation: SyntaxNodeString) throws { let node: DeclSyntax = "\(stringInterpolation)" if let castedDecl = node.as(Self.self) { self = castedDecl diff --git a/Sources/SwiftSyntaxBuilder/SwiftSyntaxBuilderCompatibility.swift b/Sources/SwiftSyntaxBuilder/SwiftSyntaxBuilderCompatibility.swift index e0c673e8706..c1b29002829 100644 --- a/Sources/SwiftSyntaxBuilder/SwiftSyntaxBuilderCompatibility.swift +++ b/Sources/SwiftSyntaxBuilder/SwiftSyntaxBuilderCompatibility.swift @@ -13,7 +13,11 @@ // This file provides compatibility aliases to keep dependents of SwiftSyntaxBuilder building. // All users of the declarations in this file should transition away from them ASAP. +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif @available(*, deprecated, renamed: "ImportPathComponentListBuilder") public typealias AccessPathBuilder = ImportPathComponentListBuilder diff --git a/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift b/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift index 42f404303e9..72c3338cbfb 100644 --- a/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift +++ b/Sources/SwiftSyntaxBuilder/Syntax+StringInterpolation.swift @@ -12,8 +12,8 @@ #if swift(>=6) public import SwiftBasicFormat -import SwiftDiagnostics -@_spi(RawSyntax) @_spi(Testing) import SwiftParser +internal import SwiftDiagnostics +@_spi(RawSyntax) @_spi(Testing) internal import SwiftParser @_spi(RawSyntax) public import SwiftSyntax #else import SwiftBasicFormat @@ -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..2a00a4f2dc3 100644 --- a/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift +++ b/Sources/SwiftSyntaxBuilder/SyntaxNodeWithBody.swift @@ -69,8 +69,11 @@ public protocol HasTrailingCodeBlock: WithCodeBlockSyntax { init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax) rethrows } -public extension HasTrailingCodeBlock where Self: StmtSyntaxProtocol { - init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax) throws { +extension HasTrailingCodeBlock where Self: StmtSyntaxProtocol { + public init( + _ header: SyntaxNodeString, + @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax + ) throws { let stmt = StmtSyntax("\(header) {}") guard let castedStmt = stmt.as(Self.self) else { throw SyntaxStringInterpolationInvalidNodeTypeError(expectedType: Self.self, actualNode: stmt) @@ -81,7 +84,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()) } @@ -94,7 +100,7 @@ extension WhileStmtSyntax: HasTrailingCodeBlock {} // MARK: - WithOptionalCodeBlockSyntax -public extension WithOptionalCodeBlockSyntax where Self: DeclSyntaxProtocol { +extension WithOptionalCodeBlockSyntax where Self: DeclSyntaxProtocol { /// Constructs a syntax node where `header` builds the text of the node before the body in braces and `bodyBuilder` is used to build the node’s body. /// /// For example, you can construct @@ -114,7 +120,10 @@ public extension WithOptionalCodeBlockSyntax where Self: DeclSyntaxProtocol { /// ``` /// /// Throws an error if `header` defines a different node type than the type the initializer is called on. E.g. if calling `try FunctionDeclSyntax("init") {}` - init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax) throws { + public init( + _ header: SyntaxNodeString, + @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax + ) throws { let decl = DeclSyntax("\(header) {}") guard let castedDecl = decl.as(Self.self) else { throw SyntaxStringInterpolationInvalidNodeTypeError(expectedType: Self.self, actualNode: decl) @@ -150,11 +159,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 { +extension HasTrailingMemberDeclBlock where Self: DeclSyntaxProtocol { + public 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) @@ -175,7 +190,7 @@ extension StructDeclSyntax: HasTrailingMemberDeclBlock {} // IfExprSyntax is a special scenario as we also have the `else` body or an if-else // So we cannot conform to `HasTrailingCodeBlock` -public extension IfExprSyntax { +extension IfExprSyntax { /// Constructs an `if` expression with an optional `else` block. /// /// `header` specifies the part of the `if` expression before the body’s first brace. @@ -193,7 +208,7 @@ public extension IfExprSyntax { /// This function takes care of inserting the braces as well. /// /// Throws an error if `header` does not start an `if` expression. E.g. if calling `try IfExprSyntax("while true") {}` - init( + public init( _ header: SyntaxNodeString, @CodeBlockItemListBuilder bodyBuilder: () throws -> CodeBlockItemListSyntax, @CodeBlockItemListBuilder `else` elseBuilder: () throws -> CodeBlockItemListSyntax? = { nil } @@ -242,7 +257,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 { + public 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 +294,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() } @@ -285,7 +307,7 @@ extension SwitchCaseSyntax { // SwitchExprSyntax is a special scenario as it don't have body or members // So we cannot conform to `HasTrailingCodeBlock` or `HasTrailingMemberDeclBlock` -public extension SwitchExprSyntax { +extension SwitchExprSyntax { /// Constructs a `switch` expression where `header` builds the text before the opening `{` and `casesBuilder` can be used to build the case items. /// /// For example, to construct @@ -309,7 +331,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 { + public 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) @@ -323,7 +348,7 @@ public extension SwitchExprSyntax { // VariableDeclSyntax is a special scenario as it don't have body or members // So we cannot conform to `HasTrailingCodeBlock` or `HasTrailingMemberDeclBlock` -public extension VariableDeclSyntax { +extension VariableDeclSyntax { /// Construct a variable with a single `get` accessor where `header` builds the text before the opening `{` and `accessor` builds the accessor body. /// /// For example, to construct @@ -343,7 +368,10 @@ public extension VariableDeclSyntax { /// ``` /// /// Throws an error if `header` does not start a variable declaration. E.g. if calling `try VariableDeclSyntax("func foo") {}` - init(_ header: SyntaxNodeString, @CodeBlockItemListBuilder accessor: () throws -> CodeBlockItemListSyntax) throws { + public init( + _ header: SyntaxNodeString, + @CodeBlockItemListBuilder accessor: () throws -> CodeBlockItemListSyntax + ) throws { let decl = DeclSyntax("\(header) {}") guard let castedDecl = decl.as(Self.self) else { throw SyntaxStringInterpolationInvalidNodeTypeError(expectedType: Self.self, actualNode: decl) diff --git a/Sources/SwiftSyntaxBuilder/SyntaxParsable+ExpressibleByStringInterpolation.swift b/Sources/SwiftSyntaxBuilder/SyntaxParsable+ExpressibleByStringInterpolation.swift index 506c2247f79..f87f7e324ec 100644 --- a/Sources/SwiftSyntaxBuilder/SyntaxParsable+ExpressibleByStringInterpolation.swift +++ b/Sources/SwiftSyntaxBuilder/SyntaxParsable+ExpressibleByStringInterpolation.swift @@ -11,10 +11,10 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftDiagnostics +internal import SwiftDiagnostics public import SwiftParser -import SwiftParserDiagnostics -import SwiftSyntax +internal import SwiftParserDiagnostics +internal import SwiftSyntax #else import SwiftDiagnostics import SwiftParser diff --git a/Sources/SwiftSyntaxBuilder/ValidatingSyntaxNodes.swift b/Sources/SwiftSyntaxBuilder/ValidatingSyntaxNodes.swift index 010331b3ba5..73f0923c3ac 100644 --- a/Sources/SwiftSyntaxBuilder/ValidatingSyntaxNodes.swift +++ b/Sources/SwiftSyntaxBuilder/ValidatingSyntaxNodes.swift @@ -11,8 +11,8 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftDiagnostics -import SwiftParserDiagnostics +internal import SwiftDiagnostics +internal import SwiftParserDiagnostics public import SwiftSyntax #else import SwiftDiagnostics diff --git a/Sources/SwiftSyntaxBuilder/WithTrailingCommaSyntax+EnsuringTrailingComma.swift b/Sources/SwiftSyntaxBuilder/WithTrailingCommaSyntax+EnsuringTrailingComma.swift index f5c0c2de9fc..9080ecc5960 100644 --- a/Sources/SwiftSyntaxBuilder/WithTrailingCommaSyntax+EnsuringTrailingComma.swift +++ b/Sources/SwiftSyntaxBuilder/WithTrailingCommaSyntax+EnsuringTrailingComma.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif extension WithTrailingCommaSyntax { func ensuringTrailingComma() -> Self { diff --git a/Sources/SwiftSyntaxBuilder/generated/ResultBuilders.swift b/Sources/SwiftSyntaxBuilder/generated/ResultBuilders.swift index 6a48ae96427..fed40420091 100644 --- a/Sources/SwiftSyntaxBuilder/generated/ResultBuilders.swift +++ b/Sources/SwiftSyntaxBuilder/generated/ResultBuilders.swift @@ -25,8 +25,8 @@ public struct AccessorDeclListBuilder: ListBuilder { public typealias FinalResult = AccessorDeclListSyntax } -public extension AccessorDeclListSyntax { - init(@AccessorDeclListBuilder itemsBuilder: () throws -> AccessorDeclListSyntax) rethrows { +extension AccessorDeclListSyntax { + public init(@AccessorDeclListBuilder itemsBuilder: () throws -> AccessorDeclListSyntax) rethrows { self = try itemsBuilder() } } @@ -38,8 +38,8 @@ public struct ArrayElementListBuilder: ListBuilder { public typealias FinalResult = ArrayElementListSyntax } -public extension ArrayElementListSyntax { - init(@ArrayElementListBuilder itemsBuilder: () throws -> ArrayElementListSyntax) rethrows { +extension ArrayElementListSyntax { + public init(@ArrayElementListBuilder itemsBuilder: () throws -> ArrayElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -59,8 +59,8 @@ public struct AttributeListBuilder: ListBuilder { } } -public extension AttributeListSyntax { - init(@AttributeListBuilder itemsBuilder: () throws -> AttributeListSyntax) rethrows { +extension AttributeListSyntax { + public init(@AttributeListBuilder itemsBuilder: () throws -> AttributeListSyntax) rethrows { self = try itemsBuilder() } } @@ -72,8 +72,8 @@ public struct AvailabilityArgumentListBuilder: ListBuilder { public typealias FinalResult = AvailabilityArgumentListSyntax } -public extension AvailabilityArgumentListSyntax { - init(@AvailabilityArgumentListBuilder itemsBuilder: () throws -> AvailabilityArgumentListSyntax) rethrows { +extension AvailabilityArgumentListSyntax { + public init(@AvailabilityArgumentListBuilder itemsBuilder: () throws -> AvailabilityArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -85,8 +85,8 @@ public struct CatchClauseListBuilder: ListBuilder { public typealias FinalResult = CatchClauseListSyntax } -public extension CatchClauseListSyntax { - init(@CatchClauseListBuilder itemsBuilder: () throws -> CatchClauseListSyntax) rethrows { +extension CatchClauseListSyntax { + public init(@CatchClauseListBuilder itemsBuilder: () throws -> CatchClauseListSyntax) rethrows { self = try itemsBuilder() } } @@ -98,8 +98,8 @@ public struct CatchItemListBuilder: ListBuilder { public typealias FinalResult = CatchItemListSyntax } -public extension CatchItemListSyntax { - init(@CatchItemListBuilder itemsBuilder: () throws -> CatchItemListSyntax) rethrows { +extension CatchItemListSyntax { + public init(@CatchItemListBuilder itemsBuilder: () throws -> CatchItemListSyntax) rethrows { self = try itemsBuilder() } } @@ -111,8 +111,8 @@ public struct ClosureCaptureListBuilder: ListBuilder { public typealias FinalResult = ClosureCaptureListSyntax } -public extension ClosureCaptureListSyntax { - init(@ClosureCaptureListBuilder itemsBuilder: () throws -> ClosureCaptureListSyntax) rethrows { +extension ClosureCaptureListSyntax { + public init(@ClosureCaptureListBuilder itemsBuilder: () throws -> ClosureCaptureListSyntax) rethrows { self = try itemsBuilder() } } @@ -124,8 +124,8 @@ public struct ClosureParameterListBuilder: ListBuilder { public typealias FinalResult = ClosureParameterListSyntax } -public extension ClosureParameterListSyntax { - init(@ClosureParameterListBuilder itemsBuilder: () throws -> ClosureParameterListSyntax) rethrows { +extension ClosureParameterListSyntax { + public init(@ClosureParameterListBuilder itemsBuilder: () throws -> ClosureParameterListSyntax) rethrows { self = try itemsBuilder() } } @@ -137,8 +137,8 @@ public struct ClosureShorthandParameterListBuilder: ListBuilder { public typealias FinalResult = ClosureShorthandParameterListSyntax } -public extension ClosureShorthandParameterListSyntax { - init(@ClosureShorthandParameterListBuilder itemsBuilder: () throws -> ClosureShorthandParameterListSyntax) rethrows { +extension ClosureShorthandParameterListSyntax { + public init(@ClosureShorthandParameterListBuilder itemsBuilder: () throws -> ClosureShorthandParameterListSyntax) rethrows { self = try itemsBuilder() } } @@ -150,8 +150,8 @@ public struct CodeBlockItemListBuilder: ListBuilder { public typealias FinalResult = CodeBlockItemListSyntax } -public extension CodeBlockItemListSyntax { - init(@CodeBlockItemListBuilder itemsBuilder: () throws -> CodeBlockItemListSyntax) rethrows { +extension CodeBlockItemListSyntax { + public init(@CodeBlockItemListBuilder itemsBuilder: () throws -> CodeBlockItemListSyntax) rethrows { self = try itemsBuilder() } } @@ -163,8 +163,8 @@ public struct CompositionTypeElementListBuilder: ListBuilder { public typealias FinalResult = CompositionTypeElementListSyntax } -public extension CompositionTypeElementListSyntax { - init(@CompositionTypeElementListBuilder itemsBuilder: () throws -> CompositionTypeElementListSyntax) rethrows { +extension CompositionTypeElementListSyntax { + public init(@CompositionTypeElementListBuilder itemsBuilder: () throws -> CompositionTypeElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -176,8 +176,8 @@ public struct ConditionElementListBuilder: ListBuilder { public typealias FinalResult = ConditionElementListSyntax } -public extension ConditionElementListSyntax { - init(@ConditionElementListBuilder itemsBuilder: () throws -> ConditionElementListSyntax) rethrows { +extension ConditionElementListSyntax { + public init(@ConditionElementListBuilder itemsBuilder: () throws -> ConditionElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -189,8 +189,8 @@ public struct DeclModifierListBuilder: ListBuilder { public typealias FinalResult = DeclModifierListSyntax } -public extension DeclModifierListSyntax { - init(@DeclModifierListBuilder itemsBuilder: () throws -> DeclModifierListSyntax) rethrows { +extension DeclModifierListSyntax { + public init(@DeclModifierListBuilder itemsBuilder: () throws -> DeclModifierListSyntax) rethrows { self = try itemsBuilder() } } @@ -202,8 +202,8 @@ public struct DeclNameArgumentListBuilder: ListBuilder { public typealias FinalResult = DeclNameArgumentListSyntax } -public extension DeclNameArgumentListSyntax { - init(@DeclNameArgumentListBuilder itemsBuilder: () throws -> DeclNameArgumentListSyntax) rethrows { +extension DeclNameArgumentListSyntax { + public init(@DeclNameArgumentListBuilder itemsBuilder: () throws -> DeclNameArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -215,8 +215,8 @@ public struct DesignatedTypeListBuilder: ListBuilder { public typealias FinalResult = DesignatedTypeListSyntax } -public extension DesignatedTypeListSyntax { - init(@DesignatedTypeListBuilder itemsBuilder: () throws -> DesignatedTypeListSyntax) rethrows { +extension DesignatedTypeListSyntax { + public init(@DesignatedTypeListBuilder itemsBuilder: () throws -> DesignatedTypeListSyntax) rethrows { self = try itemsBuilder() } } @@ -228,8 +228,8 @@ public struct DictionaryElementListBuilder: ListBuilder { public typealias FinalResult = DictionaryElementListSyntax } -public extension DictionaryElementListSyntax { - init(@DictionaryElementListBuilder itemsBuilder: () throws -> DictionaryElementListSyntax) rethrows { +extension DictionaryElementListSyntax { + public init(@DictionaryElementListBuilder itemsBuilder: () throws -> DictionaryElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -241,8 +241,8 @@ public struct DifferentiabilityArgumentListBuilder: ListBuilder { public typealias FinalResult = DifferentiabilityArgumentListSyntax } -public extension DifferentiabilityArgumentListSyntax { - init(@DifferentiabilityArgumentListBuilder itemsBuilder: () throws -> DifferentiabilityArgumentListSyntax) rethrows { +extension DifferentiabilityArgumentListSyntax { + public init(@DifferentiabilityArgumentListBuilder itemsBuilder: () throws -> DifferentiabilityArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -254,8 +254,8 @@ public struct DocumentationAttributeArgumentListBuilder: ListBuilder { public typealias FinalResult = DocumentationAttributeArgumentListSyntax } -public extension DocumentationAttributeArgumentListSyntax { - init(@DocumentationAttributeArgumentListBuilder itemsBuilder: () throws -> DocumentationAttributeArgumentListSyntax) rethrows { +extension DocumentationAttributeArgumentListSyntax { + public init(@DocumentationAttributeArgumentListBuilder itemsBuilder: () throws -> DocumentationAttributeArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -267,8 +267,8 @@ public struct EffectsAttributeArgumentListBuilder: ListBuilder { public typealias FinalResult = EffectsAttributeArgumentListSyntax } -public extension EffectsAttributeArgumentListSyntax { - init(@EffectsAttributeArgumentListBuilder itemsBuilder: () throws -> EffectsAttributeArgumentListSyntax) rethrows { +extension EffectsAttributeArgumentListSyntax { + public init(@EffectsAttributeArgumentListBuilder itemsBuilder: () throws -> EffectsAttributeArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -280,8 +280,8 @@ public struct EnumCaseElementListBuilder: ListBuilder { public typealias FinalResult = EnumCaseElementListSyntax } -public extension EnumCaseElementListSyntax { - init(@EnumCaseElementListBuilder itemsBuilder: () throws -> EnumCaseElementListSyntax) rethrows { +extension EnumCaseElementListSyntax { + public init(@EnumCaseElementListBuilder itemsBuilder: () throws -> EnumCaseElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -293,8 +293,8 @@ public struct EnumCaseParameterListBuilder: ListBuilder { public typealias FinalResult = EnumCaseParameterListSyntax } -public extension EnumCaseParameterListSyntax { - init(@EnumCaseParameterListBuilder itemsBuilder: () throws -> EnumCaseParameterListSyntax) rethrows { +extension EnumCaseParameterListSyntax { + public init(@EnumCaseParameterListBuilder itemsBuilder: () throws -> EnumCaseParameterListSyntax) rethrows { self = try itemsBuilder() } } @@ -306,8 +306,8 @@ public struct ExprListBuilder: ListBuilder { public typealias FinalResult = ExprListSyntax } -public extension ExprListSyntax { - init(@ExprListBuilder itemsBuilder: () throws -> ExprListSyntax) rethrows { +extension ExprListSyntax { + public init(@ExprListBuilder itemsBuilder: () throws -> ExprListSyntax) rethrows { self = try itemsBuilder() } } @@ -319,8 +319,8 @@ public struct FunctionParameterListBuilder: ListBuilder { public typealias FinalResult = FunctionParameterListSyntax } -public extension FunctionParameterListSyntax { - init(@FunctionParameterListBuilder itemsBuilder: () throws -> FunctionParameterListSyntax) rethrows { +extension FunctionParameterListSyntax { + public init(@FunctionParameterListBuilder itemsBuilder: () throws -> FunctionParameterListSyntax) rethrows { self = try itemsBuilder() } } @@ -332,8 +332,8 @@ public struct GenericArgumentListBuilder: ListBuilder { public typealias FinalResult = GenericArgumentListSyntax } -public extension GenericArgumentListSyntax { - init(@GenericArgumentListBuilder itemsBuilder: () throws -> GenericArgumentListSyntax) rethrows { +extension GenericArgumentListSyntax { + public init(@GenericArgumentListBuilder itemsBuilder: () throws -> GenericArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -345,8 +345,8 @@ public struct GenericParameterListBuilder: ListBuilder { public typealias FinalResult = GenericParameterListSyntax } -public extension GenericParameterListSyntax { - init(@GenericParameterListBuilder itemsBuilder: () throws -> GenericParameterListSyntax) rethrows { +extension GenericParameterListSyntax { + public init(@GenericParameterListBuilder itemsBuilder: () throws -> GenericParameterListSyntax) rethrows { self = try itemsBuilder() } } @@ -358,8 +358,8 @@ public struct GenericRequirementListBuilder: ListBuilder { public typealias FinalResult = GenericRequirementListSyntax } -public extension GenericRequirementListSyntax { - init(@GenericRequirementListBuilder itemsBuilder: () throws -> GenericRequirementListSyntax) rethrows { +extension GenericRequirementListSyntax { + public init(@GenericRequirementListBuilder itemsBuilder: () throws -> GenericRequirementListSyntax) rethrows { self = try itemsBuilder() } } @@ -371,8 +371,8 @@ public struct IfConfigClauseListBuilder: ListBuilder { public typealias FinalResult = IfConfigClauseListSyntax } -public extension IfConfigClauseListSyntax { - init(@IfConfigClauseListBuilder itemsBuilder: () throws -> IfConfigClauseListSyntax) rethrows { +extension IfConfigClauseListSyntax { + public init(@IfConfigClauseListBuilder itemsBuilder: () throws -> IfConfigClauseListSyntax) rethrows { self = try itemsBuilder() } } @@ -384,8 +384,8 @@ public struct ImportPathComponentListBuilder: ListBuilder { public typealias FinalResult = ImportPathComponentListSyntax } -public extension ImportPathComponentListSyntax { - init(@ImportPathComponentListBuilder itemsBuilder: () throws -> ImportPathComponentListSyntax) rethrows { +extension ImportPathComponentListSyntax { + public init(@ImportPathComponentListBuilder itemsBuilder: () throws -> ImportPathComponentListSyntax) rethrows { self = try itemsBuilder() } } @@ -397,8 +397,8 @@ public struct InheritedTypeListBuilder: ListBuilder { public typealias FinalResult = InheritedTypeListSyntax } -public extension InheritedTypeListSyntax { - init(@InheritedTypeListBuilder itemsBuilder: () throws -> InheritedTypeListSyntax) rethrows { +extension InheritedTypeListSyntax { + public init(@InheritedTypeListBuilder itemsBuilder: () throws -> InheritedTypeListSyntax) rethrows { self = try itemsBuilder() } } @@ -410,8 +410,8 @@ public struct KeyPathComponentListBuilder: ListBuilder { public typealias FinalResult = KeyPathComponentListSyntax } -public extension KeyPathComponentListSyntax { - init(@KeyPathComponentListBuilder itemsBuilder: () throws -> KeyPathComponentListSyntax) rethrows { +extension KeyPathComponentListSyntax { + public init(@KeyPathComponentListBuilder itemsBuilder: () throws -> KeyPathComponentListSyntax) rethrows { self = try itemsBuilder() } } @@ -423,24 +423,24 @@ public struct LabeledExprListBuilder: ListBuilder { public typealias FinalResult = LabeledExprListSyntax } -public extension LabeledExprListSyntax { - init(@LabeledExprListBuilder itemsBuilder: () throws -> LabeledExprListSyntax) rethrows { +extension LabeledExprListSyntax { + public init(@LabeledExprListBuilder itemsBuilder: () throws -> LabeledExprListSyntax) rethrows { self = try itemsBuilder() } } // MARK: - LifetimeSpecifierArgumentListBuilder -@resultBuilder #if compiler(>=5.8) @_spi(ExperimentalLanguageFeatures) #endif +@resultBuilder public struct LifetimeSpecifierArgumentListBuilder: ListBuilder { public typealias FinalResult = LifetimeSpecifierArgumentListSyntax } -public extension LifetimeSpecifierArgumentListSyntax { - init(@LifetimeSpecifierArgumentListBuilder itemsBuilder: () throws -> LifetimeSpecifierArgumentListSyntax) rethrows { +extension LifetimeSpecifierArgumentListSyntax { + public init(@LifetimeSpecifierArgumentListBuilder itemsBuilder: () throws -> LifetimeSpecifierArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -452,8 +452,8 @@ public struct MemberBlockItemListBuilder: ListBuilder { public typealias FinalResult = MemberBlockItemListSyntax } -public extension MemberBlockItemListSyntax { - init(@MemberBlockItemListBuilder itemsBuilder: () throws -> MemberBlockItemListSyntax) rethrows { +extension MemberBlockItemListSyntax { + public init(@MemberBlockItemListBuilder itemsBuilder: () throws -> MemberBlockItemListSyntax) rethrows { self = try itemsBuilder() } } @@ -465,8 +465,8 @@ public struct MultipleTrailingClosureElementListBuilder: ListBuilder { public typealias FinalResult = MultipleTrailingClosureElementListSyntax } -public extension MultipleTrailingClosureElementListSyntax { - init(@MultipleTrailingClosureElementListBuilder itemsBuilder: () throws -> MultipleTrailingClosureElementListSyntax) rethrows { +extension MultipleTrailingClosureElementListSyntax { + public init(@MultipleTrailingClosureElementListBuilder itemsBuilder: () throws -> MultipleTrailingClosureElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -478,8 +478,8 @@ public struct ObjCSelectorPieceListBuilder: ListBuilder { public typealias FinalResult = ObjCSelectorPieceListSyntax } -public extension ObjCSelectorPieceListSyntax { - init(@ObjCSelectorPieceListBuilder itemsBuilder: () throws -> ObjCSelectorPieceListSyntax) rethrows { +extension ObjCSelectorPieceListSyntax { + public init(@ObjCSelectorPieceListBuilder itemsBuilder: () throws -> ObjCSelectorPieceListSyntax) rethrows { self = try itemsBuilder() } } @@ -491,8 +491,8 @@ public struct PatternBindingListBuilder: ListBuilder { public typealias FinalResult = PatternBindingListSyntax } -public extension PatternBindingListSyntax { - init(@PatternBindingListBuilder itemsBuilder: () throws -> PatternBindingListSyntax) rethrows { +extension PatternBindingListSyntax { + public init(@PatternBindingListBuilder itemsBuilder: () throws -> PatternBindingListSyntax) rethrows { self = try itemsBuilder() } } @@ -504,8 +504,8 @@ public struct PlatformVersionItemListBuilder: ListBuilder { public typealias FinalResult = PlatformVersionItemListSyntax } -public extension PlatformVersionItemListSyntax { - init(@PlatformVersionItemListBuilder itemsBuilder: () throws -> PlatformVersionItemListSyntax) rethrows { +extension PlatformVersionItemListSyntax { + public init(@PlatformVersionItemListBuilder itemsBuilder: () throws -> PlatformVersionItemListSyntax) rethrows { self = try itemsBuilder() } } @@ -529,8 +529,8 @@ public struct PrecedenceGroupAttributeListBuilder: ListBuilder { } } -public extension PrecedenceGroupAttributeListSyntax { - init(@PrecedenceGroupAttributeListBuilder itemsBuilder: () throws -> PrecedenceGroupAttributeListSyntax) rethrows { +extension PrecedenceGroupAttributeListSyntax { + public init(@PrecedenceGroupAttributeListBuilder itemsBuilder: () throws -> PrecedenceGroupAttributeListSyntax) rethrows { self = try itemsBuilder() } } @@ -542,8 +542,8 @@ public struct PrecedenceGroupNameListBuilder: ListBuilder { public typealias FinalResult = PrecedenceGroupNameListSyntax } -public extension PrecedenceGroupNameListSyntax { - init(@PrecedenceGroupNameListBuilder itemsBuilder: () throws -> PrecedenceGroupNameListSyntax) rethrows { +extension PrecedenceGroupNameListSyntax { + public init(@PrecedenceGroupNameListBuilder itemsBuilder: () throws -> PrecedenceGroupNameListSyntax) rethrows { self = try itemsBuilder() } } @@ -555,8 +555,8 @@ public struct PrimaryAssociatedTypeListBuilder: ListBuilder { public typealias FinalResult = PrimaryAssociatedTypeListSyntax } -public extension PrimaryAssociatedTypeListSyntax { - init(@PrimaryAssociatedTypeListBuilder itemsBuilder: () throws -> PrimaryAssociatedTypeListSyntax) rethrows { +extension PrimaryAssociatedTypeListSyntax { + public init(@PrimaryAssociatedTypeListBuilder itemsBuilder: () throws -> PrimaryAssociatedTypeListSyntax) rethrows { self = try itemsBuilder() } } @@ -568,8 +568,8 @@ public struct SimpleStringLiteralSegmentListBuilder: ListBuilder { public typealias FinalResult = SimpleStringLiteralSegmentListSyntax } -public extension SimpleStringLiteralSegmentListSyntax { - init(@SimpleStringLiteralSegmentListBuilder itemsBuilder: () throws -> SimpleStringLiteralSegmentListSyntax) rethrows { +extension SimpleStringLiteralSegmentListSyntax { + public init(@SimpleStringLiteralSegmentListBuilder itemsBuilder: () throws -> SimpleStringLiteralSegmentListSyntax) rethrows { self = try itemsBuilder() } } @@ -597,8 +597,8 @@ public struct SpecializeAttributeArgumentListBuilder: ListBuilder { } } -public extension SpecializeAttributeArgumentListSyntax { - init(@SpecializeAttributeArgumentListBuilder itemsBuilder: () throws -> SpecializeAttributeArgumentListSyntax) rethrows { +extension SpecializeAttributeArgumentListSyntax { + public init(@SpecializeAttributeArgumentListBuilder itemsBuilder: () throws -> SpecializeAttributeArgumentListSyntax) rethrows { self = try itemsBuilder() } } @@ -618,8 +618,8 @@ public struct StringLiteralSegmentListBuilder: ListBuilder { } } -public extension StringLiteralSegmentListSyntax { - init(@StringLiteralSegmentListBuilder itemsBuilder: () throws -> StringLiteralSegmentListSyntax) rethrows { +extension StringLiteralSegmentListSyntax { + public init(@StringLiteralSegmentListBuilder itemsBuilder: () throws -> StringLiteralSegmentListSyntax) rethrows { self = try itemsBuilder() } } @@ -631,8 +631,8 @@ public struct SwitchCaseItemListBuilder: ListBuilder { public typealias FinalResult = SwitchCaseItemListSyntax } -public extension SwitchCaseItemListSyntax { - init(@SwitchCaseItemListBuilder itemsBuilder: () throws -> SwitchCaseItemListSyntax) rethrows { +extension SwitchCaseItemListSyntax { + public init(@SwitchCaseItemListBuilder itemsBuilder: () throws -> SwitchCaseItemListSyntax) rethrows { self = try itemsBuilder() } } @@ -652,8 +652,8 @@ public struct SwitchCaseListBuilder: ListBuilder { } } -public extension SwitchCaseListSyntax { - init(@SwitchCaseListBuilder itemsBuilder: () throws -> SwitchCaseListSyntax) rethrows { +extension SwitchCaseListSyntax { + public init(@SwitchCaseListBuilder itemsBuilder: () throws -> SwitchCaseListSyntax) rethrows { self = try itemsBuilder() } } @@ -665,8 +665,8 @@ public struct TuplePatternElementListBuilder: ListBuilder { public typealias FinalResult = TuplePatternElementListSyntax } -public extension TuplePatternElementListSyntax { - init(@TuplePatternElementListBuilder itemsBuilder: () throws -> TuplePatternElementListSyntax) rethrows { +extension TuplePatternElementListSyntax { + public init(@TuplePatternElementListBuilder itemsBuilder: () throws -> TuplePatternElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -678,8 +678,8 @@ public struct TupleTypeElementListBuilder: ListBuilder { public typealias FinalResult = TupleTypeElementListSyntax } -public extension TupleTypeElementListSyntax { - init(@TupleTypeElementListBuilder itemsBuilder: () throws -> TupleTypeElementListSyntax) rethrows { +extension TupleTypeElementListSyntax { + public init(@TupleTypeElementListBuilder itemsBuilder: () throws -> TupleTypeElementListSyntax) rethrows { self = try itemsBuilder() } } @@ -702,8 +702,8 @@ public struct TypeSpecifierListBuilder: ListBuilder { } } -public extension TypeSpecifierListSyntax { - init(@TypeSpecifierListBuilder itemsBuilder: () throws -> TypeSpecifierListSyntax) rethrows { +extension TypeSpecifierListSyntax { + public init(@TypeSpecifierListBuilder itemsBuilder: () throws -> TypeSpecifierListSyntax) rethrows { self = try itemsBuilder() } } @@ -715,8 +715,8 @@ public struct UnexpectedNodesBuilder: ListBuilder { public typealias FinalResult = UnexpectedNodesSyntax } -public extension UnexpectedNodesSyntax { - init(@UnexpectedNodesBuilder itemsBuilder: () throws -> UnexpectedNodesSyntax) rethrows { +extension UnexpectedNodesSyntax { + public init(@UnexpectedNodesBuilder itemsBuilder: () throws -> UnexpectedNodesSyntax) rethrows { self = try itemsBuilder() } } @@ -728,8 +728,8 @@ public struct VersionComponentListBuilder: ListBuilder { public typealias FinalResult = VersionComponentListSyntax } -public extension VersionComponentListSyntax { - init(@VersionComponentListBuilder itemsBuilder: () throws -> VersionComponentListSyntax) rethrows { +extension VersionComponentListSyntax { + public init(@VersionComponentListBuilder itemsBuilder: () throws -> VersionComponentListSyntax) rethrows { self = try itemsBuilder() } } @@ -741,8 +741,8 @@ public struct YieldedExpressionListBuilder: ListBuilder { public typealias FinalResult = YieldedExpressionListSyntax } -public extension YieldedExpressionListSyntax { - init(@YieldedExpressionListBuilder itemsBuilder: () throws -> YieldedExpressionListSyntax) rethrows { +extension YieldedExpressionListSyntax { + public init(@YieldedExpressionListBuilder itemsBuilder: () throws -> YieldedExpressionListSyntax) rethrows { self = try itemsBuilder() } } diff --git a/Sources/SwiftSyntaxBuilder/generated/SyntaxExpressibleByStringInterpolationConformances.swift b/Sources/SwiftSyntaxBuilder/generated/SyntaxExpressibleByStringInterpolationConformances.swift index 1119428842e..c999b3f2f8f 100644 --- a/Sources/SwiftSyntaxBuilder/generated/SyntaxExpressibleByStringInterpolationConformances.swift +++ b/Sources/SwiftSyntaxBuilder/generated/SyntaxExpressibleByStringInterpolationConformances.swift @@ -12,7 +12,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif extension AccessorBlockSyntax: SyntaxExpressibleByStringInterpolation {} @@ -122,6 +126,12 @@ extension TypeSyntax: SyntaxExpressibleByStringInterpolation {} extension TypeSyntax: @retroactive ExpressibleByStringInterpolation {} #endif +extension VersionTupleSyntax: SyntaxExpressibleByStringInterpolation {} + +#if compiler(>=6) +extension VersionTupleSyntax: @retroactive ExpressibleByStringInterpolation {} +#endif + extension AccessorDeclListSyntax: SyntaxExpressibleByStringInterpolation {} #if compiler(>=6) diff --git a/Sources/SwiftSyntaxMacroExpansion/BasicMacroExpansionContext.swift b/Sources/SwiftSyntaxMacroExpansion/BasicMacroExpansionContext.swift index 1cd2fc00f65..4701332d1fb 100644 --- a/Sources/SwiftSyntaxMacroExpansion/BasicMacroExpansionContext.swift +++ b/Sources/SwiftSyntaxMacroExpansion/BasicMacroExpansionContext.swift @@ -12,7 +12,7 @@ #if swift(>=6) public import SwiftDiagnostics -import SwiftOperators +internal import SwiftOperators public import SwiftSyntax public import SwiftSyntaxMacros #else diff --git a/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift b/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift index f3794d7ebe9..6ab1294d5b7 100644 --- a/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift +++ b/Sources/SwiftSyntaxMacroExpansion/IndentationUtils.swift @@ -10,7 +10,11 @@ // //===----------------------------------------------------------------------===// +#if swift(>=6) +internal import SwiftSyntax +#else import SwiftSyntax +#endif // MARK: SyntaxProtocol.indentationOfFirstLine diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroArgument.swift b/Sources/SwiftSyntaxMacroExpansion/MacroArgument.swift index 68500c20675..855c3e831ab 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroArgument.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroArgument.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftDiagnostics +internal import SwiftDiagnostics public import SwiftSyntax #else import SwiftDiagnostics 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..23961c8ec5c 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroReplacement.swift @@ -11,9 +11,9 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftDiagnostics +internal import SwiftDiagnostics public import SwiftSyntax -import SwiftSyntaxBuilder +internal import SwiftSyntaxBuilder #else import SwiftDiagnostics import SwiftSyntax @@ -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/MacroSpec.swift b/Sources/SwiftSyntaxMacroExpansion/MacroSpec.swift index 4d5401d8662..c2f0033a750 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroSpec.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroSpec.swift @@ -21,7 +21,7 @@ import SwiftSyntaxMacros /// The information of a macro declaration, to be used with `assertMacroExpansion`. /// /// In addition to specifying the macro’s type, this allows the specification of conformances that will be passed to the macro’s `expansion` function. -public struct MacroSpec { +public struct MacroSpec: Sendable { /// The type of macro. let type: Macro.Type /// The list of types for which the macro needs to add conformances. diff --git a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift index 5d46aee2089..1c539aeb296 100644 --- a/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift +++ b/Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift @@ -11,11 +11,11 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftDiagnostics -import SwiftOperators -@_spi(MacroExpansion) import SwiftParser +internal import SwiftDiagnostics +internal import SwiftOperators +@_spi(MacroExpansion) internal import SwiftParser public import SwiftSyntax -import SwiftSyntaxBuilder +internal import SwiftSyntaxBuilder @_spi(MacroExpansion) @_spi(ExperimentalLanguageFeature) public import SwiftSyntaxMacros #else import SwiftDiagnostics @@ -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..450e3a5d037 100644 --- a/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift +++ b/Sources/SwiftSyntaxMacros/MacroExpansionContext.swift @@ -88,11 +88,18 @@ extension MacroExpansionContext { return location(of: node, at: .afterLeadingTrivia, filePathMode: .fileID) } + #if compiler(>=6.0) + @available(*, deprecated, message: "`MacroExpansionContext` conformance must implement `lexicalContext`") + public var lexicalContext: [Syntax] { + return [] + } + #else public var lexicalContext: [Syntax] { fatalError( "`MacroExpansionContext` conformance must implement `lexicalContext`" ) } + #endif } /// Diagnostic message used for thrown errors. @@ -116,7 +123,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/SwiftSyntaxMacros/MacroProtocols/BodyMacro.swift b/Sources/SwiftSyntaxMacros/MacroProtocols/BodyMacro.swift index 13b96e05821..d5a53710fa4 100644 --- a/Sources/SwiftSyntaxMacros/MacroProtocols/BodyMacro.swift +++ b/Sources/SwiftSyntaxMacros/MacroProtocols/BodyMacro.swift @@ -16,7 +16,6 @@ import SwiftSyntax /// Describes a macro that can create the body for a function that does not /// have one. -@_spi(ExperimentalLanguageFeature) public protocol BodyMacro: AttachedMacro { /// Expand a macro described by the given custom attribute and /// attached to the given declaration and evaluated within a diff --git a/Sources/SwiftSyntaxMacros/MacroProtocols/DeclarationMacro.swift b/Sources/SwiftSyntaxMacros/MacroProtocols/DeclarationMacro.swift index da54b3479a4..4496328c2d5 100644 --- a/Sources/SwiftSyntaxMacros/MacroProtocols/DeclarationMacro.swift +++ b/Sources/SwiftSyntaxMacros/MacroProtocols/DeclarationMacro.swift @@ -31,7 +31,7 @@ public protocol DeclarationMacro: FreestandingMacro { static var propagateFreestandingMacroModifiers: Bool { get } } -public extension DeclarationMacro { - static var propagateFreestandingMacroAttributes: Bool { true } - static var propagateFreestandingMacroModifiers: Bool { true } +extension DeclarationMacro { + public static var propagateFreestandingMacroAttributes: Bool { true } + public static var propagateFreestandingMacroModifiers: Bool { true } } diff --git a/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift b/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift index 0672ca8877d..67e58c89762 100644 --- a/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift +++ b/Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// /// Describes the mode to use to format the result of an expansion. -public enum FormatMode { +public enum FormatMode: Sendable { /// Perform a basic format of the expansion. This is primarily for inserting /// whitespace as required (eg. between two keywords), but also adds simple /// newline and indentation. @@ -22,8 +22,8 @@ public enum FormatMode { case disabled } -public extension Macro { - static var formatMode: FormatMode { +extension Macro { + public static var formatMode: FormatMode { return .auto } } diff --git a/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift b/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift index 86cb762d923..4e021220b76 100644 --- a/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift +++ b/Sources/SwiftSyntaxMacros/MacroProtocols/MemberMacro.swift @@ -70,9 +70,9 @@ private struct UnimplementedExpansionMethodError: Error, CustomStringConvertible } } -public extension MemberMacro { +extension MemberMacro { /// Default implementation supplies no conformances. - static func expansion( + public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext @@ -81,7 +81,7 @@ public extension MemberMacro { } /// Default implementation that ignores the unhandled conformances. - static func expansion( + public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, conformingTo protocols: [TypeSyntax], diff --git a/Sources/SwiftSyntaxMacrosGenericTestSupport/Assertions.swift b/Sources/SwiftSyntaxMacrosGenericTestSupport/Assertions.swift new file mode 100644 index 00000000000..8f204aafbf3 --- /dev/null +++ b/Sources/SwiftSyntaxMacrosGenericTestSupport/Assertions.swift @@ -0,0 +1,607 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if swift(>=6.0) +import SwiftBasicFormat +public import SwiftDiagnostics +@_spi(FixItApplier) import SwiftIDEUtils +import SwiftParser +import SwiftParserDiagnostics +public import SwiftSyntax +public import SwiftSyntaxMacroExpansion +private import SwiftSyntaxMacros +private import _SwiftSyntaxGenericTestSupport +#else +import SwiftBasicFormat +import SwiftDiagnostics +@_spi(FixItApplier) import SwiftIDEUtils +import SwiftParser +import SwiftParserDiagnostics +import SwiftSyntax +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacros +import _SwiftSyntaxGenericTestSupport +#endif + +/// Defines the location at which the a test failure should be anchored. This is typically the location where the +/// assertion function is called. +public struct TestFailureLocation { + @_spi(XCTestFailureLocation) public let staticFileID: StaticString + public var fileID: String { staticFileID.description } + + @_spi(XCTestFailureLocation) public let staticFilePath: StaticString + public var filePath: String { staticFilePath.description } + + @_spi(XCTestFailureLocation) public let unsignedLine: UInt + public var line: Int { Int(unsignedLine) } + + @_spi(XCTestFailureLocation) public let unsignedColumn: UInt + public var column: Int { Int(unsignedColumn) } + + public init( + fileID: StaticString, + filePath: StaticString, + line: UInt, + column: UInt + ) { + self.staticFileID = fileID + self.staticFilePath = filePath + self.unsignedLine = line + self.unsignedColumn = column + } + + fileprivate init(underlying: _SwiftSyntaxGenericTestSupport.TestFailureLocation) { + self.init( + fileID: underlying.fileID, + filePath: underlying.filePath, + line: underlying.line, + column: underlying.column + ) + } + + /// This type is intentionally different to `_SwiftSyntaxGenericTestSupport.TestFailureLocation` so we can + /// import `_SwiftSyntaxGenericTestSupport` privately and don't expose its internal types. + fileprivate var underlying: _SwiftSyntaxGenericTestSupport.TestFailureLocation { + _SwiftSyntaxGenericTestSupport.TestFailureLocation( + fileID: self.staticFileID, + filePath: self.staticFilePath, + line: self.unsignedLine, + column: self.unsignedColumn + ) + } +} + +/// Defines the details of a test failure, consisting of a message and the location at which the test failure should be +/// shown. +public struct TestFailureSpec { + public let message: String + public let location: TestFailureLocation + + public init(message: String, location: TestFailureLocation) { + self.message = message + self.location = location + } + + fileprivate init(underlying: _SwiftSyntaxGenericTestSupport.TestFailureSpec) { + self.init( + message: underlying.message, + location: TestFailureLocation(underlying: underlying.location) + ) + } +} + +// MARK: - Note + +/// Describes a diagnostic note that tests expect to be created by a macro expansion. +public struct NoteSpec { + /// The expected message of the note + public let message: String + + /// The line to which the note is expected to point + public let line: Int + + /// The column to which the note is expected to point + public let column: Int + + /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + internal let failureLocation: TestFailureLocation + + /// Creates a new ``NoteSpec`` that describes a note tests are expecting to be generated by a macro expansion. + /// + /// - Parameters: + /// - message: The expected message of the note + /// - line: The line to which the note is expected to point + /// - column: The column to which the note is expected to point + /// - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + /// - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + public init( + message: String, + line: Int, + column: Int, + originatorFileID: StaticString = #fileID, + originatorFile: StaticString = #filePath, + originatorLine: UInt = #line, + originatorColumn: UInt = #column + ) { + self.message = message + self.line = line + self.column = column + self.failureLocation = TestFailureLocation( + fileID: originatorFileID, + filePath: originatorFile, + line: originatorLine, + column: originatorColumn + ) + } +} + +func assertNote( + _ note: Note, + in expansionContext: BasicMacroExpansionContext, + expected spec: NoteSpec, + failureHandler: (TestFailureSpec) -> Void +) { + assertStringsEqualWithDiff( + note.message, + spec.message, + "message of note does not match", + location: spec.failureLocation.underlying, + failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) } + ) + let location = expansionContext.location(for: note.position, anchoredAt: note.node, fileName: "") + if location.line != spec.line { + failureHandler( + TestFailureSpec( + message: "line of note \(location.line) does not match expected line \(spec.line)", + location: spec.failureLocation + ) + ) + } + if location.column != spec.column { + failureHandler( + TestFailureSpec( + message: "column of note \(location.column) does not match expected column \(spec.column)", + location: spec.failureLocation + ) + ) + } +} + +// MARK: - Fix-It + +/// Describes a Fix-It that tests expect to be created by a macro expansion. +/// +/// Currently, it only compares the message of the Fix-It. In the future, it might +/// also compare the expected changes that should be performed by the Fix-It. +public struct FixItSpec { + /// The expected message of the Fix-It + public let message: String + + /// The file and line at which this ``FixItSpec`` was created, so that assertion failures can be reported at its location. + internal let failureLocation: TestFailureLocation + + /// Creates a new ``FixItSpec`` that describes a Fix-It tests are expecting to be generated by a macro expansion. + /// + /// - Parameters: + /// - message: The expected message of the note + /// - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + /// - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + public init( + message: String, + originatorFileID: StaticString = #fileID, + originatorFile: StaticString = #filePath, + originatorLine: UInt = #line, + originatorColumn: UInt = #column + ) { + self.message = message + self.failureLocation = TestFailureLocation( + fileID: originatorFileID, + filePath: originatorFile, + line: originatorLine, + column: originatorColumn + ) + } +} + +func assertFixIt( + _ fixIt: FixIt, + expected spec: FixItSpec, + failureHandler: (TestFailureSpec) -> Void +) { + assertStringsEqualWithDiff( + fixIt.message.message, + spec.message, + "message of Fix-It does not match", + location: spec.failureLocation.underlying, + failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) } + ) +} + +// MARK: - Diagnostic + +/// Describes a diagnostic that tests expect to be created by a macro expansion. +public struct DiagnosticSpec { + /// If not `nil`, the ID, which the diagnostic is expected to have. + public let id: MessageID? + + /// The expected message of the diagnostic + public let message: String + + /// The line to which the diagnostic is expected to point + public let line: Int + + /// The column to which the diagnostic is expected to point + public let column: Int + + /// The expected severity of the diagnostic + public let severity: DiagnosticSeverity + + /// If not `nil`, the text fragments the diagnostic is expected to highlight + public let highlights: [String]? + + /// The notes that are expected to be attached to the diagnostic + public let notes: [NoteSpec] + + /// The messages of the Fix-Its the diagnostic is expected to produce + public let fixIts: [FixItSpec] + + /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + internal let failureLocation: TestFailureLocation + + /// Creates a new ``DiagnosticSpec`` that describes a diagnostic tests are expecting to be generated by a macro expansion. + /// + /// - Parameters: + /// - id: If not `nil`, the ID, which the diagnostic is expected to have. + /// - message: The expected message of the diagnostic + /// - line: The line to which the diagnostic is expected to point + /// - column: The column to which the diagnostic is expected to point + /// - severity: The expected severity of the diagnostic + /// - highlights: If not empty, the text fragments the diagnostic is expected to highlight + /// - notes: The notes that are expected to be attached to the diagnostic + /// - fixIts: The messages of the Fix-Its the diagnostic is expected to produce + /// - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + /// - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. + public init( + id: MessageID? = nil, + message: String, + line: Int, + column: Int, + severity: DiagnosticSeverity = .error, + highlights: [String]? = nil, + notes: [NoteSpec] = [], + fixIts: [FixItSpec] = [], + originatorFileID: StaticString = #fileID, + originatorFile: StaticString = #filePath, + originatorLine: UInt = #line, + originatorColumn: UInt = #column + ) { + self.id = id + self.message = message + self.line = line + self.column = column + self.severity = severity + self.highlights = highlights + self.notes = notes + self.fixIts = fixIts + self.failureLocation = TestFailureLocation( + fileID: originatorFileID, + filePath: originatorFile, + line: originatorLine, + column: originatorColumn + ) + } +} + +extension DiagnosticSpec { + @available(*, deprecated, message: "Use highlights instead") + public var highlight: String? { + guard let highlights else { + return nil + } + return highlights.joined(separator: " ") + } + + // 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, + line: Int, + column: Int, + severity: DiagnosticSeverity = .error, + highlight: String? = nil, + notes: [NoteSpec] = [], + fixIts: [FixItSpec] = [], + originatorFile: StaticString = #filePath, + originatorLine: UInt = #line + ) { + self.init( + id: id, + message: message, + line: line, + column: column, + severity: severity, + highlights: highlight.map { [$0] }, + notes: notes, + fixIts: fixIts + ) + } +} + +func assertDiagnostic( + _ diag: Diagnostic, + in expansionContext: BasicMacroExpansionContext, + expected spec: DiagnosticSpec, + failureHandler: (TestFailureSpec) -> Void +) { + if let id = spec.id, diag.diagnosticID != id { + failureHandler( + TestFailureSpec( + message: "diagnostic ID \(diag.diagnosticID) does not match expected id \(id)", + location: spec.failureLocation + ) + ) + } + assertStringsEqualWithDiff( + diag.message, + spec.message, + "message does not match", + location: spec.failureLocation.underlying, + failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) } + ) + let location = expansionContext.location(for: diag.position, anchoredAt: diag.node, fileName: "") + if location.line != spec.line { + failureHandler( + TestFailureSpec( + message: "line \(location.line) does not match expected line \(spec.line)", + location: spec.failureLocation + ) + ) + } + if location.column != spec.column { + failureHandler( + TestFailureSpec( + message: "column \(location.column) does not match expected column \(spec.column)", + location: spec.failureLocation + ) + ) + } + + if spec.severity != diag.diagMessage.severity { + failureHandler( + TestFailureSpec( + message: "severity \(diag.diagMessage.severity) does not match expected severity \(spec.severity)", + location: spec.failureLocation + ) + ) + } + + if let highlights = spec.highlights { + if diag.highlights.count != highlights.count { + failureHandler( + TestFailureSpec( + message: """ + Expected \(highlights.count) highlights but received \(diag.highlights.count): + \(diag.highlights.map(\.trimmedDescription).joined(separator: "\n")) + """, + location: spec.failureLocation + ) + ) + } else { + for (actual, expected) in zip(diag.highlights, highlights) { + assertStringsEqualWithDiff( + actual.trimmedDescription, + expected, + "highlight does not match", + location: spec.failureLocation.underlying, + failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) } + ) + } + } + } + if diag.notes.count != spec.notes.count { + failureHandler( + TestFailureSpec( + message: """ + Expected \(spec.notes.count) notes but received \(diag.notes.count): + \(diag.notes.map(\.debugDescription).joined(separator: "\n")) + """, + location: spec.failureLocation + ) + ) + } else { + for (note, expectedNote) in zip(diag.notes, spec.notes) { + assertNote(note, in: expansionContext, expected: expectedNote, failureHandler: failureHandler) + } + } + if diag.fixIts.count != spec.fixIts.count { + failureHandler( + TestFailureSpec( + message: """ + Expected \(spec.fixIts.count) Fix-Its but received \(diag.fixIts.count): + \(diag.fixIts.map(\.message.message).joined(separator: "\n")) + """, + location: spec.failureLocation + ) + ) + } else { + for (fixIt, expectedFixIt) in zip(diag.fixIts, spec.fixIts) { + assertFixIt(fixIt, expected: expectedFixIt, failureHandler: failureHandler) + } + } +} + +/// Assert that expanding the given macros in the original source produces +/// the given expanded source code. +/// +/// - Parameters: +/// - originalSource: The original source code, which is expected to contain +/// macros in various places (e.g., `#stringify(x + y)`). +/// - expectedExpandedSource: The source code that we expect to see after +/// performing macro expansion on the original source. +/// - diagnostics: The diagnostics when expanding any macro +/// - macroSpecs: The macros that should be expanded, provided as a dictionary +/// mapping macro names (e.g., `"CodableMacro"`) to specification with macro type +/// (e.g., `CodableMacro.self`) and a list of conformances macro provides +/// (e.g., `["Decodable", "Encodable"]`). +/// - applyFixIts: If specified, filters the Fix-Its that are applied to generate `fixedSource` to only those whose message occurs in this array. If `nil`, all Fix-Its from the diagnostics are applied. +/// - fixedSource: If specified, asserts that the source code after applying Fix-Its matches this string. +/// - testModuleName: The name of the test module to use. +/// - testFileName: The name of the test file name to use. +/// - indentationWidth: The indentation width used in the expansion. +public func assertMacroExpansion( + _ originalSource: String, + expandedSource expectedExpandedSource: String, + diagnostics: [DiagnosticSpec] = [], + macroSpecs: [String: MacroSpec], + applyFixIts: [String]? = nil, + fixedSource expectedFixedSource: String? = nil, + testModuleName: String = "TestModule", + testFileName: String = "test.swift", + indentationWidth: Trivia = .spaces(4), + failureHandler: (TestFailureSpec) -> Void, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column +) { + let failureLocation = TestFailureLocation(fileID: fileID, filePath: filePath, line: line, column: column) + // Parse the original source file. + let origSourceFile = Parser.parse(source: originalSource) + + // Expand all macros in the source. + let context = BasicMacroExpansionContext( + sourceFiles: [origSourceFile: .init(moduleName: testModuleName, fullFilePath: testFileName)] + ) + + func contextGenerator(_ syntax: Syntax) -> BasicMacroExpansionContext { + return BasicMacroExpansionContext(sharingWith: context, lexicalContext: syntax.allMacroLexicalContexts()) + } + + let expandedSourceFile = origSourceFile.expand( + macroSpecs: macroSpecs, + contextGenerator: contextGenerator, + indentationWidth: indentationWidth + ) + let diags = ParseDiagnosticsGenerator.diagnostics(for: expandedSourceFile) + if !diags.isEmpty { + failureHandler( + TestFailureSpec( + message: """ + Expanded source should not contain any syntax errors, but contains: + \(DiagnosticsFormatter.annotatedSource(tree: expandedSourceFile, diags: diags)) + + Expanded syntax tree was: + \(expandedSourceFile.debugDescription) + """, + location: failureLocation + ) + ) + } + + assertStringsEqualWithDiff( + expandedSourceFile.description.drop(while: \.isNewline).droppingLast(while: \.isNewline), + expectedExpandedSource.drop(while: \.isNewline).droppingLast(while: \.isNewline), + "Macro expansion did not produce the expected expanded source", + additionalInfo: """ + Actual expanded source: + \(expandedSourceFile) + """, + location: failureLocation.underlying, + failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) } + ) + + if context.diagnostics.count != diagnostics.count { + failureHandler( + TestFailureSpec( + message: """ + Expected \(diagnostics.count) diagnostics but received \(context.diagnostics.count): + \(context.diagnostics.map(\.debugDescription).joined(separator: "\n")) + """, + location: failureLocation + ) + ) + } else { + for (actualDiag, expectedDiag) in zip(context.diagnostics, diagnostics) { + assertDiagnostic(actualDiag, in: context, expected: expectedDiag, failureHandler: failureHandler) + } + } + + // Applying Fix-Its + if let expectedFixedSource = expectedFixedSource { + let messages = applyFixIts ?? context.diagnostics.compactMap { $0.fixIts.first?.message.message } + + let edits = + context.diagnostics + .flatMap(\.fixIts) + .filter { messages.contains($0.message.message) } + .flatMap { $0.changes } + .map { $0.edit(in: context) } + + let fixedTree = FixItApplier.apply(edits: edits, to: origSourceFile) + let fixedTreeDescription = fixedTree.description + assertStringsEqualWithDiff( + fixedTreeDescription.trimmingTrailingWhitespace(), + expectedFixedSource.trimmingTrailingWhitespace(), + location: failureLocation.underlying, + failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) } + ) + } +} + +fileprivate extension FixIt.Change { + /// Returns the edit for this change, translating positions from detached nodes + /// to the corresponding locations in the original source file based on + /// `expansionContext`. + /// + /// - SeeAlso: `FixIt.Change.edit` + func edit(in expansionContext: BasicMacroExpansionContext) -> SourceEdit { + switch self { + case .replace(let oldNode, let newNode): + let start = expansionContext.position(of: oldNode.position, anchoredAt: oldNode) + let end = expansionContext.position(of: oldNode.endPosition, anchoredAt: oldNode) + return SourceEdit( + range: start.. AbsolutePosition { + let location = self.location(for: position, anchoredAt: Syntax(node), fileName: "") + return AbsolutePosition(utf8Offset: location.offset) + } +} diff --git a/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift b/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift index 6ad8ca9fe22..50296b267ab 100644 --- a/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift +++ b/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift @@ -11,290 +11,23 @@ //===----------------------------------------------------------------------===// #if swift(>=6.0) -import SwiftBasicFormat -public import SwiftDiagnostics -@_spi(FixItApplier) import SwiftIDEUtils -import SwiftParser -import SwiftParserDiagnostics public import SwiftSyntax public import SwiftSyntaxMacroExpansion public import SwiftSyntaxMacros -import _SwiftSyntaxTestSupport +@_spi(XCTestFailureLocation) public import SwiftSyntaxMacrosGenericTestSupport private import XCTest #else -import SwiftBasicFormat -import SwiftDiagnostics -@_spi(FixItApplier) import SwiftIDEUtils -import SwiftParser -import SwiftParserDiagnostics import SwiftSyntax import SwiftSyntaxMacroExpansion import SwiftSyntaxMacros -import _SwiftSyntaxTestSupport +@_spi(XCTestFailureLocation) import SwiftSyntaxMacrosGenericTestSupport import XCTest #endif -// MARK: - Note - -/// Describes a diagnostic note that tests expect to be created by a macro expansion. -public struct NoteSpec { - /// The expected message of the note - public let message: String - - /// The line to which the note is expected to point - public let line: Int - - /// The column to which the note is expected to point - public let column: Int - - /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - internal let originatorFile: StaticString - internal let originatorLine: UInt - - /// Creates a new ``NoteSpec`` that describes a note tests are expecting to be generated by a macro expansion. - /// - /// - Parameters: - /// - message: The expected message of the note - /// - line: The line to which the note is expected to point - /// - column: The column to which the note is expected to point - /// - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - /// - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - public init( - message: String, - line: Int, - column: Int, - originatorFile: StaticString = #file, - originatorLine: UInt = #line - ) { - self.message = message - self.line = line - self.column = column - self.originatorFile = originatorFile - self.originatorLine = originatorLine - } -} - -func assertNote( - _ note: Note, - in expansionContext: BasicMacroExpansionContext, - expected spec: NoteSpec -) { - 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) -} - -// MARK: - Fix-It - -/// Describes a Fix-It that tests expect to be created by a macro expansion. -/// -/// Currently, it only compares the message of the Fix-It. In the future, it might -/// also compare the expected changes that should be performed by the Fix-It. -public struct FixItSpec { - /// The expected message of the Fix-It - public let message: String - - /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - internal let originatorFile: StaticString - internal let originatorLine: UInt - - /// Creates a new ``FixItSpec`` that describes a Fix-It tests are expecting to be generated by a macro expansion. - /// - /// - Parameters: - /// - message: The expected message of the note - /// - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - /// - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - public init( - message: String, - originatorFile: StaticString = #filePath, - originatorLine: UInt = #line - ) { - self.message = message - self.originatorFile = originatorFile - self.originatorLine = originatorLine - } -} - -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) -} - -// MARK: - Diagnostic - -/// Describes a diagnostic that tests expect to be created by a macro expansion. -public struct DiagnosticSpec { - /// If not `nil`, the ID, which the diagnostic is expected to have. - public let id: MessageID? - - /// The expected message of the diagnostic - public let message: String - - /// The line to which the diagnostic is expected to point - public let line: Int - - /// The column to which the diagnostic is expected to point - public let column: Int - - /// The expected severity of the diagnostic - public let severity: DiagnosticSeverity - - /// If not `nil`, the text fragments the diagnostic is expected to highlight - public let highlights: [String]? - - /// The notes that are expected to be attached to the diagnostic - public let notes: [NoteSpec] - - /// The messages of the Fix-Its the diagnostic is expected to produce - public let fixIts: [FixItSpec] - - /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - internal let originatorFile: StaticString - internal let originatorLine: UInt - - /// Creates a new ``DiagnosticSpec`` that describes a diagnostic tests are expecting to be generated by a macro expansion. - /// - /// - Parameters: - /// - id: If not `nil`, the ID, which the diagnostic is expected to have. - /// - message: The expected message of the diagnostic - /// - line: The line to which the diagnostic is expected to point - /// - column: The column to which the diagnostic is expected to point - /// - severity: The expected severity of the diagnostic - /// - highlights: If not empty, the text fragments the diagnostic is expected to highlight - /// - notes: The notes that are expected to be attached to the diagnostic - /// - fixIts: The messages of the Fix-Its the diagnostic is expected to produce - /// - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - /// - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location. - public init( - id: MessageID? = nil, - message: String, - line: Int, - column: Int, - severity: DiagnosticSeverity = .error, - highlights: [String]? = nil, - notes: [NoteSpec] = [], - fixIts: [FixItSpec] = [], - originatorFile: StaticString = #filePath, - originatorLine: UInt = #line - ) { - self.id = id - self.message = message - self.line = line - self.column = column - self.severity = severity - self.highlights = highlights - self.notes = notes - self.fixIts = fixIts - self.originatorFile = originatorFile - self.originatorLine = originatorLine - } -} - -extension DiagnosticSpec { - @available(*, deprecated, message: "Use highlights instead") - public var highlight: String? { - guard let highlights else { - return nil - } - return highlights.joined(separator: " ") - } - - @_disfavoredOverload - @available(*, deprecated, message: "Use init(id:message:line:column:severity:highlights:notes:fixIts:originatorFile:originatorLine:) instead") - public init( - id: MessageID? = nil, - message: String, - line: Int, - column: Int, - severity: DiagnosticSeverity = .error, - highlight: String? = nil, - notes: [NoteSpec] = [], - fixIts: [FixItSpec] = [], - originatorFile: StaticString = #filePath, - originatorLine: UInt = #line - ) { - self.init( - id: id, - message: message, - line: line, - column: column, - severity: severity, - highlights: highlight.map { [$0] }, - notes: notes, - fixIts: fixIts - ) - } -} - -func assertDiagnostic( - _ diag: Diagnostic, - in expansionContext: BasicMacroExpansionContext, - expected spec: DiagnosticSpec -) { - if let id = spec.id { - 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) - 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(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 { - XCTFail( - """ - Expected \(highlights.count) highlights but received \(diag.highlights.count): - \(diag.highlights.map(\.trimmedDescription).joined(separator: "\n")) - """, - file: spec.originatorFile, - line: spec.originatorLine - ) - } else { - for (actual, expected) in zip(diag.highlights, highlights) { - assertStringsEqualWithDiff( - actual.trimmedDescription, - expected, - "highlight does not match", - file: spec.originatorFile, - line: spec.originatorLine - ) - } - } - } - if diag.notes.count != spec.notes.count { - XCTFail( - """ - Expected \(spec.notes.count) notes but received \(diag.notes.count): - \(diag.notes.map(\.debugDescription).joined(separator: "\n")) - """, - file: spec.originatorFile, - line: spec.originatorLine - ) - } else { - for (note, expectedNote) in zip(diag.notes, spec.notes) { - assertNote(note, in: expansionContext, expected: expectedNote) - } - } - if diag.fixIts.count != spec.fixIts.count { - XCTFail( - """ - Expected \(spec.fixIts.count) Fix-Its but received \(diag.fixIts.count): - \(diag.fixIts.map(\.message.message).joined(separator: "\n")) - """, - file: spec.originatorFile, - line: spec.originatorLine - ) - } else { - for (fixIt, expectedFixIt) in zip(diag.fixIts, spec.fixIts) { - assertFixIt(fixIt, expected: expectedFixIt) - } - } -} +// Re-export the spec types from `SwiftSyntaxMacrosGenericTestSupport`. +public typealias NoteSpec = SwiftSyntaxMacrosGenericTestSupport.NoteSpec +public typealias FixItSpec = SwiftSyntaxMacrosGenericTestSupport.FixItSpec +public typealias DiagnosticSpec = SwiftSyntaxMacrosGenericTestSupport.DiagnosticSpec /// Assert that expanding the given macros in the original source produces /// the given expanded source code. @@ -337,7 +70,9 @@ public func assertMacroExpansion( fixedSource: expectedFixedSource, testModuleName: testModuleName, testFileName: testFileName, - indentationWidth: indentationWidth + indentationWidth: indentationWidth, + file: file, + line: line ) } @@ -372,126 +107,22 @@ public func assertMacroExpansion( file: StaticString = #filePath, line: UInt = #line ) { - // Parse the original source file. - let origSourceFile = Parser.parse(source: originalSource) - - // Expand all macros in the source. - let context = BasicMacroExpansionContext( - sourceFiles: [origSourceFile: .init(moduleName: testModuleName, fullFilePath: testFileName)] - ) - - func contextGenerator(_ syntax: Syntax) -> BasicMacroExpansionContext { - return BasicMacroExpansionContext(sharingWith: context, lexicalContext: syntax.allMacroLexicalContexts()) - } - - let expandedSourceFile = origSourceFile.expand(macroSpecs: macroSpecs, contextGenerator: contextGenerator, indentationWidth: indentationWidth) - let diags = ParseDiagnosticsGenerator.diagnostics(for: expandedSourceFile) - if !diags.isEmpty { - XCTFail( - """ - Expanded source should not contain any syntax errors, but contains: - \(DiagnosticsFormatter.annotatedSource(tree: expandedSourceFile, diags: diags)) - - Expanded syntax tree was: - \(expandedSourceFile.debugDescription) - """, - file: file, - line: line - ) - } - - assertStringsEqualWithDiff( - expandedSourceFile.description.trimmingCharacters(in: .newlines), - expectedExpandedSource.trimmingCharacters(in: .newlines), - "Macro expansion did not produce the expected expanded source", - additionalInfo: """ - Actual expanded source: - \(expandedSourceFile) - """, - file: file, - line: line + SwiftSyntaxMacrosGenericTestSupport.assertMacroExpansion( + originalSource, + expandedSource: expectedExpandedSource, + diagnostics: diagnostics, + macroSpecs: macroSpecs, + applyFixIts: applyFixIts, + fixedSource: expectedFixedSource, + testModuleName: testModuleName, + testFileName: testFileName, + indentationWidth: indentationWidth, + failureHandler: { + XCTFail($0.message, file: $0.location.staticFilePath, line: $0.location.unsignedLine) + }, + fileID: "", // Not used in the failure handler + filePath: file, + line: line, + column: 0 // Not used in the failure handler ) - - if context.diagnostics.count != diagnostics.count { - XCTFail( - """ - Expected \(diagnostics.count) diagnostics but received \(context.diagnostics.count): - \(context.diagnostics.map(\.debugDescription).joined(separator: "\n")) - """, - file: file, - line: line - ) - } else { - for (actualDiag, expectedDiag) in zip(context.diagnostics, diagnostics) { - assertDiagnostic(actualDiag, in: context, expected: expectedDiag) - } - } - - // Applying Fix-Its - if let expectedFixedSource = expectedFixedSource { - let messages = applyFixIts ?? context.diagnostics.compactMap { $0.fixIts.first?.message.message } - - let edits = - context.diagnostics - .flatMap(\.fixIts) - .filter { messages.contains($0.message.message) } - .flatMap { $0.changes } - .map { $0.edit(in: context) } - - let fixedTree = FixItApplier.apply(edits: edits, to: origSourceFile) - let fixedTreeDescription = fixedTree.description - assertStringsEqualWithDiff( - fixedTreeDescription.trimmingTrailingWhitespace(), - expectedFixedSource.trimmingTrailingWhitespace(), - file: file, - line: line - ) - } -} - -fileprivate extension FixIt.Change { - /// Returns the edit for this change, translating positions from detached nodes - /// to the corresponding locations in the original source file based on - /// `expansionContext`. - /// - /// - SeeAlso: `FixIt.Change.edit` - func edit(in expansionContext: BasicMacroExpansionContext) -> SourceEdit { - switch self { - case .replace(let oldNode, let newNode): - let start = expansionContext.position(of: oldNode.position, anchoredAt: oldNode) - let end = expansionContext.position(of: oldNode.endPosition, anchoredAt: oldNode) - return SourceEdit( - range: start.. AbsolutePosition { - let location = self.location(for: position, anchoredAt: Syntax(node), fileName: "") - return AbsolutePosition(utf8Offset: location.offset) - } } diff --git a/Sources/_AtomicBool/include/SwiftSyntaxAtomicBool.h b/Sources/_AtomicBool/include/SwiftSyntaxAtomicBool.h deleted file mode 100644 index 28d45c06d96..00000000000 --- a/Sources/_AtomicBool/include/SwiftSyntaxAtomicBool.h +++ /dev/null @@ -1,26 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// - -#include - -typedef struct { - _Atomic(bool) value; -} AtomicBool; - -__attribute__((swift_name("AtomicBool.init(initialValue:)"))) -AtomicBool atomic_bool_create(bool initialValue); - -__attribute__((swift_name("getter:AtomicBool.value(self:)"))) -bool atomic_bool_get(AtomicBool *atomic); - -__attribute__((swift_name("setter:AtomicBool.value(self:_:)"))) -void atomic_bool_set(AtomicBool *atomic, bool newValue); diff --git a/Sources/_SwiftLibraryPluginProviderCShims/CMakeLists.txt b/Sources/_SwiftLibraryPluginProviderCShims/CMakeLists.txt new file mode 100644 index 00000000000..6efd0094d41 --- /dev/null +++ b/Sources/_SwiftLibraryPluginProviderCShims/CMakeLists.txt @@ -0,0 +1,6 @@ +add_library(_SwiftLibraryPluginProviderCShims STATIC + LoadLibrary.c +) +target_include_directories(_SwiftLibraryPluginProviderCShims PUBLIC "include") +set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS _SwiftLibraryPluginProviderCShims) +install(TARGETS _SwiftLibraryPluginProviderCShims EXPORT SwiftSyntaxTargets) diff --git a/Sources/_SwiftLibraryPluginProviderCShims/LoadLibrary.c b/Sources/_SwiftLibraryPluginProviderCShims/LoadLibrary.c new file mode 100644 index 00000000000..05dfdfe5cac --- /dev/null +++ b/Sources/_SwiftLibraryPluginProviderCShims/LoadLibrary.c @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#include "LoadLibrary.h" + +#ifdef _WIN32 + +#include +#include +#include + +void *swiftlibrarypluginprovider_LoadLibraryW(uint16_t *lpLibFileName) { + return LoadLibraryW(lpLibFileName); +} + +unsigned long swiftlibrarypluginprovider_GetLastError() { + return GetLastError(); +} + +#endif /* _WIN32 */ diff --git a/Sources/_SwiftLibraryPluginProviderCShims/include/LoadLibrary.h b/Sources/_SwiftLibraryPluginProviderCShims/include/LoadLibrary.h new file mode 100644 index 00000000000..dbc2e961b79 --- /dev/null +++ b/Sources/_SwiftLibraryPluginProviderCShims/include/LoadLibrary.h @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFT_LIBRARY_PLUGIN_PROVIDER_LOAD_LIBRARY_H +#define SWIFT_LIBRARY_PLUGIN_PROVIDER_LOAD_LIBRARY_H + +#ifdef _WIN32 + +#include + +void *swiftlibrarypluginprovider_LoadLibraryW(uint16_t *lpLibFileName); +unsigned long swiftlibrarypluginprovider_GetLastError(); + +#endif /* _WIN32 */ + +#endif /* SWIFT_LIBRARY_PLUGIN_PROVIDER_LOAD_LIBRARY_H */ diff --git a/Sources/_SwiftLibraryPluginProviderCShims/include/module.modulemap b/Sources/_SwiftLibraryPluginProviderCShims/include/module.modulemap new file mode 100644 index 00000000000..feb00a74694 --- /dev/null +++ b/Sources/_SwiftLibraryPluginProviderCShims/include/module.modulemap @@ -0,0 +1,4 @@ +module _SwiftLibraryPluginProviderCShims { + header "LoadLibrary.h" + export * +} diff --git a/Sources/_SwiftSyntaxCShims/CMakeLists.txt b/Sources/_SwiftSyntaxCShims/CMakeLists.txt new file mode 100644 index 00000000000..b85340a7456 --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/CMakeLists.txt @@ -0,0 +1,4 @@ +add_library(_SwiftSyntaxCShims INTERFACE) +target_include_directories(_SwiftSyntaxCShims INTERFACE "include") +set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS _SwiftSyntaxCShims) +install(TARGETS _SwiftSyntaxCShims EXPORT SwiftSyntaxTargets) diff --git a/Sources/_SwiftSyntaxCShims/dummy.c b/Sources/_SwiftSyntaxCShims/dummy.c new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/dummy.c @@ -0,0 +1 @@ + diff --git a/Sources/_SwiftSyntaxCShims/include/AtomicBool.h b/Sources/_SwiftSyntaxCShims/include/AtomicBool.h new file mode 100644 index 00000000000..1d456ad4943 --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/include/AtomicBool.h @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFTSYNTAX_ATOMICBOOL_H +#define SWIFTSYNTAX_ATOMICBOOL_H + +#include +#include + +typedef struct { + _Atomic(bool) value; +} AtomicBool; + +static inline AtomicBool *_Nonnull swiftsyntax_atomic_bool_create(bool initialValue) { + AtomicBool *atomic = malloc(sizeof(AtomicBool)); + atomic->value = initialValue; + return atomic; +} + +static inline bool swiftsyntax_atomic_bool_get(AtomicBool *_Nonnull atomic) { + return atomic->value; +} + +static inline void swiftsyntax_atomic_bool_set(AtomicBool *_Nonnull atomic, bool newValue) { + atomic->value = newValue; +} + +static inline void swiftsyntax_atomic_bool_destroy(AtomicBool *_Nonnull atomic) { + free(atomic); +} + +#endif // SWIFTSYNTAX_ATOMICBOOL_H diff --git a/Sources/_SwiftSyntaxCShims/include/SwiftSyntaxCShims.h b/Sources/_SwiftSyntaxCShims/include/SwiftSyntaxCShims.h new file mode 100644 index 00000000000..1db9283cdfb --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/include/SwiftSyntaxCShims.h @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#include "_includes.h" +#include "AtomicBool.h" +#include "swiftsyntax_errno.h" +#include "swiftsyntax_stdio.h" diff --git a/Sources/_SwiftSyntaxCShims/include/_includes.h b/Sources/_SwiftSyntaxCShims/include/_includes.h new file mode 100644 index 00000000000..1502181da49 --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/include/_includes.h @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file is for, instead of importing platform modules in Swift file, like: +// +// #if canImport(Darwin) +// import Darwin +// #elseif canImport(Glibc) +// import Glibc +// ... +// +// Just include them here using C facilities, so that Swift module can just: +// +// import _SwiftSyntaxCShims +// +//===----------------------------------------------------------------------===// + +#if defined(_WIN32) +// NOTE: Do NOT include "WinSDK" headers here. +// This is a part of compiler. If we use 'WinSDK' here, the compiler links with +// swiftWinSDK.dll when (re)bulding it, and fails because it's used. +#include + +#elif defined(__unix__) || defined(__APPLE__) +#include +#endif + +#include +#include +#include diff --git a/Sources/_SwiftSyntaxCShims/include/module.modulemap b/Sources/_SwiftSyntaxCShims/include/module.modulemap new file mode 100644 index 00000000000..010d951f292 --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/include/module.modulemap @@ -0,0 +1,7 @@ +module _SwiftSyntaxCShims { + header "_includes.h" + header "AtomicBool.h" + header "swiftsyntax_errno.h" + header "swiftsyntax_stdio.h" + export * +} diff --git a/Sources/_SwiftSyntaxCShims/include/swiftsyntax_errno.h b/Sources/_SwiftSyntaxCShims/include/swiftsyntax_errno.h new file mode 100644 index 00000000000..589fde7eaed --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/include/swiftsyntax_errno.h @@ -0,0 +1,23 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFTSYNTAX_ERRNO_H +#define SWIFTSYNTAX_ERRNO_H + +#include + +__attribute__((swift_name("getter:_errno()"))) +static inline int swiftsyntax_errno(void) { + return errno; +} + +#endif // SWIFTSYNTAX_ERRNO_H diff --git a/Sources/_SwiftSyntaxCShims/include/swiftsyntax_stdio.h b/Sources/_SwiftSyntaxCShims/include/swiftsyntax_stdio.h new file mode 100644 index 00000000000..a7f24c3dfee --- /dev/null +++ b/Sources/_SwiftSyntaxCShims/include/swiftsyntax_stdio.h @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFTSYNTAX_STDIO_H +#define SWIFTSYNTAX_STDIO_H + +#include + +__attribute__((swift_name("getter:_stdout()"))) +static inline FILE *swiftsyntax_stdout(void) { + return stdout; +} + +__attribute__((swift_name("getter:_stdin()"))) +static inline FILE *swiftsyntax_stdin(void) { + return stdin; +} + +__attribute__((swift_name("getter:_stderr()"))) +static inline FILE *swiftsyntax_stderr(void) { + return stderr; +} + +#endif // SWIFTSYNTAX_STDIO_H diff --git a/Sources/_SwiftSyntaxGenericTestSupport/AssertEqualWithDiff.swift b/Sources/_SwiftSyntaxGenericTestSupport/AssertEqualWithDiff.swift new file mode 100644 index 00000000000..d23a3031538 --- /dev/null +++ b/Sources/_SwiftSyntaxGenericTestSupport/AssertEqualWithDiff.swift @@ -0,0 +1,135 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +/// Defines the location at which the a test failure should be anchored. This is typically the location where the +/// assertion function is called. +public struct TestFailureLocation { + public let fileID: StaticString + public let filePath: StaticString + public let line: UInt + public let column: UInt + + public init( + fileID: StaticString, + filePath: StaticString, + line: UInt, + column: UInt + ) { + self.fileID = fileID + self.filePath = filePath + self.line = line + self.column = column + } +} + +/// Defines the details of a test failure, consisting of a message and the location at which the test failure should be +/// shown. +public struct TestFailureSpec { + public let message: String + public let location: TestFailureLocation +} + +/// Asserts that the two strings are equal, providing Unix `diff`-style output if they are not. +/// +/// - Parameters: +/// - actual: The actual string. +/// - expected: The expected string. +/// - message: An optional description of the failure. +/// - additionalInfo: Additional information about the failed test case that will be printed after the diff +/// - file: The file in which failure occurred. Defaults to the file name of the test case in +/// which this function was called. +/// - line: The line number on which failure occurred. Defaults to the line number on which this +/// function was called. +public func assertStringsEqualWithDiff( + _ actual: String, + _ expected: String, + _ message: String = "", + additionalInfo: @autoclosure () -> String? = nil, + location: TestFailureLocation, + failureHandler: (TestFailureSpec) -> Void +) { + if actual == expected { + return + } + failStringsEqualWithDiff( + actual, + expected, + message, + additionalInfo: additionalInfo(), + location: location, + failureHandler: failureHandler + ) +} + +/// `XCTFail` with `diff`-style output. +public func failStringsEqualWithDiff( + _ actual: String, + _ expected: String, + _ message: String = "", + additionalInfo: @autoclosure () -> String? = nil, + location: TestFailureLocation, + failureHandler: (TestFailureSpec) -> Void +) { + let stringComparison: String + + // Use `CollectionDifference` on supported platforms to get `diff`-like line-based output. On + // older platforms, fall back to simple string comparison. + let actualLines = actual.split(separator: "\n") + let expectedLines = expected.split(separator: "\n") + + let difference = actualLines.difference(from: expectedLines) + + var result = "" + + var insertions = [Int: Substring]() + var removals = [Int: Substring]() + + for change in difference { + switch change { + case .insert(let offset, let element, _): + insertions[offset] = element + case .remove(let offset, let element, _): + removals[offset] = element + } + } + + var expectedLine = 0 + var actualLine = 0 + + while expectedLine < expectedLines.count || actualLine < actualLines.count { + if let removal = removals[expectedLine] { + result += "–\(removal)\n" + expectedLine += 1 + } else if let insertion = insertions[actualLine] { + result += "+\(insertion)\n" + actualLine += 1 + } else { + result += " \(expectedLines[expectedLine])\n" + expectedLine += 1 + actualLine += 1 + } + } + + stringComparison = result + + var fullMessage = """ + \(message.isEmpty ? "Actual output does not match the expected" : message) + \(stringComparison) + """ + if let additional = additionalInfo() { + fullMessage = """ + \(fullMessage) + \(additional) + """ + } + failureHandler(TestFailureSpec(message: fullMessage, location: location)) +} diff --git a/Sources/_AtomicBool/src/SwiftSyntaxAtomicBool.c b/Sources/_SwiftSyntaxGenericTestSupport/String+TrimmingTrailingWhitespace.swift similarity index 55% rename from Sources/_AtomicBool/src/SwiftSyntaxAtomicBool.c rename to Sources/_SwiftSyntaxGenericTestSupport/String+TrimmingTrailingWhitespace.swift index 7d1e0d93667..2134b5632c5 100644 --- a/Sources/_AtomicBool/src/SwiftSyntaxAtomicBool.c +++ b/Sources/_SwiftSyntaxGenericTestSupport/String+TrimmingTrailingWhitespace.swift @@ -10,18 +10,18 @@ // //===----------------------------------------------------------------------===// -#include "SwiftSyntaxAtomicBool.h" - -AtomicBool atomic_bool_create(bool initialValue) { - AtomicBool atomic; - atomic.value = initialValue; - return atomic; -} - -bool atomic_bool_get(AtomicBool *atomic) { - return atomic->value; +extension String { + public func trimmingTrailingWhitespace() -> String { + return + self + .split(separator: "\n", omittingEmptySubsequences: false) + .map { $0.droppingLast(while: \.isWhitespace) } + .joined(separator: "\n") + } } -void atomic_bool_set(AtomicBool *atomic, bool newValue) { - atomic->value = newValue; +public extension StringProtocol { + func droppingLast(while predicate: (Character) -> Bool) -> String { + return String(self.reversed().drop(while: predicate).reversed()) + } } diff --git a/Sources/_SwiftSyntaxTestSupport/AssertEqualWithDiff.swift b/Sources/_SwiftSyntaxTestSupport/AssertEqualWithDiff.swift index 6fb8244b8b7..99f451a555a 100644 --- a/Sources/_SwiftSyntaxTestSupport/AssertEqualWithDiff.swift +++ b/Sources/_SwiftSyntaxTestSupport/AssertEqualWithDiff.swift @@ -13,9 +13,11 @@ #if swift(>=6) public import Foundation private import XCTest +private import _SwiftSyntaxGenericTestSupport #else import Foundation import XCTest +import _SwiftSyntaxGenericTestSupport #endif /// Asserts that the two strings are equal, providing Unix `diff`-style output if they are not. @@ -37,16 +39,21 @@ public func assertStringsEqualWithDiff( file: StaticString = #filePath, line: UInt = #line ) { - if actual == expected { - return - } - failStringsEqualWithDiff( + let location = TestFailureLocation( + fileID: "", // Not used in the failure handler + filePath: file, + line: line, + column: 0 // Not used in the failure handler + ) + return _SwiftSyntaxGenericTestSupport.assertStringsEqualWithDiff( actual, expected, message, additionalInfo: additionalInfo(), - file: file, - line: line + location: location, + failureHandler: { + XCTFail($0.message, file: $0.location.filePath, line: $0.location.line) + } ) } @@ -73,89 +80,19 @@ public func assertDataEqualWithDiff( return } - // NOTE: Converting to `Stirng` here looses invalid UTF8 sequence difference, - // but at least we can see something is different. - failStringsEqualWithDiff( - String(decoding: actual, as: UTF8.self), - String(decoding: expected, as: UTF8.self), + let actualString = String(decoding: actual, as: UTF8.self) + let expectedString = String(decoding: expected, as: UTF8.self) + + if actualString == expectedString { + XCTFail("Actual differs from expected data but underlying strings are equivalent", file: file, line: line) + } + + assertStringsEqualWithDiff( + actualString, + expectedString, message, additionalInfo: additionalInfo(), file: file, line: line ) } - -/// `XCTFail` with `diff`-style output. -public func failStringsEqualWithDiff( - _ actual: String, - _ expected: String, - _ message: String = "", - additionalInfo: @autoclosure () -> String? = nil, - file: StaticString = #filePath, - line: UInt = #line -) { - let stringComparison: String - - // Use `CollectionDifference` on supported platforms to get `diff`-like line-based output. On - // older platforms, fall back to simple string comparison. - if #available(macOS 10.15, *) { - let actualLines = actual.components(separatedBy: .newlines) - let expectedLines = expected.components(separatedBy: .newlines) - - let difference = actualLines.difference(from: expectedLines) - - var result = "" - - var insertions = [Int: String]() - var removals = [Int: String]() - - for change in difference { - switch change { - case .insert(let offset, let element, _): - insertions[offset] = element - case .remove(let offset, let element, _): - removals[offset] = element - } - } - - var expectedLine = 0 - var actualLine = 0 - - while expectedLine < expectedLines.count || actualLine < actualLines.count { - if let removal = removals[expectedLine] { - result += "–\(removal)\n" - expectedLine += 1 - } else if let insertion = insertions[actualLine] { - result += "+\(insertion)\n" - actualLine += 1 - } else { - result += " \(expectedLines[expectedLine])\n" - expectedLine += 1 - actualLine += 1 - } - } - - stringComparison = result - } else { - // Fall back to simple message on platforms that don't support CollectionDifference. - stringComparison = """ - Expected: - \(expected) - - Actual: - \(actual) - """ - } - - var fullMessage = """ - \(message.isEmpty ? "Actual output does not match the expected" : message) - \(stringComparison) - """ - if let additional = additionalInfo() { - fullMessage = """ - \(fullMessage) - \(additional) - """ - } - XCTFail(fullMessage, file: file, line: line) -} 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/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..29fcd33b741 100644 --- a/Sources/_SwiftSyntaxTestSupport/SyntaxComparison.swift +++ b/Sources/_SwiftSyntaxTestSupport/SyntaxComparison.swift @@ -90,10 +90,10 @@ extension TreeDifference: CustomDebugStringConvertible { } } -public extension SyntaxProtocol { +extension SyntaxProtocol { /// Compares the current tree against a `baseline`, returning the first /// difference it finds. - func findFirstDifference(baseline: some SyntaxProtocol, includeTrivia: Bool = false) -> TreeDifference? { + public func findFirstDifference(baseline: some SyntaxProtocol, includeTrivia: Bool = false) -> TreeDifference? { if let reason = isDifferent(baseline: baseline, includeTrivia: includeTrivia) { return TreeDifference(node: self, baseline: baseline, reason: reason) } @@ -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..670d90c8eac 100644 --- a/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift +++ b/Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift @@ -11,10 +11,10 @@ //===----------------------------------------------------------------------===// #if swift(>=6) -import SwiftBasicFormat -@_spi(Testing) import SwiftParser +internal import SwiftBasicFormat +@_spi(Testing) internal import SwiftParser @_spi(RawSyntax) public import SwiftSyntax -import SwiftSyntaxBuilder +internal import SwiftSyntaxBuilder #else import SwiftBasicFormat @_spi(Testing) import SwiftParser @@ -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/commands/VerifySourceCode.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift index 7fe30eb8c6e..5f339341ae0 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/VerifySourceCode.swift @@ -129,6 +129,7 @@ struct VerifySpiYmlExecutor { .components(separatedBy: "\n") .filter({ !$0.matches(of: extractNameRegex).isEmpty }) .map { $0.replacing(extractNameRegex) { $0.1 } } + .filter({ !$0.hasPrefix("_") }) .sorted() } /// Returns all targets listed in `.spi.yml`. diff --git a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift index 907d24dc033..36d6d198cc6 100644 --- a/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift +++ b/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Paths.swift @@ -14,7 +14,7 @@ import Foundation enum Paths { static var packageDir: URL { - URL(fileURLWithPath: #file) + URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .deletingLastPathComponent() .deletingLastPathComponent() 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..250addfc71e 100644 --- a/Tests/PerformanceTest/InstructionsCountAssertion.swift +++ b/Tests/PerformanceTest/InstructionsCountAssertion.swift @@ -17,13 +17,18 @@ fileprivate var baselineURL: URL { if let baselineFile = ProcessInfo.processInfo.environment["BASELINE_FILE"] { return URL(fileURLWithPath: baselineFile) } else { - return URL(fileURLWithPath: #file) + return URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .appendingPathComponent("baselines.json") } } -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/PerformanceTest/ParsingPerformanceTests.swift b/Tests/PerformanceTest/ParsingPerformanceTests.swift index 45a469828a1..714ad0cfb6d 100644 --- a/Tests/PerformanceTest/ParsingPerformanceTests.swift +++ b/Tests/PerformanceTest/ParsingPerformanceTests.swift @@ -18,7 +18,7 @@ import _SwiftSyntaxTestSupport class ParsingPerformanceTests: XCTestCase { var inputFile: URL { - return URL(fileURLWithPath: #file) + return URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .appendingPathComponent("Inputs") .appendingPathComponent("MinimalCollections.swift.input") @@ -27,7 +27,7 @@ class ParsingPerformanceTests: XCTestCase { func testNativeParsingPerformance() throws { try XCTSkipIf(longTestsDisabled) - let source = try String(contentsOf: inputFile) + let source = try String(contentsOf: inputFile, encoding: .utf8) try measureInstructions { _ = Parser.parse(source: source) diff --git a/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift b/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift index 78a1237de06..6be46deef1c 100644 --- a/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift +++ b/Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift @@ -19,7 +19,7 @@ import _SwiftSyntaxTestSupport class SyntaxClassifierPerformanceTests: XCTestCase { var inputFile: URL { - return URL(fileURLWithPath: #file) + return URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .appendingPathComponent("Inputs") .appendingPathComponent("MinimalCollections.swift.input") @@ -28,7 +28,7 @@ class SyntaxClassifierPerformanceTests: XCTestCase { func testClassifierPerformance() throws { try XCTSkipIf(longTestsDisabled) - let source = try String(contentsOf: inputFile) + let source = try String(contentsOf: inputFile, encoding: .utf8) let parsed = Parser.parse(source: source) try measureInstructions { diff --git a/Tests/PerformanceTest/VisitorPerformanceTests.swift b/Tests/PerformanceTest/VisitorPerformanceTests.swift index 6dfbde5303f..659c27dad55 100644 --- a/Tests/PerformanceTest/VisitorPerformanceTests.swift +++ b/Tests/PerformanceTest/VisitorPerformanceTests.swift @@ -18,7 +18,7 @@ import _SwiftSyntaxTestSupport class VisitorPerformanceTests: XCTestCase { var inputFile: URL { - return URL(fileURLWithPath: #file) + return URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .appendingPathComponent("Inputs") .appendingPathComponent("MinimalCollections.swift.input") @@ -28,7 +28,7 @@ class VisitorPerformanceTests: XCTestCase { try XCTSkipIf(longTestsDisabled) class EmptyVisitor: SyntaxVisitor {} - let source = try String(contentsOf: inputFile) + let source = try String(contentsOf: inputFile, encoding: .utf8) let parsed = Parser.parse(source: source) let emptyVisitor = EmptyVisitor(viewMode: .sourceAccurate) @@ -41,7 +41,7 @@ class VisitorPerformanceTests: XCTestCase { try XCTSkipIf(longTestsDisabled) class EmptyRewriter: SyntaxRewriter {} - let source = try String(contentsOf: inputFile) + let source = try String(contentsOf: inputFile, encoding: .utf8) let parsed = Parser.parse(source: source) let emptyRewriter = EmptyRewriter(viewMode: .sourceAccurate) @@ -54,7 +54,7 @@ class VisitorPerformanceTests: XCTestCase { try XCTSkipIf(longTestsDisabled) class EmptyAnyVisitor: SyntaxAnyVisitor {} - let source = try String(contentsOf: inputFile) + let source = try String(contentsOf: inputFile, encoding: .utf8) let parsed = Parser.parse(source: source) let emptyVisitor = EmptyAnyVisitor(viewMode: .sourceAccurate) diff --git a/Tests/SwiftBasicFormatTest/BasicFormatTests.swift b/Tests/SwiftBasicFormatTest/BasicFormatTests.swift index 980181fea21..801c5e5e7ff 100644 --- a/Tests/SwiftBasicFormatTest/BasicFormatTests.swift +++ b/Tests/SwiftBasicFormatTest/BasicFormatTests.swift @@ -43,6 +43,15 @@ fileprivate func assertFormatted( ) } +fileprivate func assertFormattingRoundTrips( + _ source: String, + using format: BasicFormat = BasicFormat(indentationWidth: .spaces(4)), + file: StaticString = #filePath, + line: UInt = #line +) { + assertFormatted(source: source, expected: source, using: format, file: file, line: line) +} + final class BasicFormatTest: XCTestCase { func testNotIndented() { assertFormatted( @@ -100,26 +109,26 @@ final class BasicFormatTest: XCTestCase { } func testAlreadyIndented() { - let source = """ + assertFormattingRoundTrips( + """ func foo() { someFunc(a: 1, b: 1) } """ - - assertFormatted(source: source, expected: source) + ) } func testAlreadyIndentedWithComment() { - let source = """ + assertFormattingRoundTrips( + """ func foo() { // ABC someFunc(a: 1, b: 1) } """ - - assertFormatted(source: source, expected: source) + ) } func testAlreadyIndentedWithComment2() { @@ -278,7 +287,8 @@ final class BasicFormatTest: XCTestCase { } func testMultilineStringLiteralWithBlankLines() { - let source = #""" + assertFormattingRoundTrips( + #""" assertionFailure(""" First line @@ -287,20 +297,22 @@ final class BasicFormatTest: XCTestCase { """) """# - assertFormatted(source: source, expected: source) + ) } func testMultilineStringLiteralWithFirstLineBlank() { - let source = #""" + assertFormattingRoundTrips( + #""" assertionFailure(""" """) """# - assertFormatted(source: source, expected: source) + ) } func testNestedMultilineStringLiterals() { - let source = #""" + assertFormattingRoundTrips( + #""" assertionFailure(""" \(""" @@ -308,8 +320,7 @@ final class BasicFormatTest: XCTestCase { """) """) """# - - assertFormatted(source: source, expected: source) + ) } func testIndentNestedMultilineStringLiterals() throws { @@ -375,7 +386,8 @@ final class BasicFormatTest: XCTestCase { } func testClosureInStringInterpolation() { - let source = #""" + assertFormattingRoundTrips( + #""" """ \(gen { (x) in return """ @@ -384,8 +396,7 @@ final class BasicFormatTest: XCTestCase { }) """ """# - - assertFormatted(source: source, expected: source) + ) } func testNestedUserDefinedIndentation() { @@ -540,31 +551,27 @@ final class BasicFormatTest: XCTestCase { } func testPeriodAfterStringLiteral() { - let source = """ + assertFormattingRoundTrips( + """ "test".lowercased() """ - assertFormatted(source: source, expected: source) + ) } func testPeriodAfterRawStringLiteral() { - let source = """ + assertFormattingRoundTrips( + """ #"test"#.lowercased() """ - assertFormatted(source: source, expected: source) + ) } func testPeriodAfterRegexLiteral() { - let source = """ - /test/.something - """ - assertFormatted(source: source, expected: source) + assertFormattingRoundTrips("/test/.something") } func testPeriodAfterRawRegexLiteral() { - let source = """ - /test/.something - """ - assertFormatted(source: source, expected: source) + assertFormattingRoundTrips("/test/.something") } func testNewlineInTrailingTriviaAtEndOfIndentationScope() throws { @@ -627,22 +634,65 @@ final class BasicFormatTest: XCTestCase { } func testIndentedStandaloneClosureRoundTrips() throws { - let source = """ + assertFormattingRoundTrips( + """ foo { "abc" } """ - assertFormatted(source: source, expected: source) + ) } func testIndentedStandaloneClosureRoundTrips2() throws { - let source = """ + assertFormattingRoundTrips( + """ foo { if true { print("test") } } """ - assertFormatted(source: source, expected: source) + ) + } + + func testPrivateSetVar() { + assertFormattingRoundTrips("private(set) var x = 1") + + assertFormattingRoundTrips("internal(set) var x = 1") + } + + func testSpiAttribute() { + assertFormattingRoundTrips( + """ + @_spi(MySPI) struct Foo { + } + """ + ) + } + + func testTypedThrows() { + assertFormattingRoundTrips( + """ + func foo() throws(MyError) { + } + """ + ) + } + + func testClosureParameterClause() { + assertFormatted( + source: "{(x: Int) in}", + expected: """ + { (x: Int) in + } + """ + ) + } + + func testFunctionType() { + assertFormatted( + source: "let x:(Int)->Void", + expected: "let x: (Int) -> Void" + ) } } diff --git a/Tests/SwiftCompilerPluginTest/JSONTests.swift b/Tests/SwiftCompilerPluginTest/JSONTests.swift new file mode 100644 index 00000000000..2018d831662 --- /dev/null +++ b/Tests/SwiftCompilerPluginTest/JSONTests.swift @@ -0,0 +1,317 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +@_spi(PluginMessage) import SwiftCompilerPluginMessageHandling +import XCTest + +final class JSONTests: XCTestCase { + + func testPrimitive() { + assertRoundTrip(of: true, expectedJSON: "true") + assertRoundTrip(of: false, expectedJSON: "false") + assertRoundTrip(of: Bool?.none, expectedJSON: "null") + assertRoundTrip(of: "", expectedJSON: "\"\"") + assertRoundTrip(of: 0, expectedJSON: "0") + assertRoundTrip(of: 0 as Int8, expectedJSON: "0") + assertRoundTrip(of: 0.0 as Float, expectedJSON: "0.0") + assertRoundTrip(of: 0.0 as Double, expectedJSON: "0.0") + } + + func testEmptyStruct() { + let value = EmptyStruct() + assertRoundTrip(of: value, expectedJSON: "{}") + } + + func testEmptyClass() { + let value = EmptyClass() + assertRoundTrip(of: value, expectedJSON: "{}") + } + + func testTrivialEnumDefault() { + assertRoundTrip(of: Direction.left, expectedJSON: #"{"left":{}}"#) + assertRoundTrip(of: Direction.right, expectedJSON: #"{"right":{}}"#) + } + + func testTrivialEnumRawValue() { + assertRoundTrip(of: Animal.dog, expectedJSON: #""dog""#) + assertRoundTrip(of: Animal.cat, expectedJSON: #""cat""#) + } + + func testTrivialEnumCustom() { + assertRoundTrip(of: Switch.off, expectedJSON: "false") + assertRoundTrip(of: Switch.on, expectedJSON: "true") + } + + func testEnumWithAssociated() { + let tree: Tree = .dictionary([ + "name": .string("John Doe"), + "data": .array([.int(12), .string("foo")]), + ]) + assertRoundTrip( + of: tree, + expectedJSON: #""" + {"dictionary":{"_0":{"data":{"array":{"_0":[{"int":{"_0":12}},{"string":{"_0":"foo"}}]}},"name":{"string":{"_0":"John Doe"}}}}} + """# + ) + } + + func testArrayOfInt() { + let arr: [Int] = [12, 42] + assertRoundTrip(of: arr, expectedJSON: "[12,42]") + let empty: [Int] = [] + assertRoundTrip(of: empty, expectedJSON: "[]") + } + + func testComplexStruct() { + let empty = ComplexStruct(result: nil, diagnostics: [], elapsed: 0.0) + assertRoundTrip(of: empty, expectedJSON: #"{"diagnostics":[],"elapsed":0.0}"#) + + let value = ComplexStruct( + result: "\tresult\nfoo", + diagnostics: [ + .init( + message: "error 🛑", + animal: .cat, + data: [nil, 42] + ) + ], + elapsed: 42.3e32 + ) + assertRoundTrip( + of: value, + expectedJSON: #""" + {"diagnostics":[{"animal":"cat","data":[null,42],"message":"error 🛑"}],"elapsed":4.23e+33,"result":"\tresult\nfoo"} + """# + ) + } + + func testEscapedString() { + assertRoundTrip( + of: "\n\"\\\u{A9}\u{0}\u{07}\u{1B}", + expectedJSON: #""" + "\n\"\\©\u0000\u0007\u001B" + """# + ) + } + + func testParseError() { + assertParseError( + #"{"foo": 1"#, + message: "unexpected end of file" + ) + assertParseError( + #""foo"#, + message: "unexpected end of file" + ) + assertParseError( + "\n", + message: "unexpected end of file" + ) + assertParseError( + "trua", + message: "unexpected character 'a'; expected 'e'" + ) + assertParseError( + "[true, #foo]", + message: "unexpected character '#'; value start" + ) + assertParseError( + "{}true", + message: "unexpected character 't'; after top-level value" + ) + } + + func testInvalidStringDecoding() { + assertInvalidStrng(#""foo\"#) // EOF after '\' + assertInvalidStrng(#""\x""#) // Unknown character after '\' + assertInvalidStrng(#""\u1""#) // Missing 4 digits after '\u' + assertInvalidStrng(#""\u12""#) + assertInvalidStrng(#""\u123""#) + assertInvalidStrng(#""\uEFGH""#) // Invalid HEX characters. + } + + func testStringSurrogatePairDecoding() { + // FIXME: Escaped surrogate pairs are not supported. + // Currently parsed as "invalid", but this should be valid '𐐷' (U+10437) character + assertInvalidStrng(#"\uD801\uDC37"#) + } + + func testTypeCoercion() { + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [UInt].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [UInt8].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [UInt16].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [UInt32].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [UInt64].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Float].self) + assertRoundTripTypeCoercionFailure(of: [false, true], as: [Double].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [Int], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [Int8], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [Int16], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [Int32], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [Int64], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [UInt], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [UInt8], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [UInt16], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [UInt32], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0, 1] as [UInt64], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Float], as: [Bool].self) + assertRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Double], as: [Bool].self) + } + + func testFloatingPointBufferBoundary() throws { + // Make sure floating point parsing does not read past the decoding JSON buffer. + var str = "0.199" + try str.withUTF8 { buf in + let truncated = UnsafeBufferPointer(rebasing: buf[0..<3]) + XCTAssertEqual(try JSON.decode(Double.self, from: truncated), 0.1) + XCTAssertEqual(try JSON.decode(Float.self, from: truncated), 0.1) + } + } + + private func assertRoundTrip( + of value: T, + expectedJSON: String, + file: StaticString = #filePath, + line: UInt = #line + ) { + let payload: [UInt8] + do { + payload = try JSON.encode(value) + } catch let error { + XCTFail("Failed to encode \(T.self) to JSON: \(error)", file: file, line: line) + return + } + + let jsonStr = String(decoding: payload, as: UTF8.self) + XCTAssertEqual(jsonStr, expectedJSON, file: file, line: line) + + let decoded: T + do { + decoded = try payload.withUnsafeBufferPointer { + try JSON.decode(T.self, from: $0) + } + } catch let error { + XCTFail("Failed to decode \(T.self) from JSON: \(error)", file: file, line: line) + return + } + XCTAssertEqual(value, decoded, file: file, line: line) + } + + private func assertRoundTripTypeCoercionFailure( + of value: T, + as type: U.Type, + file: StaticString = #filePath, + line: UInt = #line + ) { + do { + let data = try JSONEncoder().encode(value) + let _ = try JSONDecoder().decode(U.self, from: data) + XCTFail("Coercion from \(T.self) to \(U.self) was expected to fail.", file: file, line: line) + } catch DecodingError.typeMismatch(_, _) { + // Success + } catch { + XCTFail("unexpected error", file: file, line: line) + } + } + + private func assertInvalidStrng(_ json: String, file: StaticString = #filePath, line: UInt = #line) { + do { + var json = json + _ = try json.withUTF8 { try JSON.decode(String.self, from: $0) } + XCTFail("decoding should fail", file: file, line: line) + } catch {} + } + + private func assertParseError(_ json: String, message: String, file: StaticString = #filePath, line: UInt = #line) { + do { + var json = json + _ = try json.withUTF8 { try JSON.decode(Bool.self, from: $0) } + XCTFail("decoding should fail", file: file, line: line) + } catch DecodingError.dataCorrupted(let context) { + XCTAssertEqual( + String(describing: try XCTUnwrap(context.underlyingError, file: file, line: line)), + message + ) + } catch { + XCTFail("unexpected error", file: file, line: line) + } + } +} + +// MARK: - Test Types + +fileprivate struct EmptyStruct: Codable, Equatable { + static func == (_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool { + return true + } +} + +fileprivate class EmptyClass: Codable, Equatable { + static func == (_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool { + return true + } +} + +fileprivate enum Direction: Codable { + case right + case left +} + +fileprivate enum Animal: String, Codable { + case dog + case cat +} + +fileprivate enum Switch: Codable { + case off + case on + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + switch try container.decode(Bool.self) { + case false: self = .off + case true: self = .on + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .off: try container.encode(false) + case .on: try container.encode(true) + } + } +} + +fileprivate enum Tree: Codable, Equatable { + indirect case int(Int) + indirect case string(String) + indirect case array([Self]) + indirect case dictionary([String: Self]) +} + +fileprivate struct ComplexStruct: Codable, Equatable { + struct Diagnostic: Codable, Equatable { + var message: String + var animal: Animal + var data: [Int?] + } + + var result: String? + var diagnostics: [Diagnostic] + var elapsed: Double +} diff --git a/Tests/SwiftCompilerPluginTest/LRUCacheTests.swift b/Tests/SwiftCompilerPluginTest/LRUCacheTests.swift new file mode 100644 index 00000000000..4192812dee7 --- /dev/null +++ b/Tests/SwiftCompilerPluginTest/LRUCacheTests.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +@_spi(Testing) import SwiftCompilerPluginMessageHandling +import XCTest + +final class LRUCacheTests: XCTestCase { + func testBasic() { + let cache = LRUCache(capacity: 2) + cache["foo"] = 0 + cache["bar"] = 1 + XCTAssertEqual(cache["foo"], 0) + cache["baz"] = 2 + XCTAssertEqual(cache["foo"], 0) + XCTAssertEqual(cache["bar"], nil) + XCTAssertEqual(cache["baz"], 2) + XCTAssertEqual(cache.count, 2) + + cache["qux"] = nil + cache["baz"] = nil + cache["foo"] = 10 + XCTAssertEqual(cache["foo"], 10) + XCTAssertEqual(cache["bar"], nil) + XCTAssertEqual(cache["baz"], nil) + XCTAssertEqual(cache["qux"], nil) + XCTAssertEqual(cache.count, 1) + } +} diff --git a/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift b/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift index 76ba6fef82a..ec95397f9b4 100644 --- a/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift +++ b/Tests/SwiftDiagnosticsTest/GroupDiagnosticsFormatterTests.swift @@ -77,9 +77,9 @@ final class GroupedDiagnosticsFormatterTests: XCTestCase { annotated, """ other.swift:123:17: error: consecutive statements on a line must be separated by newline or ';' - 1 │ #sourceLocation(file: "other.swift", line: 123) - 2 │ let pi = 3.14159 x - │ ╰─ error: consecutive statements on a line must be separated by newline or ';' + 1 | #sourceLocation(file: "other.swift", line: 123) + 2 | let pi = 3.14159 x + | `- error: consecutive statements on a line must be separated by newline or ';' """ ) @@ -134,20 +134,20 @@ final class GroupedDiagnosticsFormatterTests: XCTestCase { annotated, """ main.swift:6:14: error: expected ')' to end function call - 3 │ // test - 4 │ let pi = 3.14159 - 5 │ #myAssert(pi == 3) - │ ╰─ note: in expansion of macro 'myAssert' here - ╭─── #myAssert ─────────────────────────────────────────────────────── - │1 │ let __a = pi - │2 │ let __b = 3 - │3 │ if !(__a == __b) { - │ │ ╰─ error: no matching operator '==' for types 'Double' and 'Int' - │4 │ fatalError("assertion failed: pi != 3") - │5 │ } - ╰───────────────────────────────────────────────────────────────────── - 6 │ print("hello" - │ ╰─ error: expected ')' to end function call + 3 | // test + 4 | let pi = 3.14159 + 5 | #myAssert(pi == 3) + | `- note: in expansion of macro 'myAssert' here + +--- #myAssert ------------------------------------------------------- + |1 | let __a = pi + |2 | let __b = 3 + |3 | if !(__a == __b) { + | | `- error: no matching operator '==' for types 'Double' and 'Int' + |4 | fatalError("assertion failed: pi != 3") + |5 | } + +--------------------------------------------------------------------- + 6 | print("hello" + | `- error: expected ')' to end function call """ ) @@ -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 + ) ] ) @@ -204,23 +212,23 @@ final class GroupedDiagnosticsFormatterTests: XCTestCase { annotated, """ #invertedEqualityCheck:1:7: error: no matching operator '==' for types 'Double' and 'Int' - ╰─ main.swift:2:1: note: expanded code originates here - 1 │ let pi = 3.14159 - 2 │ #myAssert(pi == 3) - │ ╰─ note: in expansion of macro 'myAssert' here - ╭─── #myAssert ─────────────────────────────────────────────────────── - │1 │ let __a = pi - │2 │ let __b = 3 - │3 │ if #invertedEqualityCheck(__a, __b) { - │ │ ╰─ note: in expansion of macro 'invertedEqualityCheck' here - │ ╭─── #invertedEqualityCheck ─────────────────────────────────────── - │ │1 │ !(__a == __b) - │ │ │ ╰─ error: no matching operator '==' for types 'Double' and 'Int' - │ ╰────────────────────────────────────────────────────────────────── - │4 │ fatalError("assertion failed: pi != 3") - │5 │ } - ╰───────────────────────────────────────────────────────────────────── - 3 │ print("hello") + `- main.swift:2:1: note: expanded code originates here + 1 | let pi = 3.14159 + 2 | #myAssert(pi == 3) + | `- note: in expansion of macro 'myAssert' here + +--- #myAssert ------------------------------------------------------- + |1 | let __a = pi + |2 | let __b = 3 + |3 | if #invertedEqualityCheck(__a, __b) { + | | `- note: in expansion of macro 'invertedEqualityCheck' here + | +--- #invertedEqualityCheck --------------------------------------- + | |1 | !(__a == __b) + | | | `- error: no matching operator '==' for types 'Double' and 'Int' + | +------------------------------------------------------------------ + |4 | fatalError("assertion failed: pi != 3") + |5 | } + +--------------------------------------------------------------------- + 3 | print("hello") """ ) diff --git a/Tests/SwiftDiagnosticsTest/ParserDiagnosticsFormatterIntegrationTests.swift b/Tests/SwiftDiagnosticsTest/ParserDiagnosticsFormatterIntegrationTests.swift index bd373df4150..5f717422309 100644 --- a/Tests/SwiftDiagnosticsTest/ParserDiagnosticsFormatterIntegrationTests.swift +++ b/Tests/SwiftDiagnosticsTest/ParserDiagnosticsFormatterIntegrationTests.swift @@ -29,8 +29,8 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { var foo = bar + """ let expectedOutput = """ - 1 │ var foo = bar + - │ ╰─ error: expected expression after operator + 1 | var foo = bar + + | `- error: expected expression after operator """ assertStringsEqualWithDiff(annotate(source: source), expectedOutput) @@ -41,10 +41,10 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { foo.[].[].[] """ let expectedOutput = """ - 1 │ foo.[].[].[] - │ │ │ ╰─ error: expected name in member access - │ │ ╰─ error: expected name in member access - │ ╰─ error: expected name in member access + 1 | foo.[].[].[] + | | | `- error: expected name in member access + | | `- error: expected name in member access + | `- error: expected name in member access """ assertStringsEqualWithDiff(annotate(source: source), expectedOutput) @@ -65,17 +65,17 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { i = bar( """ let expectedOutput = """ - 2 │ i = 2 - 3 │ i = foo( - 4 │ i = 4 - │ ╰─ error: expected ')' to end function call - 5 │ i = 5 - 6 │ i = 6 - ┆ - 9 │ i = 9 - 10 │ i = 10 - 11 │ i = bar( - │ ╰─ error: expected value and ')' to end function call + 2 | i = 2 + 3 | i = foo( + 4 | i = 4 + | `- error: expected ')' to end function call + 5 | i = 5 + 6 | i = 6 + : + 9 | i = 9 + 10 | i = 10 + 11 | i = bar( + | `- error: expected value and ')' to end function call """ assertStringsEqualWithDiff(annotate(source: source), expectedOutput) @@ -85,9 +85,9 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { let source = "t as (..)" let expectedOutput = """ - 1 │ t as (..) - │ ├─ error: expected type in tuple type - │ ╰─ error: unexpected code '..' in tuple type + 1 | t as (..) + | |- error: expected type in tuple type + | `- error: unexpected code '..' in tuple type """ @@ -100,8 +100,8 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { """ let expectedOutput = """ - \u{001B}[0;36m1 │\u{001B}[0;0m var foo = bar + - \u{001B}[0;36m│\u{001B}[0;0m ╰─ \u{001B}[1;31merror: \u{001B}[1;39mexpected expression after operator\u{001B}[0;0m + \u{001B}[0;36m1 |\u{001B}[0;0m var foo = bar + + \u{001B}[0;36m|\u{001B}[0;0m `- \u{001B}[1;31merror: \u{001B}[1;39mexpected expression after operator\u{001B}[0;0m """ assertStringsEqualWithDiff(annotate(source: source, colorize: true), expectedOutput) @@ -112,10 +112,10 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { foo.[].[].[] """ let expectedOutput = """ - \u{001B}[0;36m1 │\u{001B}[0;0m foo.[].[].[] - \u{001B}[0;36m│\u{001B}[0;0m │ │ ╰─ \u{001B}[1;31merror: \u{001B}[1;39mexpected name in member access\u{001B}[0;0m - \u{001B}[0;36m│\u{001B}[0;0m │ ╰─ \u{001B}[1;31merror: \u{001B}[1;39mexpected name in member access\u{001B}[0;0m - \u{001B}[0;36m│\u{001B}[0;0m ╰─ \u{001B}[1;31merror: \u{001B}[1;39mexpected name in member access\u{001B}[0;0m + \u{001B}[0;36m1 |\u{001B}[0;0m foo.[].[].[] + \u{001B}[0;36m|\u{001B}[0;0m | | `- \u{001B}[1;31merror: \u{001B}[1;39mexpected name in member access\u{001B}[0;0m + \u{001B}[0;36m|\u{001B}[0;0m | `- \u{001B}[1;31merror: \u{001B}[1;39mexpected name in member access\u{001B}[0;0m + \u{001B}[0;36m|\u{001B}[0;0m `- \u{001B}[1;31merror: \u{001B}[1;39mexpected name in member access\u{001B}[0;0m """ assertStringsEqualWithDiff(annotate(source: source, colorize: true), expectedOutput) @@ -127,9 +127,9 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { """ let expectedOutput = """ - \u{001B}[0;36m1 │\u{001B}[0;0m for \u{001B}[4;39m(i\u{001B}[0;0m \u{001B}[4;39m= 🐮; i != 👩‍👩‍👦‍👦; i += 1)\u{001B}[0;0m { } - \u{001B}[0;36m│\u{001B}[0;0m │ ╰─ \u{001B}[1;31merror: \u{001B}[1;39mexpected ')' to end tuple pattern\u{001B}[0;0m - \u{001B}[0;36m│\u{001B}[0;0m ╰─ \u{001B}[1;31merror: \u{001B}[1;39mC-style for statement has been removed in Swift 3\u{001B}[0;0m + \u{001B}[0;36m1 |\u{001B}[0;0m for \u{001B}[4;39m(i\u{001B}[0;0m \u{001B}[4;39m= 🐮; i != 👩‍👩‍👦‍👦; i += 1)\u{001B}[0;0m { } + \u{001B}[0;36m|\u{001B}[0;0m | `- \u{001B}[1;31merror: \u{001B}[1;39mexpected ')' to end tuple pattern\u{001B}[0;0m + \u{001B}[0;36m|\u{001B}[0;0m `- \u{001B}[1;31merror: \u{001B}[1;39mC-style for statement has been removed in Swift 3\u{001B}[0;0m """ @@ -142,9 +142,9 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { """ let expectedOutput = """ - 1 │ let _ : Float -> Int - │ │ ╰─ error: expected ')' in function type - │ ╰─ error: expected '(' to start function type + 1 | let _ : Float -> Int + | | `- error: expected ')' in function type + | `- error: expected '(' to start function type """ @@ -159,11 +159,11 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { """ let expectedOutput = """ - 1 │ func o() { - 2 │ }👨‍👩‍👧‍👦} - │ │╰─ error: extraneous braces at top level - │ ╰─ error: consecutive statements on a line must be separated by newline or ';' - 3 │ } + 1 | func o() { + 2 | }👨‍👩‍👧‍👦} + | |`- error: extraneous braces at top level + | `- error: consecutive statements on a line must be separated by newline or ';' + 3 | } """ @@ -176,8 +176,8 @@ final class ParserDiagnosticsFormatterIntegrationTests: XCTestCase { """ let expectedOutput = """ - 1 │ let 👨‍👩‍👧‍👦 = ; - │ ╰─ error: expected expression in variable + 1 | let 👨‍👩‍👧‍👦 = ; + | `- error: expected expression in variable """ diff --git a/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift b/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift index 4240c5350dd..e5856339b18 100644 --- a/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift +++ b/Tests/SwiftIDEUtilsTest/NameMatcherTests.swift @@ -51,6 +51,7 @@ private func assertNameMatcherResult( case .noArguments: argumentLabels = [] case .call(let labels, _): argumentLabels = labels case .parameters(let labels): argumentLabels = labels + case .enumCaseParameters(let labels): argumentLabels = labels case .noncollapsibleParameters(let labels): argumentLabels = labels case .selector(let labels): argumentLabels = labels } @@ -58,7 +59,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) } @@ -70,6 +76,7 @@ private struct DeclNameLocationSpec { case noArguments case call case parameters + case enumCaseParameters case noncollapsibleParameters case selector @@ -78,6 +85,7 @@ private struct DeclNameLocationSpec { case .noArguments: self = .noArguments case .call: self = .call case .parameters: self = .parameters + case .enumCaseParameters: self = .enumCaseParameters case .noncollapsibleParameters: self = .noncollapsibleParameters case .selector: self = .selector } @@ -321,4 +329,63 @@ class NameMatcherTests: XCTestCase { ] ) } + + func testEnumCaseParameterWithLabels() { + assertNameMatcherResult( + """ + enum MyEnum { + case 1️⃣myCase(label: String) + } + """, + expected: [ + DeclNameLocationSpec(baseName: "myCase", argumentLabels: ["label"], type: .enumCaseParameters) + ] + ) + } + + func testEnumCaseParameterWithoutLabels() { + assertNameMatcherResult( + """ + enum MyEnum { + case 1️⃣myCase(String) + } + """, + expected: [ + DeclNameLocationSpec(baseName: "myCase", argumentLabels: [""], type: .enumCaseParameters) + ] + ) + } + + func testEnumCaseParameterWithoutAssociatedValues() { + assertNameMatcherResult( + """ + enum MyEnum { + case 1️⃣myCase + } + """, + expected: [ + DeclNameLocationSpec(baseName: "myCase", argumentLabels: [], type: .noArguments) + ] + ) + } + + func testEnumCaseParameterWithoutWildcardAsExternalLabel() { + assertNameMatcherResult( + """ + enum MyEnum { + case 1️⃣myCase(_ label: String) + } + """, + expected: [ + DeclNameLocationSpec(baseName: "myCase", argumentLabels: ["_ label"], type: .enumCaseParameters) + ] + ) + } + + func testPositionAtSpaceInFrontOfIdentifier() { + assertNameMatcherResult( + " 1️⃣ fn", + expected: [] + ) + } } diff --git a/Tests/SwiftParserTest/Assertions.swift b/Tests/SwiftParserTest/Assertions.swift index e9230aca36c..8cce493526a 100644 --- a/Tests/SwiftParserTest/Assertions.swift +++ b/Tests/SwiftParserTest/Assertions.swift @@ -99,7 +99,7 @@ private func assertTokens( } if actualLexeme.leadingTriviaText != expectedLexeme.leadingTrivia { - failStringsEqualWithDiff( + assertStringsEqualWithDiff( String(syntaxText: actualLexeme.leadingTriviaText), String(syntaxText: expectedLexeme.leadingTrivia), "Leading trivia does not match", @@ -109,7 +109,7 @@ private func assertTokens( } if actualLexeme.tokenText.debugDescription != expectedLexeme.tokenText.debugDescription { - failStringsEqualWithDiff( + assertStringsEqualWithDiff( actualLexeme.tokenText.debugDescription, expectedLexeme.tokenText.debugDescription, "Token text does not match", @@ -119,7 +119,7 @@ private func assertTokens( } if actualLexeme.trailingTriviaText != expectedLexeme.trailingTrivia { - failStringsEqualWithDiff( + assertStringsEqualWithDiff( String(syntaxText: actualLexeme.trailingTriviaText), String(syntaxText: expectedLexeme.trailingTrivia), "Trailing trivia does not match", @@ -402,7 +402,7 @@ func assertDiagnostic( line: spec.line ) } else if spec.fixIts != diag.fixIts.map(\.message.message) { - failStringsEqualWithDiff( + assertStringsEqualWithDiff( diag.fixIts.map(\.message.message).joined(separator: "\n"), spec.fixIts.joined(separator: "\n"), file: spec.file, @@ -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 57c77124a01..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", @@ -361,7 +364,7 @@ final class AttributeTests: ParserTestCase { assertParse( "@_implements(1️⃣\(baseType), f())", - AttributeSyntax.parse, + { AttributeSyntax.parse(from: &$0) }, substructure: TypeSyntax.parse(from: &parser), substructureAfterMarker: "1️⃣", line: line @@ -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..818e0a6c05d 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"), ], @@ -2978,7 +3105,7 @@ final class DeclarationTests: ParserTestCase { ) } - // https://github.com/apple/swift-syntax/issues/2273 + // https://github.com/swiftlang/swift-syntax/issues/2273 func testEnumCaseWithGenericParameter() { assertParse( """ @@ -3159,11 +3286,17 @@ final class DeclarationTests: ParserTestCase { func testInitializerWithReturnType() { assertParse( - "init(_ ptr: UnsafeRawBufferPointer, _ a: borrowing Array) -> _borrow(a) Self", + "init(_ ptr: UnsafeRawBufferPointer, _ a: borrowing Array) -> dependsOn(a) Self", experimentalFeatures: .nonescapableTypes ) // Not actually valid, needs to be diagnosed during type checking assertParse("public init() -> Int") } + + func testSendingTypeSpecifier() { + assertParse("func testVarDeclTupleElt() -> (sending String, String) {}") + assertParse("func testVarDeclTuple2(_ x: (sending String)) {}") + assertParse("func testVarDeclTuple2(_ x: (sending String, String)) {}") + } } diff --git a/Tests/SwiftParserTest/ExpressionInterpretedAsVersionTupleTests.swift b/Tests/SwiftParserTest/ExpressionInterpretedAsVersionTupleTests.swift new file mode 100644 index 00000000000..7a80a86ffec --- /dev/null +++ b/Tests/SwiftParserTest/ExpressionInterpretedAsVersionTupleTests.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import SwiftParser +import SwiftSyntax +import XCTest +import _SwiftSyntaxTestSupport + +final class ExpressionInterpretedAsVersionTupleTest: XCTestCase { + func testExpressionInterpretedAsVersionTuple() throws { + let expression: ExprSyntax = "1.2.3.4" + let versionTuple = try XCTUnwrap(expression.interpretedAsVersionTuple) + let subtreeMatcher = SubtreeMatcher(versionTuple, markers: [:]) + try subtreeMatcher.assertSameStructure( + VersionTupleSyntax( + major: .integerLiteral("1"), + components: VersionComponentListSyntax([ + VersionComponentSyntax( + period: .periodToken(), + number: .integerLiteral("2") + ), + VersionComponentSyntax( + period: .periodToken(), + number: .integerLiteral("3") + ), + VersionComponentSyntax( + period: .periodToken(), + number: .integerLiteral("4") + ), + ]) + ) + ) + } + + func testExpressionInterpretedAsInvalidVersionTuple() throws { + let expression: ExprSyntax = "2.0 + 1. + 1" + XCTAssertNil(expression.interpretedAsVersionTuple) + } + + func testMissingMajorComponent() throws { + let expression: ExprSyntax = ".1.2" + XCTAssertNil(expression.interpretedAsVersionTuple) + } + + func testMissingSubComponentNumber() throws { + let expression: ExprSyntax = "1.2." + XCTAssertNil(expression.interpretedAsVersionTuple) + } +} diff --git a/Tests/SwiftParserTest/ExpressionTests.swift b/Tests/SwiftParserTest/ExpressionTests.swift index 965e2eb4594..786c61bda43 100644 --- a/Tests/SwiftParserTest/ExpressionTests.swift +++ b/Tests/SwiftParserTest/ExpressionTests.swift @@ -271,7 +271,7 @@ final class ExpressionTests: ParserTestCase { assertParse( "\\\(rootType).y", - ExprSyntax.parse, + { ExprSyntax.parse(from: &$0) }, substructure: KeyPathExprSyntax( root: TypeSyntax.parse(from: &parser), components: KeyPathComponentListSyntax([ @@ -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]()" @@ -2902,6 +2972,9 @@ final class StatementExpressionTests: ParserTestCase { assertParse( "[() throws(MyError) -> Void]()" ) + assertParse( + "[() throws(any Error) -> Void]()" + ) assertParse( "X<() throws(MyError) -> Int>()" ) @@ -2910,6 +2983,22 @@ final class StatementExpressionTests: ParserTestCase { ) } + func testTypedThrowsClosureParam() { + assertParse( + """ + try foo { (a, b) throws(S) in 1 } + """ + ) + } + + func testTypedThrowsShorthandClosureParams() { + assertParse( + """ + try foo { a, b throws(S) in 1 } + """ + ) + } + func testArrayExprWithNoCommas() { assertParse("[() ()]") diff --git a/Tests/SwiftParserTest/ExpressionTypeTests.swift b/Tests/SwiftParserTest/ExpressionTypeTests.swift index 8f1f5b22bc1..5e8676c7539 100644 --- a/Tests/SwiftParserTest/ExpressionTypeTests.swift +++ b/Tests/SwiftParserTest/ExpressionTypeTests.swift @@ -74,7 +74,7 @@ final class ExpressionTypeTests: ParserTestCase { for (line, type) in cases { assertParse( "G<\(type)>.self", - ExprSyntax.parse, + { ExprSyntax.parse(from: &$0) }, substructure: IdentifierTypeSyntax(name: .identifier("X")), substructureAfterMarker: "1️⃣", line: line @@ -84,7 +84,7 @@ final class ExpressionTypeTests: ParserTestCase { // Void assertParse( "G<1️⃣()>.self", - ExprSyntax.parse, + { ExprSyntax.parse(from: &$0) }, substructure: TupleTypeSyntax(elements: .init([])), substructureAfterMarker: "1️⃣" ) @@ -92,7 +92,7 @@ final class ExpressionTypeTests: ParserTestCase { // Any assertParse( "G<1️⃣Any>.self", - ExprSyntax.parse, + { ExprSyntax.parse(from: &$0) }, substructure: IdentifierTypeSyntax(name: .keyword(.Any)), substructureAfterMarker: "1️⃣" ) @@ -100,7 +100,7 @@ final class ExpressionTypeTests: ParserTestCase { // Self assertParse( "G<1️⃣Self>.self", - ExprSyntax.parse, + { ExprSyntax.parse(from: &$0) }, substructure: IdentifierTypeSyntax(name: .keyword(.Self)), substructureAfterMarker: "1️⃣" ) diff --git a/Tests/SwiftParserTest/IncrementalParsingTests.swift b/Tests/SwiftParserTest/IncrementalParsingTests.swift index 679ace162d3..8bda2652e4e 100644 --- a/Tests/SwiftParserTest/IncrementalParsingTests.swift +++ b/Tests/SwiftParserTest/IncrementalParsingTests.swift @@ -23,7 +23,7 @@ class IncrementalParsingTests: ParserTestCase { struct A⏩️⏸️A⏪️ { func f() { """, reusedNodes: [ - ReusedNodeSpec("func f() {", kind: .memberDeclListItem) + ReusedNodeSpec("func f() {", kind: .memberBlockItem) ] ) } @@ -191,10 +191,10 @@ class IncrementalParsingTests: ParserTestCase { } """, reusedNodes: [ - ReusedNodeSpec("let a: Int", kind: .memberDeclListItem), - ReusedNodeSpec("let b: Int", kind: .memberDeclListItem), - ReusedNodeSpec("let c: Int", kind: .memberDeclListItem), - ReusedNodeSpec("let g: Int", kind: .memberDeclListItem), + ReusedNodeSpec("let a: Int", kind: .memberBlockItem), + ReusedNodeSpec("let b: Int", kind: .memberBlockItem), + ReusedNodeSpec("let c: Int", kind: .memberBlockItem), + ReusedNodeSpec("let g: Int", kind: .memberBlockItem), ] ) } 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 51ab3625bb5..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" + ) ] ) } @@ -1561,4 +1684,26 @@ class LexerTests: ParserTestCase { ] ) } + + func testNestedUnterminatedStringInterpolations() { + assertLexemes( + #""" + "\("\( + + """#, + lexemes: [ + LexemeSpec(.stringQuote, text: #"""#), + LexemeSpec(.stringSegment, text: ""), + LexemeSpec(.backslash, text: #"\"#), + LexemeSpec(.leftParen, text: "("), + LexemeSpec(.stringQuote, text: #"""#), + LexemeSpec(.stringSegment, text: ""), + LexemeSpec(.backslash, text: #"\"#), + LexemeSpec(.leftParen, text: "("), + LexemeSpec(.stringSegment, text: ""), + LexemeSpec(.stringSegment, text: ""), + LexemeSpec(.endOfFile, leading: "\n", text: "", flags: [.isAtStartOfLine]), + ] + ) + } } 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/ParserTests.swift b/Tests/SwiftParserTest/ParserTests.swift index f22e1dcad68..9b7c3450122 100644 --- a/Tests/SwiftParserTest/ParserTests.swift +++ b/Tests/SwiftParserTest/ParserTests.swift @@ -61,6 +61,7 @@ class ParserTests: ParserTestCase { checkDiagnostics: Bool, shouldExclude: @Sendable (URL) -> Bool = { _ in false } ) { + // nonisolated(unsafe) because [URL] is not marked Sendable on Linux. let fileURLs = FileManager.default .enumerator(at: path, includingPropertiesForKeys: nil)! .compactMap({ $0 as? URL }) @@ -85,7 +86,7 @@ class ParserTests: ParserTestCase { } } - let packageDir = URL(fileURLWithPath: #file) + let packageDir = URL(fileURLWithPath: #filePath) .deletingLastPathComponent() .deletingLastPathComponent() .deletingLastPathComponent() 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/TransferringTest.swift b/Tests/SwiftParserTest/SendingTest.swift similarity index 64% rename from Tests/SwiftParserTest/TransferringTest.swift rename to Tests/SwiftParserTest/SendingTest.swift index 49c61ca13c8..d2d84257f2b 100644 --- a/Tests/SwiftParserTest/TransferringTest.swift +++ b/Tests/SwiftParserTest/SendingTest.swift @@ -13,24 +13,22 @@ @_spi(ExperimentalLanguageFeatures) import SwiftParser import XCTest -final class TransferringTests: ParserTestCase { - func testTransferingArg1() { +final class SendingTests: ParserTestCase { + func testSendingArg1() { assertParse( """ class Klass {} - func transferMain(_ x: transferring Klass) -> () - """, - experimentalFeatures: .transferringArgsAndResults + func transferMain(_ x: sending Klass) -> () + """ ) } - func testTransferingArgMiddle() { + func testSendingArgMiddle() { assertParse( """ class Klass {} - func transferMain(_ y: Klass, _ x: transferring Klass, _ z: Klass) -> () - """, - experimentalFeatures: .transferringArgsAndResults + func transferMain(_ y: Klass, _ x: sending Klass, _ z: Klass) -> () + """ ) } } diff --git a/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift b/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift index 602628c3469..1a45c2ac39c 100644 --- a/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift +++ b/Tests/SwiftParserTest/SequentialToConcurrentEditTranslationTests.swift @@ -37,7 +37,7 @@ func verifySequentialToConcurrentTranslation( _ sequential: [IncrementalEdit], _ expectedConcurrent: [IncrementalEdit], testString: String = longString, - file: StaticString = #file, + file: StaticString = #filePath, line: UInt = #line ) { let concurrent = ConcurrentEdits(fromSequential: sequential) @@ -337,7 +337,9 @@ final class TranslateSequentialToConcurrentEditsTests: ParserTestCase { let numEdits = Int.random(in: 1..<10) for _ in 0..case @@ -656,7 +676,7 @@ final class StatementTests: ParserTestCase { } func testSkippingOverEmptyStringLiteral() { - // https://github.com/apple/swift-syntax/issues/1247 + // https://github.com/swiftlang/swift-syntax/issues/1247 assertParse( """ if pℹ️{""1️⃣ @@ -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/TypeCompositionTests.swift b/Tests/SwiftParserTest/TypeCompositionTests.swift index 0e6adf5c657..05ada5c9753 100644 --- a/Tests/SwiftParserTest/TypeCompositionTests.swift +++ b/Tests/SwiftParserTest/TypeCompositionTests.swift @@ -51,7 +51,7 @@ final class TypeCompositionTests: ParserTestCase { assertParse( "\(component) & \(component) & \(component)", - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: CompositionTypeSyntax( elements: .init([ CompositionTypeElementSyntax(type: componentSyntax, ampersand: .binaryOperator("&")), diff --git a/Tests/SwiftParserTest/TypeMemberTests.swift b/Tests/SwiftParserTest/TypeMemberTests.swift index b839b60f10a..9e0e123ccc1 100644 --- a/Tests/SwiftParserTest/TypeMemberTests.swift +++ b/Tests/SwiftParserTest/TypeMemberTests.swift @@ -18,7 +18,7 @@ final class TypeMemberTests: ParserTestCase { func testKeyword() { assertParse( "MyType.class", - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: MemberTypeSyntax( baseType: IdentifierTypeSyntax( name: .identifier("MyType") @@ -31,7 +31,7 @@ final class TypeMemberTests: ParserTestCase { func testMissing() { assertParse( "MyType.1️⃣", - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: MemberTypeSyntax( baseType: IdentifierTypeSyntax( name: .identifier("MyType") @@ -69,7 +69,7 @@ final class TypeMemberTests: ParserTestCase { for (line, source) in cases { assertParse( source, - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: expected, line: line ) @@ -86,8 +86,10 @@ final class TypeMemberTests: ParserTestCase { for (line, source) in cases { assertParse( source, - TypeSyntax.parse, - diagnostics: [DiagnosticSpec(message: "extraneous whitespace after '.' is not permitted", fixIts: ["remove whitespace"])], + { TypeSyntax.parse(from: &$0) }, + diagnostics: [ + DiagnosticSpec(message: "extraneous whitespace after '.' is not permitted", fixIts: ["remove whitespace"]) + ], fixedSource: expected, line: line ) @@ -136,14 +138,14 @@ final class TypeMemberTests: ParserTestCase { assertParse( "\(baseType).Z", - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: expectedSyntax, line: line ) assertParse( "\(baseType).Z", - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: expectedSyntax.with( \.genericArgumentClause, GenericArgumentClauseSyntax( diff --git a/Tests/SwiftParserTest/TypeMetatypeTests.swift b/Tests/SwiftParserTest/TypeMetatypeTests.swift index a5c506cd5fb..cf4ecf6afec 100644 --- a/Tests/SwiftParserTest/TypeMetatypeTests.swift +++ b/Tests/SwiftParserTest/TypeMetatypeTests.swift @@ -55,7 +55,7 @@ final class TypeMetatypeTests: ParserTestCase { for metaKind in [.`Type`, .`Protocol`] as [Keyword] { assertParse( "\(baseType).\(metaKind)", - TypeSyntax.parse, + { TypeSyntax.parse(from: &$0) }, substructure: MetatypeTypeSyntax( baseType: baseTypeSyntax, metatypeSpecifier: .keyword(metaKind) diff --git a/Tests/SwiftParserTest/TypeTests.swift b/Tests/SwiftParserTest/TypeTests.swift index a06caabf286..496b65264a0 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#> @@ -305,6 +309,109 @@ final class TypeTests: ParserTestCase { ) } + func testInverseTypes() { + assertParse( + "[~Copyable]()" + ) + + assertParse( + "[any ~Copyable]()" + ) + + assertParse( + "[any P & ~Copyable]()" + ) + + assertParse( + "[P & ~Copyable]()" + ) + + assertParse( + "X<~Copyable>()" + ) + + assertParse( + "X()" + ) + + assertParse( + "X

()" + ) + + assertParse( + "X()" + ) + } + + func testInverseTypesAsExpr() { + assertParse( + "(~Copyable).self" + ) + + assertParse( + "~Copyable.self" + ) + + assertParse( + "(any ~Copyable).self" + ) + } + + func testInverseTypesInParameter() { + assertParse( + "func f(_: borrowing ~Copyable) {}" + ) + + assertParse( + "func f(_: consuming ~Copyable) {}" + ) + + assertParse( + "func f(_: borrowing any ~Copyable) {}" + ) + + assertParse( + "func f(_: consuming any ~Copyable) {}" + ) + + assertParse( + "func f(_: ~Copyable) {}" + ) + + assertParse( + "typealias T = (~Copyable) -> Void" + ) + + assertParse( + "typealias T = (_ x: ~Copyable) -> Void" + ) + + assertParse( + "typealias T = (borrowing ~Copyable) -> Void" + ) + + assertParse( + "typealias T = (_ x: borrowing ~Copyable) -> Void" + ) + + assertParse( + "typealias T = (borrowing any ~Copyable) -> Void" + ) + + assertParse( + "typealias T = (_ x: borrowing any ~Copyable) -> Void" + ) + + assertParse( + "func f(_: any borrowing 1️⃣~Copyable) {}", + diagnostics: [ + DiagnosticSpec( + message: "unexpected code '~Copyable' in parameter clause" + ) + ] + ) + } + func testTypedThrows() { assertParse( """ @@ -327,38 +434,42 @@ final class TypeTests: ParserTestCase { } func testLifetimeSpecifier() { - assertParse("func foo() -> _borrow(x) X", experimentalFeatures: [.nonescapableTypes]) + assertParse("func foo() -> dependsOn(x) X", experimentalFeatures: [.nonescapableTypes]) - assertParse("func foo() -> _borrow(x, y) X", experimentalFeatures: [.nonescapableTypes]) + assertParse("func foo() -> dependsOn(x, y) X", experimentalFeatures: [.nonescapableTypes]) assertParse( - "func foo() -> _borrow(1️⃣) X", + "func foo() -> dependsOn(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", + fixedSource: "func foo() -> dependsOn(<#identifier#>) X", experimentalFeatures: [.nonescapableTypes] ) assertParse( - "func foo() -> _borrow(x,1️⃣) X", + "func foo() -> dependsOn(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", + fixedSource: "func foo() -> dependsOn(x, <#identifier#>) X", experimentalFeatures: [.nonescapableTypes] ) - assertParse("func foo() -> _borrow(x) _borrow(y) X", experimentalFeatures: [.nonescapableTypes]) - - assertParse("func foo() -> _mutate(x) X", experimentalFeatures: [.nonescapableTypes]) - - assertParse("func foo() -> _copy(x) X", experimentalFeatures: [.nonescapableTypes]) + assertParse("func foo() -> dependsOn(x) dependsOn(scoped y) X", experimentalFeatures: [.nonescapableTypes]) - assertParse("func foo() -> _consume(x) X", experimentalFeatures: [.nonescapableTypes]) + assertParse("func foo() -> dependsOn(scoped x) X", experimentalFeatures: [.nonescapableTypes]) assertParse( - "func foo() -> _borrow 1️⃣X", + "func foo() -> dependsOn1️⃣ X", diagnostics: [ DiagnosticSpec( locationMarker: "1️⃣", @@ -366,26 +477,30 @@ final class TypeTests: ParserTestCase { fixIts: ["insert '(', parameter reference, and ')'"] ) ], - fixedSource: "func foo() -> _borrow (<#identifier#>) X", + fixedSource: "func foo() -> dependsOn(<#identifier#>) X", experimentalFeatures: [.nonescapableTypes] ) assertParse( - "func foo() -> _borrow(1️⃣*) X", + "func foo() -> dependsOn(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", + fixedSource: "func foo() -> dependsOn(<#identifier#>*) X", experimentalFeatures: [.nonescapableTypes] ) - assertParse("func foo() -> _borrow(0) X", diagnostics: [], experimentalFeatures: [.nonescapableTypes]) + assertParse("func foo() -> dependsOn(0) X", diagnostics: [], experimentalFeatures: [.nonescapableTypes]) - assertParse("func foo() -> _borrow(self) X", experimentalFeatures: [.nonescapableTypes]) + assertParse("func foo() -> dependsOn(self) X", experimentalFeatures: [.nonescapableTypes]) assertParse( - "func foo() -> _borrow1️⃣(0)2️⃣ X", + "func foo() -> dependsOn1️⃣(0)2️⃣ X", diagnostics: [ DiagnosticSpec( locationMarker: "1️⃣", @@ -399,19 +514,22 @@ final class TypeTests: ParserTestCase { ), ], fixedSource: """ - func foo() -> _borrow + func foo() -> dependsOn (0) X """ ) assertParse( - "func foo() -> _borrow(1️⃣-1) X", + "func foo() -> dependsOn(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", + fixedSource: "func foo() -> dependsOn(<#identifier#>-1) X", experimentalFeatures: [.nonescapableTypes] ) } diff --git a/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift b/Tests/SwiftParserTest/translated/AvailabilityQueryTests.swift index bd612ddc9e8..4425e329fd5 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, *) { @@ -115,7 +124,7 @@ final class AvailabilityQueryTests: ParserTestCase { func testAvailabilityQuery7() { assertParse( """ - if #available 1️⃣{ + if #available1️⃣ { } """, diagnostics: [ @@ -126,7 +135,7 @@ final class AvailabilityQueryTests: ParserTestCase { ) ], fixedSource: """ - if #available (<#identifier#>) { + if #available(<#identifier#>) { } """ ) @@ -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 30ba480f043..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"# + ), ] ) } @@ -262,10 +265,7 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, _version: 2.2.2.21️⃣.2) let a = 1 #endif - """, - diagnostics: [ - DiagnosticSpec(message: "trailing components of version 2.2.2.2 are ignored", severity: .warning) - ] + """ ) } @@ -315,10 +315,7 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, 1️⃣unknown: 2.2) let a = 1 #endif - """, - diagnostics: [ - DiagnosticSpec(message: "2nd parameter of canImport should be labeled as _version or _underlyingVersion") - ] + """ ) } @@ -330,8 +327,13 @@ final class IfconfigExprTests: ParserTestCase { #endif """, diagnostics: [ - DiagnosticSpec(message: "2nd parameter of canImport should be labeled as _version or _underlyingVersion") - ] + DiagnosticSpec(message: "expected value in function call", fixIts: ["insert value"]) + ], + fixedSource: """ + #if canImport(A, <#expression#>) + let a = 1 + #endif + """ ) } @@ -341,10 +343,7 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, 1️⃣2.2) let a = 1 #endif - """, - diagnostics: [ - DiagnosticSpec(message: "2nd parameter of canImport should be labeled as _version or _underlyingVersion") - ] + """ ) } @@ -354,11 +353,7 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, 1️⃣2.22️⃣, 1.1) let a = 1 #endif - """, - diagnostics: [ - DiagnosticSpec(locationMarker: "1️⃣", message: "2nd parameter of canImport should be labeled as _version or _underlyingVersion"), - DiagnosticSpec(locationMarker: "2️⃣", message: "canImport can take only two parameters"), - ] + """ ) } @@ -370,10 +365,10 @@ final class IfconfigExprTests: ParserTestCase { #endif """, diagnostics: [ - DiagnosticSpec(message: "expected version tuple in 'canImport' expression", fixIts: ["insert version tuple"]) + DiagnosticSpec(message: "expected value in function call", fixIts: ["insert value"]) ], fixedSource: """ - #if canImport(A, _version: <#integer literal#>) + #if canImport(A, _version: <#expression#>) let a = 1 #endif """ @@ -386,10 +381,7 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, _version: 1️⃣"") let a = 1 #endif - """#, - diagnostics: [ - DiagnosticSpec(message: #"cannot parse version component code '""'"#) - ] + """# ) } @@ -399,22 +391,19 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, _version: 1️⃣>=2.2) let a = 1 #endif - """, - diagnostics: [ - DiagnosticSpec(message: "cannot parse version component code '>=2.2'") - ] + """ ) } func testIfconfigExpr29() { assertParse( """ - #if canImport(A, _version: 1️⃣20A301) + #if canImport(A, _version: 201️⃣A301) let a = 1 #endif """, diagnostics: [ - DiagnosticSpec(message: "cannot parse version component code '20A301'") + DiagnosticSpec(message: "'A' is not a valid digit in integer literal") ] ) } @@ -425,10 +414,7 @@ final class IfconfigExprTests: ParserTestCase { #if canImport(A, _version: 1️⃣"20A301") let a = 1 #endif - """#, - diagnostics: [ - DiagnosticSpec(message: #"cannot parse version component code '"20A301"'"#) - ] + """# ) } @@ -445,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'"] ) ], @@ -720,4 +707,13 @@ final class IfconfigExprTests: ParserTestCase { ) ) } + + func testCanImportWithStringVersion() { + assertParse( + """ + #if canImport(MyModule, _version: "1.2.3") + #endif + """ + ) + } } 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/MatchingPatternsTests.swift b/Tests/SwiftParserTest/translated/MatchingPatternsTests.swift index 4036caf2821..c7d407bc9e7 100644 --- a/Tests/SwiftParserTest/translated/MatchingPatternsTests.swift +++ b/Tests/SwiftParserTest/translated/MatchingPatternsTests.swift @@ -612,67 +612,63 @@ final class MatchingPatternsTests: ParserTestCase { assertParse( """ switch 42 { - case _borrowing .foo(): // parses as `_borrowing.foo()` as before + case borrowing .foo(): // parses as `borrowing.foo()` as before break } """, - substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("_borrowing"))), - experimentalFeatures: .borrowingSwitch + substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("borrowing"))) ) assertParse( """ switch 42 { - case _borrowing (): // parses as `_borrowing()` as before + case borrowing (): // parses as `borrowing()` as before break } """, - substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("_borrowing"))), - experimentalFeatures: .borrowingSwitch + substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("borrowing"))) ) assertParse( """ switch 42 { - case _borrowing x: // parses as binding + case borrowing x: // parses as binding break } """, substructure: PatternSyntax( ValueBindingPatternSyntax( - bindingSpecifier: .keyword(._borrowing), + bindingSpecifier: .keyword(.borrowing), pattern: PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("x"))) ) - ), - experimentalFeatures: .borrowingSwitch + ) ) assertParse( """ switch bar { - case .payload(_borrowing x): // parses as binding + case .payload(borrowing x): // parses as binding break } """, substructure: PatternSyntax( ValueBindingPatternSyntax( - bindingSpecifier: .keyword(._borrowing), + bindingSpecifier: .keyword(.borrowing), pattern: PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("x"))) ) - ), - experimentalFeatures: .borrowingSwitch + ) ) assertParse( """ switch bar { - case _borrowing x.member: // parses as var introducer surrounding postfix expression (which never is valid) + case borrowing x.member: // parses as var introducer surrounding postfix expression (which never is valid) break } """, substructure: PatternSyntax( ValueBindingPatternSyntax( - bindingSpecifier: .keyword(._borrowing), + bindingSpecifier: .keyword(.borrowing), pattern: ExpressionPatternSyntax( expression: MemberAccessExprSyntax( base: DeclReferenceExprSyntax(baseName: .identifier("x")), @@ -680,58 +676,53 @@ final class MatchingPatternsTests: ParserTestCase { ) ) ) - ), - experimentalFeatures: .borrowingSwitch + ) ) assertParse( """ switch 42 { - case let _borrowing: // parses as let binding named '_borrowing' + case let borrowing: // parses as let binding named 'borrowing' break } """, substructure: PatternSyntax( ValueBindingPatternSyntax( bindingSpecifier: .keyword(.let), - pattern: PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("_borrowing"))) + pattern: PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("borrowing"))) ) - ), - experimentalFeatures: .borrowingSwitch + ) ) assertParse( """ switch 42 { - case _borrowing + _borrowing: // parses as expr pattern + case borrowing + borrowing: // parses as expr pattern break } """, - substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("_borrowing"))), - experimentalFeatures: .borrowingSwitch + substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("borrowing"))) ) assertParse( """ switch 42 { - case _borrowing(let _borrowing): // parses as let binding named '_borrowing' inside a case pattern named 'borrowing' + case borrowing(let borrowing): // parses as let binding named 'borrowing' inside a case pattern named 'borrowing' break } """, substructure: PatternSyntax( ValueBindingPatternSyntax( bindingSpecifier: .keyword(.let), - pattern: PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("_borrowing"))) + pattern: PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("borrowing"))) ) - ), - experimentalFeatures: .borrowingSwitch + ) ) assertParse( """ switch 42 { - case {}(_borrowing + _borrowing): // parses as expr pattern + case {}(borrowing + borrowing): // parses as expr pattern break } """, - substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("_borrowing"))), - experimentalFeatures: .borrowingSwitch + substructure: ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("borrowing"))) ) } } 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..93ce16e2c43 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 { @@ -2363,7 +2454,7 @@ final class RecoveryTests: ParserTestCase { DiagnosticSpec(message: "unexpected code '!=baz' in parameter clause"), ], fixedSource: """ - func foo1(bar: <#type#>!=baz) {} + func foo1(bar: <#type#>!=baz) {} """ ) } @@ -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 {} @@ -3192,7 +3315,7 @@ final class RecoveryTests: ParserTestCase { ) } - // https://github.com/apple/swift-syntax/issues/1483 + // https://github.com/swiftlang/swift-syntax/issues/1483 func testRecovery183() { // Can be parsed and produces no diagnostics. assertParse( @@ -3223,7 +3346,7 @@ final class RecoveryTests: ParserTestCase { ) } - // https://github.com/apple/swift-syntax/pull/1484/files#r1176740738 + // https://github.com/swiftlang/swift-syntax/pull/1484/files#r1176740738 func testRecovery184() { assertParse( "func foo() -> Int1️⃣:", 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/TypeExprTests.swift b/Tests/SwiftParserTest/translated/TypeExprTests.swift index cc98b34d803..badce123c32 100644 --- a/Tests/SwiftParserTest/translated/TypeExprTests.swift +++ b/Tests/SwiftParserTest/translated/TypeExprTests.swift @@ -116,9 +116,9 @@ final class TypeExprTests: ParserTestCase { """ ) - assertParse("(X).Y.self", ExprSyntax.parse) - assertParse("(X.Y).Z.self", ExprSyntax.parse) - assertParse("((X).Y).Z.self", ExprSyntax.parse) + assertParse("(X).Y.self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X.Y).Z.self", { ExprSyntax.parse(from: &$0) }) + assertParse("((X).Y).Z.self", { ExprSyntax.parse(from: &$0) }) } func testTypeExpr9() { @@ -154,9 +154,9 @@ final class TypeExprTests: ParserTestCase { """ ) - assertParse("X?.self", ExprSyntax.parse) - assertParse("[X].self", ExprSyntax.parse) - assertParse("[X : Y].self", ExprSyntax.parse) + assertParse("X?.self", { ExprSyntax.parse(from: &$0) }) + assertParse("[X].self", { ExprSyntax.parse(from: &$0) }) + assertParse("[X : Y].self", { ExprSyntax.parse(from: &$0) }) } func testTypeExpr11() { @@ -182,12 +182,12 @@ final class TypeExprTests: ParserTestCase { """ ) - assertParse("(G).Y.self", ExprSyntax.parse) - assertParse("X?.Y.self", ExprSyntax.parse) - assertParse("(X)?.Y.self", ExprSyntax.parse) - assertParse("(X?).Y.self", ExprSyntax.parse) - assertParse("[X].Y.self", ExprSyntax.parse) - assertParse("[X : Y].Z.self", ExprSyntax.parse) + assertParse("(G).Y.self", { ExprSyntax.parse(from: &$0) }) + assertParse("X?.Y.self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X)?.Y.self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X?).Y.self", { ExprSyntax.parse(from: &$0) }) + assertParse("[X].Y.self", { ExprSyntax.parse(from: &$0) }) + assertParse("[X : Y].Z.self", { ExprSyntax.parse(from: &$0) }) } func testTypeExpr12() { @@ -578,57 +578,57 @@ final class TypeExprTests: ParserTestCase { } func testCompositionTypeExpr() { - assertParse("P & Q", ExprSyntax.parse) - assertParse("P & Q.self", ExprSyntax.parse) - assertParse("any P & Q", ExprSyntax.parse) + assertParse("P & Q", { ExprSyntax.parse(from: &$0) }) + assertParse("P & Q.self", { ExprSyntax.parse(from: &$0) }) + assertParse("any P & Q", { ExprSyntax.parse(from: &$0) }) - assertParse("(P & Q).self", ExprSyntax.parse) - assertParse("((P) & (Q)).self", ExprSyntax.parse) + assertParse("(P & Q).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((P) & (Q)).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(A.B & C.D).self", ExprSyntax.parse) - assertParse("((A).B & (C).D).self", ExprSyntax.parse) + assertParse("(A.B & C.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((A).B & (C).D).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(G & G).self", ExprSyntax.parse) - assertParse("(X? & Y?).self", ExprSyntax.parse) - assertParse("([X] & [Y]).self", ExprSyntax.parse) - assertParse("([A : B] & [C : D]).self", ExprSyntax.parse) + assertParse("(G & G).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X? & Y?).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([X] & [Y]).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([A : B] & [C : D]).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(G.B & G.D).self", ExprSyntax.parse) - assertParse("(A?.B & C?.D).self", ExprSyntax.parse) - assertParse("([A].B & [A].B).self", ExprSyntax.parse) - assertParse("([A : B].C & [D : E].F).self", ExprSyntax.parse) + assertParse("(G.B & G.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(A?.B & C?.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([A].B & [A].B).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([A : B].C & [D : E].F).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(X.Type & Y.Type).self", ExprSyntax.parse) - assertParse("(X.Protocol & Y.Protocol).self", ExprSyntax.parse) + assertParse("(X.Type & Y.Type).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X.Protocol & Y.Protocol).self", { ExprSyntax.parse(from: &$0) }) - assertParse("((A, B) & (C, D)).self", ExprSyntax.parse) + assertParse("((A, B) & (C, D)).self", { ExprSyntax.parse(from: &$0) }) } func testTupleTypeExpr() { - assertParse("(X).self", ExprSyntax.parse) + assertParse("(X).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(X, Y)", ExprSyntax.parse) + assertParse("(X, Y)", { ExprSyntax.parse(from: &$0) }) - assertParse("(X, Y).self", ExprSyntax.parse) - assertParse("((X), (Y)).self", ExprSyntax.parse) + assertParse("(X, Y).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((X), (Y)).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(A.B, C.D).self", ExprSyntax.parse) - assertParse("((A).B, (C).D).self", ExprSyntax.parse) + assertParse("(A.B, C.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((A).B, (C).D).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(G, G).self", ExprSyntax.parse) - assertParse("(X?, Y?).self", ExprSyntax.parse) - assertParse("([X], [Y]).self", ExprSyntax.parse) - assertParse("([A : B], [C : D]).self", ExprSyntax.parse) + assertParse("(G, G).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X?, Y?).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([X], [Y]).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([A : B], [C : D]).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(G.B, G.D).self", ExprSyntax.parse) - assertParse("(A?.B, C?.D).self", ExprSyntax.parse) - assertParse("([A].B, [C].D).self", ExprSyntax.parse) - assertParse("([A : B].C, [D : E].F).self", ExprSyntax.parse) + assertParse("(G.B, G.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(A?.B, C?.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([A].B, [C].D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("([A : B].C, [D : E].F).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(X.Type, Y.Type).self", ExprSyntax.parse) - assertParse("(X.Protocol, Y.Protocol).self", ExprSyntax.parse) + assertParse("(X.Type, Y.Type).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(X.Protocol, Y.Protocol).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(P & Q, P & Q).self", ExprSyntax.parse) + assertParse("(P & Q, P & Q).self", { ExprSyntax.parse(from: &$0) }) assertParse( """ @@ -636,41 +636,41 @@ final class TypeExprTests: ParserTestCase { (G.Y) -> (P) & X?.Y, (X.Y, [X : Y?].Type), [(G).Y], [A.B.C].D ).self """, - ExprSyntax.parse + { ExprSyntax.parse(from: &$0) } ) } func testFunctionTypeExpr() { - assertParse("X -> Y", ExprSyntax.parse) - assertParse("(X) -> Y", ExprSyntax.parse) - assertParse("(X) -> Y -> Z", ExprSyntax.parse) - assertParse("P & Q -> X", ExprSyntax.parse) - assertParse("A & B -> C & D -> X", ExprSyntax.parse) - assertParse("(X -> Y).self", ExprSyntax.parse) - assertParse("(A & B -> C & D).self", ExprSyntax.parse) + assertParse("X -> Y", { ExprSyntax.parse(from: &$0) }) + assertParse("(X) -> Y", { ExprSyntax.parse(from: &$0) }) + assertParse("(X) -> Y -> Z", { ExprSyntax.parse(from: &$0) }) + assertParse("P & Q -> X", { ExprSyntax.parse(from: &$0) }) + assertParse("A & B -> C & D -> X", { ExprSyntax.parse(from: &$0) }) + assertParse("(X -> Y).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(A & B -> C & D).self", { ExprSyntax.parse(from: &$0) }) - assertParse("((X) -> Y).self", ExprSyntax.parse) - assertParse("(((X)) -> (Y)).self", ExprSyntax.parse) + assertParse("((X) -> Y).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(((X)) -> (Y)).self", { ExprSyntax.parse(from: &$0) }) - assertParse("((A.B) -> C.D).self", ExprSyntax.parse) - assertParse("(((A).B) -> (C).D).self", ExprSyntax.parse) + assertParse("((A.B) -> C.D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(((A).B) -> (C).D).self", { ExprSyntax.parse(from: &$0) }) - assertParse("((G) -> G).self", ExprSyntax.parse) - assertParse("((X?) -> Y?).self", ExprSyntax.parse) - assertParse("(([X]) -> [Y]).self", ExprSyntax.parse) - assertParse("(([A : B]) -> [C : D]).self", ExprSyntax.parse) + assertParse("((G) -> G).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((X?) -> Y?).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(([X]) -> [Y]).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(([A : B]) -> [C : D]).self", { ExprSyntax.parse(from: &$0) }) - assertParse("((Gen.Bar) -> Gen.Bar).self", ExprSyntax.parse) - assertParse("((Foo?.Bar) -> Foo?.Bar).self", ExprSyntax.parse) - assertParse("(([Foo].Element) -> [Foo].Element).self", ExprSyntax.parse) - assertParse("(([Int : Foo].Element) -> [Int : Foo].Element).self", ExprSyntax.parse) + assertParse("((Gen.Bar) -> Gen.Bar).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((Foo?.Bar) -> Foo?.Bar).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(([Foo].Element) -> [Foo].Element).self", { ExprSyntax.parse(from: &$0) }) + assertParse("(([Int : Foo].Element) -> [Int : Foo].Element).self", { ExprSyntax.parse(from: &$0) }) - assertParse("((X.Type) -> Y.Type).self", ExprSyntax.parse) - assertParse("((X.Protocol) -> Y.Protocol).self", ExprSyntax.parse) + assertParse("((X.Type) -> Y.Type).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((X.Protocol) -> Y.Protocol).self", { ExprSyntax.parse(from: &$0) }) - assertParse("(() -> X & Y).self", ExprSyntax.parse) - assertParse("((A & B) -> C & D).self", ExprSyntax.parse) - assertParse("((A & B) -> (C & D) -> E & Any).self", ExprSyntax.parse) + assertParse("(() -> X & Y).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((A & B) -> C & D).self", { ExprSyntax.parse(from: &$0) }) + assertParse("((A & B) -> (C & D) -> E & Any).self", { ExprSyntax.parse(from: &$0) }) assertParse( """ @@ -678,7 +678,7 @@ final class TypeExprTests: ParserTestCase { ((P) & X?.Y, G.Y, (X, [A : B?].Type)) -> ([(X).Y]) -> [X].Y ).self """, - ExprSyntax.parse + { ExprSyntax.parse(from: &$0) } ) } 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 4be5607e46d..bec587bf200 100644 --- a/Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift +++ b/Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift @@ -247,4 +247,42 @@ final class UnclosedStringInterpolationTests: ParserTestCase { """# ) } + + func testNestedUnterminatedStringInterpolation() { + assertParse( + #""" + 1️⃣"\2️⃣(3️⃣"\(4️⃣ + + """#, + diagnostics: [ + DiagnosticSpec( + locationMarker: "4️⃣", + message: "expected value and ')' in string literal", + fixIts: ["insert value and ')'"] + ), + DiagnosticSpec( + locationMarker: "4️⃣", + message: #"expected '"' to end string literal"#, + notes: [NoteSpec(locationMarker: "3️⃣", message: #"to match this opening '"'"#)], + fixIts: [#"insert '"'"#] + ), + DiagnosticSpec( + locationMarker: "4️⃣", + message: "expected ')' in string literal", + notes: [NoteSpec(locationMarker: "2️⃣", message: "to match this opening '('")], + fixIts: ["insert ')'"] + ), + DiagnosticSpec( + locationMarker: "4️⃣", + message: #"expected '"' to end string literal"#, + notes: [NoteSpec(locationMarker: "1️⃣", message: #"to match this opening '"'"#)], + fixIts: [#"insert '"'"#] + ), + ], + fixedSource: #""" + "\("\(<#expression#>)")" + + """# + ) + } } diff --git a/Tests/SwiftRefactorTest/CallToTrailingClosureTests.swift b/Tests/SwiftRefactorTest/CallToTrailingClosureTests.swift index 4c32c79c1dd..06cc7984da4 100644 --- a/Tests/SwiftRefactorTest/CallToTrailingClosureTests.swift +++ b/Tests/SwiftRefactorTest/CallToTrailingClosureTests.swift @@ -80,7 +80,7 @@ final class CallToTrailingClosuresTest: XCTestCase { """ // TODO: The ident here is not great. - // https://github.com/apple/swift-syntax/issues/1473 + // https://github.com/swiftlang/swift-syntax/issues/1473 let expected: ExprSyntax = """ foo({ label in return 1 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..4194894c0e8 100644 --- a/Tests/SwiftSyntaxBuilderTest/StringInterpolationTests.swift +++ b/Tests/SwiftSyntaxBuilderTest/StringInterpolationTests.swift @@ -442,15 +442,18 @@ 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( String(describing: error), """ - 1 │ /*comment*/ invalid /*comm*/ - │ ╰─ error: unexpected trivia 'invalid' + 1 | /*comment*/ invalid /*comm*/ + | `- error: unexpected trivia 'invalid' """ ) @@ -467,9 +470,9 @@ final class StringInterpolationTests: XCTestCase { String(describing: error), """ - 1 │ return 1 - │ │ ╰─ error: expected declaration - │ ╰─ error: unexpected code 'return 1' before declaration + 1 | return 1 + | | `- error: expected declaration + | `- error: unexpected code 'return 1' before declaration """ ) @@ -486,9 +489,9 @@ final class StringInterpolationTests: XCTestCase { String(describing: error), """ - 1 │ struct Foo {} - │ │ ╰─ error: expected statement - │ ╰─ error: unexpected code 'struct Foo {}' before statement + 1 | struct Foo {} + | | `- error: expected statement + | `- error: unexpected code 'struct Foo {}' before statement """ ) @@ -505,8 +508,8 @@ final class StringInterpolationTests: XCTestCase { String(describing: error), """ - 1 │ - │ ╰─ error: expected declaration + 1 | + | `- error: expected declaration """ ) 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..8aeaaad5d2a 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"#) } @@ -375,7 +389,7 @@ final class VariableTests: XCTestCase { } } - // https://github.com/apple/swift-syntax/issues/1815 + // https://github.com/swiftlang/swift-syntax/issues/1815 func testSpacingInDictionaryType() throws { let buildable = try VariableDeclSyntax("static var mirror: Dictionary") {} 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/LexicalContextTests.swift b/Tests/SwiftSyntaxMacroExpansionTest/LexicalContextTests.swift index 8a844347107..533a2a4d19f 100644 --- a/Tests/SwiftSyntaxMacroExpansionTest/LexicalContextTests.swift +++ b/Tests/SwiftSyntaxMacroExpansionTest/LexicalContextTests.swift @@ -200,8 +200,8 @@ struct AllLexicalContextsMacro: DeclarationMacro { } } -public struct LexicalContextDescriptionMacro: ExpressionMacro { - public static func expansion( +struct LexicalContextDescriptionMacro: ExpressionMacro { + static func expansion( of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext ) throws -> ExprSyntax { 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/IdentifierTests.swift b/Tests/SwiftSyntaxTest/IdentifierTests.swift new file mode 100644 index 00000000000..e0083a0a5c4 --- /dev/null +++ b/Tests/SwiftSyntaxTest/IdentifierTests.swift @@ -0,0 +1,53 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +@_spi(RawSyntax) import SwiftSyntax +import XCTest + +class IdentifierTests: XCTestCase { + public func testIdentifierInit() { + let someToken = TokenSyntax(stringLiteral: "someToken") + XCTAssertNotNil(Identifier(someToken)) + + let nonIdentifierToken = DeclSyntax("let a = 1").firstToken(viewMode: .all)! + XCTAssertNil(Identifier(nonIdentifierToken)) + } + + public func testName() { + let basicToken = TokenSyntax(stringLiteral: "basicToken") + XCTAssertEqual(Identifier(basicToken)?.name, "basicToken") + + let backtickedToken = TokenSyntax(stringLiteral: "`backtickedToken`") + XCTAssertEqual(Identifier(backtickedToken)?.name, "backtickedToken") + + let multiBacktickedToken = TokenSyntax(stringLiteral: "```multiBacktickedToken```") + XCTAssertEqual(Identifier(multiBacktickedToken)?.name, "``multiBacktickedToken``") + + let unicodeNormalizedToken = TokenSyntax(stringLiteral: "\u{e0}") // "a`" + XCTAssertEqual(Identifier(unicodeNormalizedToken)?.name, "\u{61}\u{300}") // "à" + } + + public func testIdentifier() { + let token = TokenSyntax(stringLiteral: "sometoken") + withExtendedLifetime(token) { token in + XCTAssertEqual(token.identifier?.raw.name, SyntaxText("sometoken")) + } + } + + public func testTokenSyntaxIdentifier() throws { + let tokenSyntax = TokenSyntax(stringLiteral: "sometoken") + XCTAssertEqual(tokenSyntax.identifier, Identifier(tokenSyntax)) + + let nonIdentifierToken = try XCTUnwrap(DeclSyntax("let a = 1").firstToken(viewMode: .all)) + XCTAssertNil(nonIdentifierToken.identifier) + } +} diff --git a/Tests/SwiftSyntaxTest/MultithreadingTests.swift b/Tests/SwiftSyntaxTest/MultithreadingTests.swift index b2f753a5975..9083e5ca400 100644 --- a/Tests/SwiftSyntaxTest/MultithreadingTests.swift +++ b/Tests/SwiftSyntaxTest/MultithreadingTests.swift @@ -20,8 +20,9 @@ extension SyntaxProtocol { } } -class MultithreadingTests: XCTestCase { - +// Marked as `@unchecked Sendable` to work around rdar://130094927, which complains about `MultithreadingTests` not conforming to +// `Sendable`. +class MultithreadingTests: XCTestCase, @unchecked Sendable { public func testPathological() { let tuple = TupleTypeSyntax( leftParen: .leftParenToken(), diff --git a/Tests/SwiftSyntaxTest/SourceLocationConverterTests.swift b/Tests/SwiftSyntaxTest/SourceLocationConverterTests.swift index bdc196b8d09..b2144e13f98 100644 --- a/Tests/SwiftSyntaxTest/SourceLocationConverterTests.swift +++ b/Tests/SwiftSyntaxTest/SourceLocationConverterTests.swift @@ -174,11 +174,39 @@ final class SourceLocationConverterTests: XCTestCase { ) } + func testMultiLineDirective() { + assertPresumedSourceLocation( + #""" + #sourceLocation( + file: "input.swift", + line: 10 + ) + + let a = 2 + """#, + presumedFile: "input.swift", + presumedLine: 11 + ) + } + + func testDirectiveWithTrailingBlockComment() { + assertPresumedSourceLocation( + #""" + #sourceLocation(file: "input.swift", line: 10) /* + comment + */ + + let a = 2 + """#, + presumedFile: "input.swift", + presumedLine: 13 + ) + } func testMultiLineStringLiteralAsFilename() { // FIXME: The current parser handles this fine but it’s a really bogus filename. // We ignore the directive because the multi-line string literal contains multiple segments. // We should probably justs disallow multi-line string literals for the `file` argument. - // cf https://github.com/apple/swift-syntax/issues/1831 + // cf https://github.com/swiftlang/swift-syntax/issues/1831 assertPresumedSourceLocation( #""" #sourceLocation(file: """ 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/SyntaxTests.swift b/Tests/SwiftSyntaxTest/SyntaxTests.swift index c59b4df4955..30055ef9817 100644 --- a/Tests/SwiftSyntaxTest/SyntaxTests.swift +++ b/Tests/SwiftSyntaxTest/SyntaxTests.swift @@ -146,4 +146,26 @@ class SyntaxTests: XCTestCase { let node = ClosureCaptureSyntax(name: "test", expression: ExprSyntax("123")) XCTAssertEqual(node.formatted().description, "test = 123") } + + func testShareSyntaxIndexInTreeBetweenTrees() throws { + let source = "func foo() {}" + + let tree1 = DeclSyntax(stringLiteral: source) + let tree2 = DeclSyntax(stringLiteral: source) + + let funcKeywordInTree1 = try XCTUnwrap(tree1.firstToken(viewMode: .sourceAccurate)) + XCTAssertEqual(funcKeywordInTree1.tokenKind, .keyword(.func)) + + let opaqueIndexInTree1 = funcKeywordInTree1.id.indexInTree.toOpaque() + + let funcKeywordIdentifierInTree2 = try XCTUnwrap( + SyntaxIdentifier.fromIndexInTree( + SyntaxIdentifier.SyntaxIndexInTree(fromOpaque: opaqueIndexInTree1), + relativeToRoot: tree2 + ) + ) + let funcKeywordInTree2 = tree2.node(at: funcKeywordIdentifierInTree2) + XCTAssertEqual(funcKeywordInTree2?.as(TokenSyntax.self)?.tokenKind, .keyword(.func)) + XCTAssertNotEqual(funcKeywordInTree1.id, funcKeywordInTree2?.id) + } } 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") diff --git a/cmake/modules/AddSwiftHostLibrary.cmake b/cmake/modules/AddSwiftHostLibrary.cmake index f3858efb584..a55053de6e6 100644 --- a/cmake/modules/AddSwiftHostLibrary.cmake +++ b/cmake/modules/AddSwiftHostLibrary.cmake @@ -61,9 +61,15 @@ function(add_swift_syntax_library name) add_custom_command( TARGET ${name} POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E touch_nocreate $ $ "${module_base}" + COMMAND "${CMAKE_COMMAND}" -E touch_nocreate $ "${module_base}" COMMAND_EXPAND_LISTS COMMENT "Update mtime of library outputs workaround") + add_custom_command( + TARGET ${name} + POST_BUILD + COMMAND "${CMAKE_COMMAND}" -E touch_nocreate $ + COMMAND_EXPAND_LISTS + COMMENT "Update mtime of objcect files workaround") # Install the Swift module into the appropriate location. set_target_properties(${name} @@ -81,6 +87,25 @@ function(add_swift_syntax_library name) -emit-module-interface-path;${module_interface_file}; -emit-private-module-interface-path;${module_private_interface_file} >) + + # Enable package CMO if possible. + if(SWIFT_PACKAGE_CMO_SUPPORT STREQUAL "IMPLEMENTED") + target_compile_options("${name}" PRIVATE + $<$: + "SHELL:-package-name ${SWIFT_MODULE_ABI_NAME_PREFIX}${PROJECT_NAME}" + "SHELL:-Xfrontend -package-cmo" + "SHELL:-Xfrontend -allow-non-resilient-access" + >) + elseif(SWIFT_PACKAGE_CMO_SUPPORT STREQUAL "EXPERIMENTAL") + target_compile_options("${name}" PRIVATE + $<$: + "SHELL:-package-name ${SWIFT_MODULE_ABI_NAME_PREFIX}${PROJECT_NAME}" + "SHELL:-Xfrontend -experimental-package-cmo" + "SHELL:-Xfrontend -experimental-allow-non-resilient-access" + "SHELL:-Xfrontend -experimental-package-bypass-resilience" + >) + endif() + if(SWIFT_MODULE_ABI_NAME_PREFIX) # ABI name prefix. this can be used to avoid name conflicts. target_compile_options("${name}" PRIVATE @@ -130,7 +155,7 @@ function(add_swift_syntax_library name) endif() endif() - if(PROJECT_IS_TOP_LEVEL) + if(PROJECT_IS_TOP_LEVEL OR SWIFT_SYNTAX_INSTALL_TARGETS) # Install this target install(TARGETS ${name} EXPORT SwiftSyntaxTargets @@ -148,4 +173,5 @@ function(add_swift_syntax_library name) else() set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS ${name}) endif() + add_library(SwiftSyntax::${name} ALIAS ${name}) endfunction() diff --git a/cmake/modules/CMakeLists.txt b/cmake/modules/CMakeLists.txt index bb98e4ba873..e29130c8b4e 100644 --- a/cmake/modules/CMakeLists.txt +++ b/cmake/modules/CMakeLists.txt @@ -1,4 +1,4 @@ -if(PROJECT_IS_TOP_LEVEL) +if(PROJECT_IS_TOP_LEVEL OR SWIFT_SYNTAX_INSTALL_TARGETS) export(EXPORT SwiftSyntaxTargets FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftSyntaxConfig.cmake NAMESPACE SwiftSyntax::) diff --git a/cmake/modules/SwiftCompilerCapability.cmake b/cmake/modules/SwiftCompilerCapability.cmake new file mode 100644 index 00000000000..d62e387184f --- /dev/null +++ b/cmake/modules/SwiftCompilerCapability.cmake @@ -0,0 +1,70 @@ + +# Test if the Swift compiler returns success for supplied compiler arguments.... +function(swift_supports_compiler_arguments out_var) + file(WRITE "${CMAKE_BINARY_DIR}/tmp/dummy.swift" "") + execute_process( + COMMAND "${CMAKE_Swift_COMPILER}" -parse ${ARGN} - + INPUT_FILE "${CMAKE_BINARY_DIR}/tmp/dummy.swift" + OUTPUT_QUIET ERROR_QUIET + RESULT_VARIABLE result + ) + if(NOT result) + set("${out_var}" "TRUE" PARENT_SCOPE) + else() + set("${out_var}" "FALSE" PARENT_SCOPE) + endif() +endfunction() + +# Test if the Swift compiler supports -disable-implicit--module-import. +macro(swift_supports_implicit_module module_name out_var) + swift_supports_compiler_arguments(${out_var} + -Xfrontend -disable-implicit-${module_name}-module-import + ) +endmacro() + +function(swift_get_swiftlang_version out_var) + execute_process( + COMMAND "${CMAKE_Swift_COMPILER}" -version + OUTPUT_VARIABLE output ERROR_VARIABLE output + RESULT_VARIABLE result + TIMEOUT 10 + ) + + if(output MATCHES [[swiftlang-([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)]]) + set("${out_var}" "${CMAKE_MATCH_1}" PARENT_SCOPE) + endif() +endfunction() + +# Get "package cross-module-optimization" compiler arguments suitable for the compiler. +function(swift_get_package_cmo_support out_var) + # > 6.0 : Fixed feature. + swift_supports_compiler_arguments(result + -package-name my-package + -Xfrontend -package-cmo + -Xfrontend -allow-non-resilient-access + ) + if(result) + set(${out_var} IMPLEMENTED PARENT_SCOPE) + return() + endif() + + # == 6.0 : Experimental. + swift_supports_compiler_arguments(result + -package-name my-package + -Xfrontend -experimental-package-cmo + -Xfrontend -experimental-allow-non-resilient-access + -Xfrontend -experimental-package-bypass-resilience + ) + if(result) + # Package CMO is implmented in Xcode 16 Beta 4 (swiftlang-6.0.0.6.8) or later. + # Consider it's not supported in non Xcode toolchain with "-experimental" options. + swift_get_swiftlang_version(swiftlang_version) + if(swiftlang_version AND swiftlang_version VERSION_GREATER_EQUAL 6.0.0.6) + set(${out_var} EXPERIMENTAL PARENT_SCOPE) + return() + endif() + endif() + + # < 6.0 : Not supported. + set(${out_var} NO PARENT_SCOPE) +endfunction() diff --git a/utils/bazel/swift_syntax_library.bzl b/utils/bazel/swift_syntax_library.bzl index fe9cd90aa64..db53a486171 100644 --- a/utils/bazel/swift_syntax_library.bzl +++ b/utils/bazel/swift_syntax_library.bzl @@ -1,12 +1,13 @@ """Convenience wrapper for swift_library targets using this repo's conventions""" -load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") +load("@build_bazel_rules_apple//apple:ios.bzl", "ios_unit_test") +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library", "swift_test") load(":opt_wrapper.bzl", "opt_wrapper") -def swift_syntax_library(name, deps, testonly = False): +def swift_syntax_library(name, deps, srcs = None, testonly = False): swift_library( name = name, - srcs = native.glob( + srcs = srcs or native.glob( ["Sources/{}/**/*.swift".format(name)], exclude = ["**/*.docc/**"], allow_empty = False, @@ -21,3 +22,38 @@ def swift_syntax_library(name, deps, testonly = False): dep = name, testonly = testonly, ) + +def swift_syntax_test(name, deps): + srcs = native.glob( + ["Tests/{}/**/*.swift".format(name)], + # These tests load source files they don't have access to in the iOS test bundle with bazel. + exclude = ["**/StringLiteralRepresentedLiteralValueTests.swift"], + allow_empty = False, + ) + + swift_test( + name = name, + srcs = srcs, + module_name = name, + deps = deps, + testonly = True, + data = srcs, + ) + + swift_library( + name = name + ".library", + srcs = srcs, + module_name = name, + tags = ["manual"], + deps = deps, + testonly = True, + ) + + ios_unit_test( + name = name + ".ios", + deps = [name + ".library"], + # Keep in sync with Package.swift + minimum_os_version = "13.0", + tags = ["exclusive"], + runner = "//:ios_test_runner", + )