├── .bazelrc ├── .bazelversion ├── .editorconfig ├── .gitattributes ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── BASICFORMAT_BUG.yml │ ├── BUG_REPORT.yml │ ├── FEATURE_REQUEST.yml │ ├── PARSER_BUG.yml │ └── config.yml └── workflows │ ├── automerge.yml │ ├── publish_release.yml │ └── pull_request.yml ├── .gitignore ├── .license_header_template ├── .licenseignore ├── .spi.yml ├── .swift-format ├── BUILD.bazel ├── CMakeLists.txt ├── CONTRIBUTING.md ├── Changelog.md ├── CodeGeneration ├── Package.swift ├── README.md ├── Sources │ ├── SyntaxSupport │ │ ├── AttributeNodes.swift │ │ ├── AvailabilityNodes.swift │ │ ├── BuilderInitializableTypes.swift │ │ ├── Child.swift │ │ ├── CommonNodes.swift │ │ ├── CompatibilityLayer.swift │ │ ├── CompilerNodes.swift │ │ ├── DeclNodes.swift │ │ ├── ExperimentalFeatures.swift │ │ ├── ExprNodes.swift │ │ ├── GenericNodes.swift │ │ ├── GrammarGenerator.swift │ │ ├── IdentifierConvertible.swift │ │ ├── InitSignature.swift │ │ ├── KeywordSpec.swift │ │ ├── Node.swift │ │ ├── NodeChoiceConvertible.swift │ │ ├── PatternNodes.swift │ │ ├── RawSyntaxNodeKind.swift │ │ ├── StmtNodes.swift │ │ ├── String+Extensions.swift │ │ ├── SyntaxNodeKind.swift │ │ ├── SyntaxNodes.swift │ │ ├── TokenSpec.swift │ │ ├── Traits.swift │ │ ├── Trivia.swift │ │ ├── TypeConvertible.swift │ │ ├── TypeNodes.swift │ │ └── Utils.swift │ ├── Utils │ │ ├── CodeGenerationFormat.swift │ │ ├── CopyrightHeader.swift │ │ ├── SyntaxBuildableChild.swift │ │ ├── SyntaxBuildableNode.swift │ │ ├── SyntaxBuildableType.swift │ │ └── Utils.swift │ └── generate-swift-syntax │ │ ├── ChildNodeChoices.swift │ │ ├── GenerateSwiftSyntax.swift │ │ ├── ImportSwiftSyntax.swift │ │ ├── InitSignature+Extensions.swift │ │ └── templates │ │ ├── swiftparser │ │ ├── ExperimentalFeaturesFile.swift │ │ ├── IsLexerClassifiedFile.swift │ │ ├── LayoutNodesParsableFile.swift │ │ ├── ParserTokenSpecSetFile.swift │ │ └── TokenSpecStaticMembersFile.swift │ │ ├── swiftparserdiagnostics │ │ ├── ChildNameForDiagnosticsFile.swift │ │ ├── SyntaxKindNameForDiagnosticsFile.swift │ │ └── TokenNameForDiagnosticsFile.swift │ │ ├── swiftsyntax │ │ ├── ChildNameForKeyPathFile.swift │ │ ├── KeywordFile.swift │ │ ├── RawSyntaxNodesFile.swift │ │ ├── RawSyntaxValidationFile.swift │ │ ├── RenamedChildrenCompatibilityFile.swift │ │ ├── RenamedSyntaxNodesFile.swift │ │ ├── SwiftSyntaxDoccIndex.swift │ │ ├── SwiftSyntaxDoccIndexTemplate.md │ │ ├── SyntaxAnyVisitorFile.swift │ │ ├── SyntaxBaseNodesFile.swift │ │ ├── SyntaxCollectionsFile.swift │ │ ├── SyntaxEnumFile.swift │ │ ├── SyntaxKindFile.swift │ │ ├── SyntaxNodeCasting.swift │ │ ├── SyntaxNodesFile.swift │ │ ├── SyntaxRewriterFile.swift │ │ ├── SyntaxTraitsFile.swift │ │ ├── SyntaxVisitorFile.swift │ │ ├── TokenKindFile.swift │ │ ├── TokensFile.swift │ │ └── TriviaPiecesFile.swift │ │ └── swiftsyntaxbuilder │ │ ├── BuildableNodesFile.swift │ │ ├── RenamedChildrenBuilderCompatibilityFile.swift │ │ ├── ResultBuildersFile.swift │ │ └── SyntaxExpressibleByStringInterpolationConformancesFile.swift └── Tests │ └── ValidateSyntaxNodes │ ├── Utils.swift │ ├── ValidateSyntaxNodes.swift │ └── ValidationFailure.swift ├── Contributor Documentation ├── API Breakage Checks.md ├── Changing Swift Syntax.md ├── Environment variables.md ├── Filing Parser Bug Reports.md ├── Fixing Bugs.md ├── Parser Design.md ├── Parser Recovery.md ├── Parsing Basics.md ├── README.md ├── RFC Process.md ├── SPI Attribute.md └── When to use protocols in SwiftSyntax.md ├── EditorExtension ├── Host │ ├── Assets.xcassets │ │ └── AppIcon.appiconset │ │ │ └── Contents.json │ ├── HostApp.swift │ └── Info.plist ├── README.md ├── SwiftRefactorExtension.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── xcshareddata │ │ └── xcschemes │ │ └── SwiftRefactorExtension.xcscheme └── SwiftRefactorExtension │ ├── Bridge.h │ ├── CommandDiscovery.swift │ ├── Info.plist │ ├── RefactoringRegistry.swift │ ├── SourceEditorCommand.swift │ ├── SourceEditorExtension.swift │ └── SwiftRefactorExtension.entitlements ├── Examples ├── Package.swift ├── README.md ├── Sources │ ├── AddOneToIntegerLiterals │ │ └── AddOneToIntegerLiterals.swift │ ├── CodeGenerationUsingSwiftSyntaxBuilder │ │ └── CodeGenerationUsingSwiftSyntaxBuilder.swift │ ├── Examples-all │ │ └── empty.swift │ └── MacroExamples │ │ ├── Implementation │ │ ├── Accessor │ │ │ └── EnvironmentValueMacro.swift │ │ ├── ComplexMacros │ │ │ ├── DictionaryIndirectionMacro.swift │ │ │ ├── ObservableMacro.swift │ │ │ └── OptionSetMacro.swift │ │ ├── Declaration │ │ │ └── FuncUniqueMacro.swift │ │ ├── Diagnostics.swift │ │ ├── Expression │ │ │ ├── AddBlocker.swift │ │ │ ├── FontLiteralMacro.swift │ │ │ ├── SourceLocationMacro.swift │ │ │ ├── StringifyMacro.swift │ │ │ ├── URLMacro.swift │ │ │ └── WarningMacro.swift │ │ ├── Extension │ │ │ ├── DefaultFatalErrorImplementationMacro.swift │ │ │ └── EquatableExtensionMacro.swift │ │ ├── Member │ │ │ ├── CaseDetectionMacro.swift │ │ │ ├── CustomCodable.swift │ │ │ ├── MetaEnumMacro.swift │ │ │ └── NewTypeMacro.swift │ │ ├── MemberAttribute │ │ │ ├── MemberDeprecatedMacro.swift │ │ │ └── WrapStoredPropertiesMacro.swift │ │ ├── Peer │ │ │ ├── AddAsyncMacro.swift │ │ │ ├── AddCompletionHandlerMacro.swift │ │ │ └── PeerValueWithSuffixNameMacro.swift │ │ └── Plugin.swift │ │ ├── Interface │ │ ├── AccessorMacros.swift │ │ ├── ComplexMacros.swift │ │ ├── DeclarationMacros.swift │ │ ├── ExpressionMacros.swift │ │ ├── ExtensionMacros.swift │ │ ├── MemberAttributeMacros.swift │ │ ├── MemberMacros.swift │ │ ├── PeerMacros.swift │ │ └── SourceLocationMacros.swift │ │ └── Playground │ │ ├── AccessorMacrosPlayground.swift │ │ ├── ComplexMacrosPlayground.swift │ │ ├── DeclarationMacrosPlayground.swift │ │ ├── ExpressionMacrosPlayground.swift │ │ ├── ExtensionMacrosPlayground.swift │ │ ├── MemberAttributeMacrosPlayground.swift │ │ ├── MemberMacrosPlayground.swift │ │ ├── PeerMacrosPlayground.swift │ │ ├── SourceLocationMacrosPlayground.swift │ │ └── main.swift └── Tests │ ├── Dummy │ └── Empty.swift │ └── MacroExamples │ └── Implementation │ ├── Accessor │ └── EnvironmentValueMacroTests.swift │ ├── ComplexMacros │ ├── DictionaryIndirectionMacroTests.swift │ ├── ObservableMacroTests.swift │ └── OptionSetMacroTests.swift │ ├── Declaration │ └── FuncUniqueMacroTests.swift │ ├── Expression │ ├── AddBlockerTests.swift │ ├── FontLiteralMacroTests.swift │ ├── StringifyMacroTests.swift │ ├── URLMacroTests.swift │ └── WarningMacroTests.swift │ ├── Extension │ ├── DefaultFatalErrorImplementationMacroTests.swift │ └── EquatableExtensionMacroTests.swift │ ├── Member │ ├── CaseDetectionMacroTests.swift │ ├── CustomCodableTests.swift │ ├── MetaEnumMacroTests.swift │ └── NewTypeMacroTests.swift │ ├── MemberAttribute │ ├── MemberDeprecatedMacroTests.swift │ └── WrapStoredPropertiesMacroTests.swift │ └── Peer │ ├── AddAsyncMacroTests.swift │ ├── AddCompletionHandlerMacroTests.swift │ └── PeerValueWithSuffixNameMacroTests.swift ├── LICENSE.txt ├── MODULE.bazel ├── Package.swift ├── README.md ├── Release Notes ├── 510.md ├── 600.md ├── 601.md └── 602.md ├── Sources ├── CMakeLists.txt ├── SwiftBasicFormat │ ├── BasicFormat.swift │ ├── CMakeLists.txt │ ├── Indenter.swift │ ├── InferIndentation.swift │ ├── SwiftBasicFormat.docc │ │ ├── FilingBugReports.md │ │ └── Info.plist │ ├── Syntax+Extensions.swift │ ├── SyntaxProtocol+Formatted.swift │ └── Trivia+FormatExtensions.swift ├── SwiftCompilerPlugin │ ├── CMakeLists.txt │ └── CompilerPlugin.swift ├── SwiftCompilerPluginMessageHandling │ ├── CMakeLists.txt │ ├── CompilerPluginMessageHandler.swift │ ├── Diagnostics.swift │ ├── JSON │ │ ├── CodingUtilities.swift │ │ ├── JSON.swift │ │ ├── JSONDecoding.swift │ │ └── JSONEncoding.swift │ ├── LRUCache.swift │ ├── Macros.swift │ ├── PluginMacroExpansionContext.swift │ ├── PluginMessageCompatibility.swift │ ├── PluginMessages.swift │ └── StandardIOMessageConnection.swift ├── SwiftDiagnostics │ ├── CMakeLists.txt │ ├── Convenience.swift │ ├── Diagnostic.swift │ ├── DiagnosticDecorators │ │ ├── ANSIDiagnosticDecorator.swift │ │ ├── BasicDiagnosticDecorator.swift │ │ └── DiagnosticDecorator.swift │ ├── DiagnosticsFormatter.swift │ ├── FixIt.swift │ ├── GroupedDiagnostics.swift │ ├── Message.swift │ └── Note.swift ├── SwiftIDEUtils │ ├── CMakeLists.txt │ ├── DeclNameLocation.swift │ ├── FixItApplier.swift │ ├── NameMatcher.swift │ ├── SwiftIDEUtilsCompatibility.swift │ ├── Syntax+Classifications.swift │ ├── SyntaxClassification.swift │ ├── SyntaxClassifier.swift │ └── Utils.swift ├── SwiftIfConfig │ ├── ActiveClauseEvaluator.swift │ ├── ActiveSyntaxRewriter.swift │ ├── ActiveSyntaxVisitor.swift │ ├── BuildConfiguration.swift │ ├── CMakeLists.txt │ ├── ConfiguredRegions.swift │ ├── IfConfigDecl+IfConfig.swift │ ├── IfConfigDiagnostic.swift │ ├── IfConfigEvaluation.swift │ ├── IfConfigFunctions.swift │ ├── IfConfigRegionState.swift │ ├── SwiftIfConfig.docc │ │ ├── Info.plist │ │ └── SwiftIfConfig.md │ ├── SyntaxLiteralUtils.swift │ ├── SyntaxProtocol+IfConfig.swift │ ├── VersionTuple+Parsing.swift │ └── VersionTuple.swift ├── SwiftLexicalLookup │ ├── CMakeLists.txt │ ├── IdentifiableSyntax.swift │ ├── LookupConfig.swift │ ├── LookupName.swift │ ├── LookupResult.swift │ ├── Scopes │ │ ├── CanInterleaveResultsLaterScopeSyntax.swift │ │ ├── FunctionScopeSyntax.swift │ │ ├── GenericParameterScopeSyntax.swift │ │ ├── IntroducingToSequentialParentScopeSyntax.swift │ │ ├── LookInMembersScopeSyntax.swift │ │ ├── NominalTypeDeclSyntax.swift │ │ ├── ScopeImplementations.swift │ │ ├── ScopeSyntax.swift │ │ ├── SequentialScopeSyntax.swift │ │ └── WithGenericParametersScopeSyntax.swift │ ├── SimpleLookupQueries.swift │ └── SwiftLexicalLookup.docc │ │ ├── Info.plist │ │ ├── LookupRules.md │ │ └── SwiftLexicalLookup.md ├── SwiftLibraryPluginProvider │ ├── CMakeLists.txt │ └── LibraryPluginProvider.swift ├── SwiftOperators │ ├── CMakeLists.txt │ ├── Operator.swift │ ├── OperatorError+Diagnostics.swift │ ├── OperatorError.swift │ ├── OperatorTable+Defaults.swift │ ├── OperatorTable+Folding.swift │ ├── OperatorTable+Semantics.swift │ ├── OperatorTable.swift │ ├── PrecedenceGraph.swift │ ├── PrecedenceGroup.swift │ ├── SwiftOperators.docc │ │ ├── Info.plist │ │ └── SwiftOperators.md │ └── SyntaxSynthesis.swift ├── SwiftParser │ ├── Attributes.swift │ ├── Availability.swift │ ├── CMakeLists.txt │ ├── CharacterInfo.swift │ ├── CollectionNodes+Parsable.swift │ ├── CompilerFiles.swift │ ├── Declarations.swift │ ├── Directives.swift │ ├── ExpressionInterpretedAsVersionTuple.swift │ ├── Expressions.swift │ ├── IncrementalParseTransition.swift │ ├── IsValidIdentifier.swift │ ├── Lexer │ │ ├── Cursor.swift │ │ ├── Lexeme.swift │ │ ├── LexemeSequence.swift │ │ ├── Lexer.swift │ │ ├── RegexLiteralLexer.swift │ │ └── UnicodeScalarExtensions.swift │ ├── Lookahead.swift │ ├── LoopProgressCondition.swift │ ├── Modifiers.swift │ ├── Names.swift │ ├── Nominals.swift │ ├── Parameters.swift │ ├── ParseSourceFile.swift │ ├── Parser.swift │ ├── Patterns.swift │ ├── README.md │ ├── Recovery.swift │ ├── Specifiers.swift │ ├── Statements.swift │ ├── StringLiteralRepresentedLiteralValue.swift │ ├── StringLiterals.swift │ ├── SwiftParser.docc │ │ ├── Info.plist │ │ └── SwiftParser.md │ ├── SwiftParserCompatibility.swift │ ├── SwiftVersion.swift │ ├── SyntaxUtils.swift │ ├── TokenConsumer.swift │ ├── TokenPrecedence.swift │ ├── TokenSpec.swift │ ├── TokenSpecSet.swift │ ├── TopLevel.swift │ ├── TriviaParser.swift │ ├── Types.swift │ └── generated │ │ ├── ExperimentalFeatures.swift │ │ ├── IsLexerClassified.swift │ │ ├── LayoutNodes+Parsable.swift │ │ ├── Parser+TokenSpecSet.swift │ │ └── TokenSpecStaticMembers.swift ├── SwiftParserDiagnostics │ ├── CMakeLists.txt │ ├── DiagnosticExtensions.swift │ ├── LexerDiagnosticMessages.swift │ ├── MissingNodesError.swift │ ├── MissingTokenError.swift │ ├── MultiLineStringLiteralDiagnosticsGenerator.swift │ ├── ParseDiagnosticsGenerator.swift │ ├── ParserDiagnosticMessages.swift │ ├── PresenceUtils.swift │ ├── SyntaxExtensions.swift │ ├── Utils.swift │ └── generated │ │ ├── ChildNameForDiagnostics.swift │ │ ├── SyntaxKindNameForDiagnostics.swift │ │ └── TokenNameForDiagnostics.swift ├── SwiftRefactor │ ├── AddSeparatorsToIntegerLiteral.swift │ ├── CMakeLists.txt │ ├── CallToTrailingClosures.swift │ ├── ConvertComputedPropertyToStored.swift │ ├── ConvertComputedPropertyToZeroParameterFunction.swift │ ├── ConvertStoredPropertyToComputed.swift │ ├── ConvertZeroParameterFunctionToComputedProperty.swift │ ├── ExpandEditorPlaceholder.swift │ ├── FormatRawStringLiteral.swift │ ├── IntegerLiteralUtilities.swift │ ├── MigrateToNewIfLetSyntax.swift │ ├── OpaqueParameterToGeneric.swift │ ├── RefactoringProvider.swift │ ├── RemoveSeparatorsFromIntegerLiteral.swift │ └── SyntaxUtils.swift ├── SwiftSyntax-all │ └── empty.swift ├── SwiftSyntax │ ├── AbsolutePosition.swift │ ├── AbsoluteSyntaxInfo.swift │ ├── ArenaAllocatedBuffer.swift │ ├── Assert.swift │ ├── BumpPtrAllocator.swift │ ├── CMakeLists.txt │ ├── CommonAncestor.swift │ ├── Convenience.swift │ ├── CustomTraits.swift │ ├── Documentation.docc │ │ ├── Glossary.md │ │ ├── Info.plist │ │ ├── Macro Versioning.md │ │ ├── RawSyntaxValidation.md │ │ ├── Resources │ │ │ ├── Formatter.step1.swift │ │ │ ├── Formatter.step10.swift │ │ │ ├── Formatter.step11.swift │ │ │ ├── Formatter.step2.swift │ │ │ ├── Formatter.step3.swift │ │ │ ├── Formatter.step4.swift │ │ │ ├── Formatter.step5.swift │ │ │ ├── Formatter.step6.swift │ │ │ ├── Formatter.step7.swift │ │ │ ├── Formatter.step8.swift │ │ │ ├── Formatter.step9.swift │ │ │ ├── Package.step1.swift │ │ │ ├── Package.step2.swift │ │ │ ├── Package.step3.swift │ │ │ ├── Package.step4.swift │ │ │ ├── Package.step5.swift │ │ │ ├── importformatter-package-project.png │ │ │ ├── swift-syntax.png │ │ │ └── swift-syntax@2x.png │ │ ├── Tutorials │ │ │ ├── SwiftSyntax By Example.tutorial │ │ │ └── Tutorial Table of Contents.tutorial │ │ ├── Working with SwiftSyntax.md │ │ └── generated │ │ │ └── SwiftSyntax.md │ ├── EditorPlaceholder.swift │ ├── Identifier.swift │ ├── MemoryLayout.swift │ ├── MissingNodeInitializers.swift │ ├── Raw │ │ ├── RawSyntax.swift │ │ ├── RawSyntaxArena.swift │ │ ├── RawSyntaxLayoutView.swift │ │ ├── RawSyntaxNodeProtocol.swift │ │ └── RawSyntaxTokenView.swift │ ├── SourceEdit.swift │ ├── SourceLength.swift │ ├── SourceLocation.swift │ ├── SourcePresence.swift │ ├── SwiftSyntaxCompatibility.swift │ ├── Syntax.swift │ ├── SyntaxChildren.swift │ ├── SyntaxCollection.swift │ ├── SyntaxHashable.swift │ ├── SyntaxIdentifier.swift │ ├── SyntaxNodeStructure.swift │ ├── SyntaxProtocol.swift │ ├── SyntaxText.swift │ ├── SyntaxTreeViewMode.swift │ ├── TokenDiagnostic.swift │ ├── TokenSequence.swift │ ├── TokenSyntax.swift │ ├── Trivia.swift │ ├── Utils.swift │ └── generated │ │ ├── ChildNameForKeyPath.swift │ │ ├── Keyword.swift │ │ ├── RenamedChildrenCompatibility.swift │ │ ├── RenamedNodesCompatibility.swift │ │ ├── SyntaxAnyVisitor.swift │ │ ├── SyntaxBaseNodes.swift │ │ ├── SyntaxCollections.swift │ │ ├── SyntaxEnum.swift │ │ ├── SyntaxKind.swift │ │ ├── SyntaxRewriter.swift │ │ ├── SyntaxTraits.swift │ │ ├── SyntaxVisitor.swift │ │ ├── TokenKind.swift │ │ ├── Tokens.swift │ │ ├── TriviaPieces.swift │ │ ├── raw │ │ ├── RawSyntaxNodesAB.swift │ │ ├── RawSyntaxNodesC.swift │ │ ├── RawSyntaxNodesD.swift │ │ ├── RawSyntaxNodesEF.swift │ │ ├── RawSyntaxNodesGHI.swift │ │ ├── RawSyntaxNodesJKLMN.swift │ │ ├── RawSyntaxNodesOP.swift │ │ ├── RawSyntaxNodesQRS.swift │ │ ├── RawSyntaxNodesTUVWXYZ.swift │ │ └── RawSyntaxValidation.swift │ │ └── syntaxNodes │ │ ├── SyntaxNodesAB.swift │ │ ├── SyntaxNodesC.swift │ │ ├── SyntaxNodesD.swift │ │ ├── SyntaxNodesEF.swift │ │ ├── SyntaxNodesGHI.swift │ │ ├── SyntaxNodesJKLMN.swift │ │ ├── SyntaxNodesOP.swift │ │ ├── SyntaxNodesQRS.swift │ │ └── SyntaxNodesTUVWXYZ.swift ├── SwiftSyntaxBuilder │ ├── CMakeLists.txt │ ├── ConvenienceInitializers.swift │ ├── DeclSyntaxParseable.swift │ ├── Documentation.docc │ │ └── Index.md │ ├── Indenter.swift │ ├── ListBuilder.swift │ ├── ResultBuilderExtensions.swift │ ├── SwiftSyntaxBuilderCompatibility.swift │ ├── Syntax+StringInterpolation.swift │ ├── SyntaxNodeWithBody.swift │ ├── SyntaxParsable+ExpressibleByStringInterpolation.swift │ ├── ValidatingSyntaxNodes.swift │ ├── WithTrailingCommaSyntax+EnsuringTrailingComma.swift │ └── generated │ │ ├── BuildableNodes.swift │ │ ├── RenamedChildrenBuilderCompatibility.swift │ │ ├── ResultBuilders.swift │ │ └── SyntaxExpressibleByStringInterpolationConformances.swift ├── SwiftSyntaxMacroExpansion │ ├── BasicMacroExpansionContext.swift │ ├── CMakeLists.txt │ ├── FunctionParameterUtils.swift │ ├── IndentationUtils.swift │ ├── MacroArgument.swift │ ├── MacroExpansion.swift │ ├── MacroExpansionDiagnosticMessages.swift │ ├── MacroReplacement.swift │ ├── MacroSpec.swift │ └── MacroSystem.swift ├── SwiftSyntaxMacros │ ├── AbstractSourceLocation.swift │ ├── CMakeLists.txt │ ├── MacroExpansionContext.swift │ ├── MacroExpansionDiagnosticMessages.swift │ ├── MacroProtocols │ │ ├── AccessorMacro.swift │ │ ├── AttachedMacro.swift │ │ ├── BodyMacro.swift │ │ ├── CodeItemMacro.swift │ │ ├── DeclarationMacro.swift │ │ ├── ExpressionMacro.swift │ │ ├── ExtensionMacro.swift │ │ ├── FreestandingMacro.swift │ │ ├── Macro+Format.swift │ │ ├── Macro.swift │ │ ├── MemberAttributeMacro.swift │ │ ├── MemberMacro.swift │ │ ├── PeerMacro.swift │ │ └── PreambleMacro.swift │ ├── SwiftSyntaxMacros.docc │ │ ├── Info.plist │ │ └── SwiftSyntaxMacros.md │ └── Syntax+LexicalContext.swift ├── SwiftSyntaxMacrosGenericTestSupport │ └── Assertions.swift ├── SwiftSyntaxMacrosTestSupport │ └── Assertions.swift ├── VersionMarkerModules │ ├── CMakeLists.txt │ ├── SwiftSyntax509 │ │ └── Empty.swift │ ├── SwiftSyntax510 │ │ └── Empty.swift │ ├── SwiftSyntax600 │ │ └── Empty.swift │ ├── SwiftSyntax601 │ │ └── Empty.swift │ ├── SwiftSyntax602 │ │ └── Empty.swift │ └── SwiftSyntax603 │ │ └── Empty.swift ├── _InstructionCounter │ ├── include │ │ └── InstructionsExecuted.h │ └── src │ │ └── InstructionsExecuted.c ├── _SwiftLibraryPluginProviderCShims │ ├── CMakeLists.txt │ ├── LoadLibrary.c │ └── include │ │ ├── LoadLibrary.h │ │ └── module.modulemap ├── _SwiftSyntaxCShims │ ├── CMakeLists.txt │ ├── PlatformMutex.c │ └── include │ │ ├── Atomics.h │ │ ├── PlatformMutex.h │ │ ├── SwiftSyntaxCShims.h │ │ ├── _bridging.h │ │ ├── _includes.h │ │ ├── module.modulemap │ │ ├── swiftsyntax_errno.h │ │ └── swiftsyntax_stdio.h ├── _SwiftSyntaxGenericTestSupport │ ├── AssertEqualWithDiff.swift │ └── String+TrimmingTrailingWhitespace.swift └── _SwiftSyntaxTestSupport │ ├── AssertEqualWithDiff.swift │ ├── IncrementalParseTestUtils.swift │ ├── LocationMarkers.swift │ ├── LongTestsDisabled.swift │ ├── Syntax+Assertions.swift │ ├── SyntaxComparison.swift │ └── SyntaxProtocol+Initializer.swift ├── SwiftParserCLI ├── Package.swift ├── README.md └── Sources │ ├── InstructionCounter │ ├── include │ │ └── InstructionsExecuted.h │ └── src │ │ └── InstructionsExecuted.c │ └── swift-parser-cli │ ├── BasicFormat.swift │ ├── Commands │ ├── PerformanceTest.swift │ ├── PrintDiags.swift │ ├── PrintTree.swift │ ├── Reduce.swift │ └── VerifyRoundTrip.swift │ ├── ParseCommand.swift │ ├── SyntaxUtils.swift │ ├── TerminalUtils.swift │ ├── Utils.swift │ └── swift-parser-cli.swift ├── SwiftSyntaxDevUtils ├── Package.swift ├── README.md └── Sources │ └── swift-syntax-dev-utils │ ├── SwiftSyntaxDevUtils.swift │ ├── commands │ ├── Build.swift │ ├── GenerateSourceCode.swift │ ├── LocalPrPrecheck.swift │ ├── Test.swift │ └── VerifySourceCode.swift │ └── common │ ├── BuildArguments.swift │ ├── Logger.swift │ ├── Paths.swift │ ├── ProcessRunner.swift │ ├── ScriptExectutionError.swift │ ├── SourceCodeGeneratorArguments.swift │ ├── SwiftPMBuilder.swift │ └── Utils.swift ├── Tests ├── PerformanceTest │ ├── Inputs │ │ └── MinimalCollections.swift.input │ ├── InstructionsCountAssertion.swift │ ├── ParsingPerformanceTests.swift │ ├── SyntaxClassifierPerformanceTests.swift │ └── VisitorPerformanceTests.swift ├── SwiftBasicFormatTest │ ├── BasicFormatTests.swift │ ├── IndentTests.swift │ └── InferIndentationTests.swift ├── SwiftCompilerPluginTest │ ├── CompilerPluginTests.swift │ ├── JSONTests.swift │ └── LRUCacheTests.swift ├── SwiftDiagnosticsTest │ ├── DiagnosticDecorators │ │ ├── ANSIDiagnosticDecoratorTests.swift │ │ └── BasicDiagnosticDecoratorTests.swift │ ├── DiagnosticFormatterTests.swift │ ├── DiagnosticTestingUtils.swift │ ├── FixItTests.swift │ ├── GroupDiagnosticsFormatterTests.swift │ └── ParserDiagnosticsFormatterIntegrationTests.swift ├── SwiftIDEUtilsTest │ ├── Assertions.swift │ ├── ClassificationTests.swift │ └── NameMatcherTests.swift ├── SwiftIfConfigTest │ ├── ActiveRegionTests.swift │ ├── EvaluateTests.swift │ ├── TestingBuildConfiguration.swift │ └── VisitorTests.swift ├── SwiftLexicalLookupTest │ ├── Assertions.swift │ ├── ExpectedName.swift │ ├── MarkerExpectation.swift │ ├── NameLookupTests.swift │ ├── ResultExpectation.swift │ └── SimpleQueryTests.swift ├── SwiftOperatorsTest │ ├── OperatorTableTests.swift │ └── SyntaxSynthesisTests.swift ├── SwiftParserDiagnosticsTest │ └── DiagnosticInfrastructureTests.swift ├── SwiftParserTest │ ├── AbsolutePositionTests.swift │ ├── Assertions.swift │ ├── AttributeTests.swift │ ├── AvailabilityTests.swift │ ├── DeclarationTests.swift │ ├── DirectiveTests.swift │ ├── DoExpressionTests.swift │ ├── ExpressionInterpretedAsVersionTupleTests.swift │ ├── ExpressionTests.swift │ ├── ExpressionTypeTests.swift │ ├── IncrementalParsingTests.swift │ ├── IsValidIdentifierTests.swift │ ├── LexerTests.swift │ ├── Parser+EntryTests.swift │ ├── ParserTestCase.swift │ ├── ParserTests.swift │ ├── PatternTests.swift │ ├── RegexLiteralTests.swift │ ├── SendingTest.swift │ ├── SequentialToConcurrentEditTranslationTests.swift │ ├── StatementTests.swift │ ├── StringLiteralRepresentedLiteralValueTests.swift │ ├── ThenStatementTests.swift │ ├── TrailingCommaTests.swift │ ├── TriviaParserTests.swift │ ├── TypeCompositionTests.swift │ ├── TypeMemberTests.swift │ ├── TypeMetatypeTests.swift │ ├── TypeTests.swift │ ├── Utils.swift │ ├── ValueGenericsTests.swift │ ├── VariadicGenericsTests.swift │ └── translated │ │ ├── ActorTests.swift │ │ ├── AlwaysEmitConformanceMetadataAttrTests.swift │ │ ├── AsyncSyntaxTests.swift │ │ ├── AsyncTests.swift │ │ ├── AvailabilityQueryTests.swift │ │ ├── AvailabilityQueryUnavailabilityTests.swift │ │ ├── BorrowExprTests.swift │ │ ├── BraceRecoveryEofTests.swift │ │ ├── BuiltinBridgeObjectTests.swift │ │ ├── BuiltinWordTests.swift │ │ ├── ConflictMarkersTests.swift │ │ ├── ConsecutiveStatementsTests.swift │ │ ├── CopyExprTests.swift │ │ ├── DebuggerTests.swift │ │ ├── DelayedExtensionTests.swift │ │ ├── DeprecatedWhereTests.swift │ │ ├── DiagnoseAvailabilityTests.swift │ │ ├── DiagnoseAvailabilityWindowsTests.swift │ │ ├── DiagnoseDynamicReplacementTests.swift │ │ ├── DiagnoseInitializerAsTypedPatternTests.swift │ │ ├── DiagnosticMissingFuncKeywordTests.swift │ │ ├── DollarIdentifierTests.swift │ │ ├── EffectfulPropertiesTests.swift │ │ ├── EnumElementPatternSwift4Tests.swift │ │ ├── EnumTests.swift │ │ ├── ErrorsTests.swift │ │ ├── EscapedIdentifiersTests.swift │ │ ├── ForeachAsyncTests.swift │ │ ├── ForeachTests.swift │ │ ├── ForwardSlashRegexSkippingAllowedTests.swift │ │ ├── ForwardSlashRegexSkippingInvalidTests.swift │ │ ├── ForwardSlashRegexSkippingTests.swift │ │ ├── ForwardSlashRegexTests.swift │ │ ├── GenericDisambiguationTests.swift │ │ ├── GuardTests.swift │ │ ├── GuardTopLevelTests.swift │ │ ├── HashbangLibraryTests.swift │ │ ├── HashbangMainTests.swift │ │ ├── IdentifiersTests.swift │ │ ├── IfconfigExprTests.swift │ │ ├── ImplicitGetterIncompleteTests.swift │ │ ├── InitDeinitTests.swift │ │ ├── InvalidIfExprTests.swift │ │ ├── InvalidStringInterpolationProtocolTests.swift │ │ ├── InvalidTests.swift │ │ ├── MatchingPatternsTests.swift │ │ ├── MetatypeObjectConversionTests.swift │ │ ├── MoveExprTests.swift │ │ ├── MultilineErrorsTests.swift │ │ ├── MultilinePoundDiagnosticArgRdar41154797Tests.swift │ │ ├── MultilineStringTests.swift │ │ ├── NoimplicitcopyAttrTests.swift │ │ ├── NumberIdentifierErrorsTests.swift │ │ ├── ObjcEnumTests.swift │ │ ├── ObjectLiteralsTests.swift │ │ ├── OperatorDeclDesignatedTypesTests.swift │ │ ├── OperatorDeclTests.swift │ │ ├── OperatorsTests.swift │ │ ├── OptionalChainLvaluesTests.swift │ │ ├── OptionalLvaluesTests.swift │ │ ├── OptionalTests.swift │ │ ├── OriginalDefinedInAttrTests.swift │ │ ├── PatternWithoutVariablesScriptTests.swift │ │ ├── PatternWithoutVariablesTests.swift │ │ ├── PlaygroundLvaluesTests.swift │ │ ├── PoundAssertTests.swift │ │ ├── PrefixSlashTests.swift │ │ ├── RawStringErrorsTests.swift │ │ ├── RawStringTests.swift │ │ ├── RecoveryLibraryTests.swift │ │ ├── RecoveryTests.swift │ │ ├── RegexParseEndOfBufferTests.swift │ │ ├── RegexParseErrorTests.swift │ │ ├── RegexTests.swift │ │ ├── ResultBuilderTests.swift │ │ ├── SelfRebindingTests.swift │ │ ├── SemicolonTests.swift │ │ ├── StringLiteralEofTests.swift │ │ ├── SubscriptingTests.swift │ │ ├── SuperTests.swift │ │ ├── SwitchIncompleteTests.swift │ │ ├── SwitchTests.swift │ │ ├── ToplevelLibraryTests.swift │ │ ├── TrailingClosuresTests.swift │ │ ├── TrailingSemiTests.swift │ │ ├── TryTests.swift │ │ ├── TypeExprTests.swift │ │ ├── TypealiasTests.swift │ │ └── UnclosedStringInterpolationTests.swift ├── SwiftRefactorTest │ ├── CallToTrailingClosureTests.swift │ ├── ConvertComputedPropertyToStoredTest.swift │ ├── ConvertComputedPropertyToZeroParameterFunctionTests.swift │ ├── ConvertStoredPropertyToComputedTest.swift │ ├── ConvertZeroParameterFunctionToComputedPropertyTests.swift │ ├── ExpandEditorPlaceholderTests.swift │ ├── FormatRawStringLiteral.swift │ ├── IntegerLiteralUtilities.swift │ ├── MigrateToNewIfLetSyntax.swift │ ├── OpaqueParameterToGeneric.swift │ ├── RefactorTestUtils.swift │ └── ReformatIntegerLiteral.swift ├── SwiftSyntaxBuilderTest │ ├── AccessorDeclTests.swift │ ├── ArrayExprTests.swift │ ├── Assertions.swift │ ├── AttributeListSyntaxTests.swift │ ├── BooleanLiteralTests.swift │ ├── BreakStmtSyntaxTests.swift │ ├── ClassDeclSyntaxTests.swift │ ├── ClosureExprTests.swift │ ├── CollectionNodeFlatteningTests.swift │ ├── CustomAttributeTests.swift │ ├── DictionaryExprTests.swift │ ├── DoStmtTests.swift │ ├── EnumCaseElementTests.swift │ ├── ExprListTests.swift │ ├── ExtensionDeclTests.swift │ ├── FloatLiteralTests.swift │ ├── ForInStmtTests.swift │ ├── FunctionParameterSyntaxTests.swift │ ├── FunctionSignatureSyntaxTests.swift │ ├── FunctionTests.swift │ ├── FunctionTypeSyntaxTests.swift │ ├── IfConfigDeclSyntaxTests.swift │ ├── IfStmtTests.swift │ ├── ImportDeclSyntaxTests.swift │ ├── InitializerDeclTests.swift │ ├── IntegerLiteralTests.swift │ ├── LabeledExprSyntaxTests.swift │ ├── ProtocolDeclTests.swift │ ├── ReturnStmsTests.swift │ ├── SourceFileTests.swift │ ├── StringInterpolationTests.swift │ ├── StringLiteralExprSyntaxTests.swift │ ├── StructTests.swift │ ├── SwitchCaseLabelSyntaxTests.swift │ ├── SwitchTests.swift │ ├── TernaryExprTests.swift │ ├── TriviaTests.swift │ ├── TupleTests.swift │ └── VariableTests.swift ├── SwiftSyntaxMacroExpansionTest │ ├── AccessorMacroTests.swift │ ├── AttributeRemoverTests.swift │ ├── BodyMacroTests.swift │ ├── CodeItemMacroTests.swift │ ├── DeclarationMacroTests.swift │ ├── ExpressionMacroTests.swift │ ├── ExtensionMacroTests.swift │ ├── LexicalContextTests.swift │ ├── MacroArgumentTests.swift │ ├── MacroReplacementTests.swift │ ├── MemberAttributeMacroTests.swift │ ├── MemberMacroTests.swift │ ├── MultiRoleMacroTests.swift │ ├── PeerMacroTests.swift │ ├── PreambleMacroTests.swift │ └── StringInterpolationErrorTests.swift ├── SwiftSyntaxMacrosTestSupportTests │ └── AssertionsTests.swift ├── SwiftSyntaxTest │ ├── AbsolutePositionTests.swift │ ├── BumpPtrAllocatorTests.swift │ ├── DebugDescriptionTests.swift │ ├── DummyParseToken.swift │ ├── IdentifierTests.swift │ ├── MemoryLayoutTest.swift │ ├── MultithreadingTests.swift │ ├── RawSyntaxTests.swift │ ├── SourceLocationConverterTests.swift │ ├── SyntaxChildrenTests.swift │ ├── SyntaxCollectionsTests.swift │ ├── SyntaxCreationTests.swift │ ├── SyntaxTests.swift │ ├── SyntaxTextTests.swift │ ├── SyntaxTreeModifierTests.swift │ ├── SyntaxVisitorTests.swift │ ├── TriviaTests.swift │ └── VisitorTests.swift └── SwiftSyntaxTestSupportTest │ ├── IncrementalParseTestUtilsTest.swift │ └── SyntaxComparisonTests.swift ├── WORKSPACE ├── cmake └── modules │ ├── AddSwiftHostLibrary.cmake │ ├── CMakeLists.txt │ └── SwiftCompilerCapability.cmake ├── swift-syntax-dev-utils └── utils └── bazel ├── BUILD.bazel ├── opt_wrapper.bzl └── swift_syntax_library.bzl /.bazelrc: -------------------------------------------------------------------------------- 1 | ##===----------------------------------------------------------------------===## 2 | ## 3 | ## This source file is part of the Swift.org open source project 4 | ## 5 | ## Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | ## Licensed under Apache License v2.0 with Runtime Library Exception 7 | ## 8 | ## See https://swift.org/LICENSE.txt for license information 9 | ## See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | ## 11 | ##===----------------------------------------------------------------------===## 12 | 13 | common --enable_bzlmod 14 | common --incompatible_disallow_empty_glob 15 | common --incompatible_use_host_features 16 | common --lockfile_mode=off 17 | 18 | build --features=swift.use_explicit_swift_module_map 19 | build --host_features=swift.use_explicit_swift_module_map 20 | 21 | # Improved build performance 22 | build --host_swiftcopt=-whole-module-optimization 23 | build --swiftcopt=-whole-module-optimization 24 | 25 | # Keep in sync with Package.swift 26 | build --host_macos_minimum_os=10.15 27 | build --macos_minimum_os=10.15 28 | 29 | test --test_output=errors 30 | -------------------------------------------------------------------------------- /.bazelversion: -------------------------------------------------------------------------------- 1 | 7.0.2 2 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | ##===----------------------------------------------------------------------===## 2 | ## 3 | ## This source file is part of the Swift.org open source project 4 | ## 5 | ## Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | ## Licensed under Apache License v2.0 with Runtime Library Exception 7 | ## 8 | ## See https://swift.org/LICENSE.txt for license information 9 | ## See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | ## 11 | ##===----------------------------------------------------------------------===## 12 | 13 | # editorconfig.org 14 | 15 | root = true 16 | 17 | [*] 18 | indent_style = space 19 | indent_size = 2 20 | trim_trailing_whitespace = true 21 | insert_final_newline = true 22 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | **/generated/** linguist-generated=true 2 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # This file is a list of the people responsible for ensuring that patches for a 2 | # particular part of SwiftSyntax are reviewed, either by themselves or by 3 | # someone else. They are also the gatekeepers for their part of Swift, with the 4 | # final word on what goes in or not. 5 | 6 | # Lines starting with '#' are comments. 7 | # Each line is a file pattern followed by one or more owners. 8 | # Order is important. The last matching pattern has the most precedence. 9 | 10 | # Owner of anything in SwiftSyntax not owned by anyone else. 11 | * @ahoppen @bnbarham @hamishknight @rintaro 12 | 13 | # Macros 14 | /Sources/SwiftSyntaxMacros @DougGregor 15 | /Tests/SwiftSyntaxMacrosTest @DougGregor 16 | 17 | # SwiftOperators 18 | /Sources/SwiftOperators @DougGregor 19 | /Tests/SwiftOperatorsTest @DougGregor 20 | 21 | /utils/bazel @keith 22 | *.bazel @keith 23 | WORKSPACE @keith 24 | .bazelrc @keith 25 | .bazelversion @keith 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/BASICFORMAT_BUG.yml: -------------------------------------------------------------------------------- 1 | name: BasicFormat Bug 2 | description: A bug in the BasicFormat module 3 | labels: [bug, BasicFormat] 4 | body: 5 | - type: markdown 6 | attributes: 7 | 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). 8 | - type: textarea 9 | id: source 10 | attributes: 11 | label: Source Code 12 | description: The source code that, when formatted, produces incorrectly formatted code. 13 | value: | 14 | ```swift 15 | ``` 16 | - type: textarea 17 | id: source 18 | attributes: 19 | label: Actual Formatted Code 20 | description: The way that `BasicFormat` formats the above code 21 | value: | 22 | ```swift 23 | ``` 24 | - type: textarea 25 | id: source 26 | attributes: 27 | label: Expected Formatted Code 28 | description: The way that you think `BasicFormat` should format the code 29 | value: | 30 | ```swift 31 | ``` 32 | - type: textarea 33 | id: description 34 | attributes: 35 | label: Description 36 | description: | 37 | Any additional information you can provide for this issue, like 38 | - Has this issue started occurring recently? 39 | - Is the issue only happening under certain circumstances? 40 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/BUG_REPORT.yml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | description: Something isn't working as expected 3 | labels: [bug] 4 | body: 5 | - type: textarea 6 | id: description 7 | attributes: 8 | label: Description 9 | description: | 10 | A short description of the incorrect behavior. 11 | If you think this issue has been recently introduced and did not occur in an 12 | earlier version, please note that. If possible, include the last version that 13 | the behavior was correct in addition to your current version. 14 | - type: textarea 15 | id: steps-to-reproduce 16 | attributes: 17 | label: Steps to Reproduce 18 | description: Replace this paragraph with an explanation of how to reproduce the incorrect behavior. 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: A suggestion for a new feature 3 | labels: [enhancement] 4 | body: 5 | - type: textarea 6 | id: description 7 | attributes: 8 | label: Description 9 | description: | 10 | A description of your proposed feature. 11 | Examples that show what's missing, or what new capabilities will be possible, are very helpful! 12 | If this feature unlocks new use-cases please describe them. 13 | Provide links to existing issues or external references/discussions, if appropriate. 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2022 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | # See https://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | contact_links: 10 | - name: Discussion Forum 11 | url: https://forums.swift.org/tags/c/development/tooling/39/swift-syntax 12 | about: Ask and answer questions about SwiftSyntax 13 | - name: SwiftSyntax Documentation 14 | url: https://swiftpackageindex.com/swiftlang/swift-syntax/documentation/swiftsyntax 15 | about: Learn about how to use the SwiftSyntax in your projects 16 | -------------------------------------------------------------------------------- /.github/workflows/automerge.yml: -------------------------------------------------------------------------------- 1 | name: Create PR to merge main into release branch 2 | # In the first period after branching the release branch, we typically want to include many changes from `main` in the release branch. This workflow automatically creates a PR every Monday to merge main into the release branch. 3 | # Later in the release cycle we should stop this practice to avoid landing risky changes by disabling this workflow. To do so, disable the workflow as described in https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/disabling-and-enabling-a-workflow 4 | on: 5 | schedule: 6 | - cron: '0 9 * * MON' 7 | workflow_dispatch: 8 | jobs: 9 | create_merge_pr: 10 | name: Create PR to merge main into release branch 11 | uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@main 12 | with: 13 | base_branch: release/6.2 14 | permissions: 15 | contents: write 16 | pull-requests: write 17 | if: (github.event_name == 'schedule' && github.repository == 'swiftlang/swift-syntax') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Swift Package Manager build artifacts directory. 2 | .build/ 3 | .*-build/ 4 | # Ignore generated Xcode projects 5 | *.xcodeproj 6 | # Ignore SwiftPM state, such as the generated xcodeproj when opening the project directly 7 | .swiftpm 8 | # Ignore user state in Xcode Projects 9 | *.xcuserdatad 10 | UserInterfaceState.xcuserstate 11 | xcuserdata/ 12 | 13 | # Ignore VScode workspace settings and launch configurations 14 | .vscode 15 | 16 | # Ignore bazel symlinks 17 | /bazel-* 18 | 19 | # Ignore cmake build configuration and output 20 | build/ 21 | 22 | # We always build swiftSyntax of trunk dependencies. Ignore any fixed 23 | # dependency versions. 24 | Package.resolved 25 | 26 | .DS_Store 27 | *.pyc 28 | 29 | Tests/PerformanceTest/baselines.json 30 | 31 | # The local build of swift-format to format swift-syntax 32 | .swift-format-build 33 | -------------------------------------------------------------------------------- /.license_header_template: -------------------------------------------------------------------------------- 1 | @@===----------------------------------------------------------------------===@@ 2 | @@ 3 | @@ This source file is part of the Swift.org open source project 4 | @@ 5 | @@ Copyright (c) YEARS Apple Inc. and the Swift project authors 6 | @@ Licensed under Apache License v2.0 with Runtime Library Exception 7 | @@ 8 | @@ See https://swift.org/LICENSE.txt for license information 9 | @@ See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | @@ 11 | @@===----------------------------------------------------------------------===@@ 12 | -------------------------------------------------------------------------------- /.licenseignore: -------------------------------------------------------------------------------- 1 | .bazelversion 2 | .gitignore 3 | *.md 4 | *.txt 5 | *.yml 6 | **/*.docc/** 7 | **/*.entitlements 8 | **/*.input 9 | **/*.modulemap 10 | **/*.plist 11 | **/*.xcodeproj/** 12 | **/CODEOWNERS 13 | *Package.swift 14 | swift-syntax-dev-utils 15 | WORKSPACE 16 | -------------------------------------------------------------------------------- /.spi.yml: -------------------------------------------------------------------------------- 1 | # This is manifest file for the Swift Package Index for it to 2 | # auto-generate and host DocC documentation. 3 | # For reference see https://swiftpackageindex.com/swiftpackageindex/spimanifest/documentation/spimanifest/commonusecases#Host-DocC-documentation-in-the-Swift-Package-Index. 4 | 5 | version: 1 6 | builder: 7 | configs: 8 | - documentation_targets: 9 | # First item in the list is the "landing" (default) target 10 | - SwiftSyntax 11 | - SwiftBasicFormat 12 | - SwiftCompilerPlugin 13 | - SwiftDiagnostics 14 | - SwiftIDEUtils 15 | - SwiftIfConfig 16 | - SwiftLexicalLookup 17 | - SwiftOperators 18 | - SwiftParser 19 | - SwiftParserDiagnostics 20 | - SwiftRefactor 21 | - SwiftSyntaxBuilder 22 | - SwiftSyntaxMacros 23 | - SwiftSyntaxMacroExpansion 24 | - SwiftSyntaxMacrosGenericTestSupport 25 | - SwiftSyntaxMacrosTestSupport 26 | custom_documentation_parameters: [--experimental-skip-synthesized-symbols] 27 | -------------------------------------------------------------------------------- /.swift-format: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "lineLength": 120, 4 | "indentation": { 5 | "spaces": 2 6 | }, 7 | "lineBreakBeforeEachArgument": true, 8 | "indentConditionalCompilationBlocks": false, 9 | "prioritizeKeepingFunctionOutputTogether": true, 10 | "rules": { 11 | "AlwaysUseLowerCamelCase": false, 12 | "AmbiguousTrailingClosureOverload": false, 13 | "NoBlockComments": false, 14 | "OrderedImports": true, 15 | "UseLetInEveryBoundCaseVariable": false, 16 | "UseSynthesizedInitializer": false 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CodeGeneration/README.md: -------------------------------------------------------------------------------- 1 | # Code-Generation for SwiftSyntax 2 | 3 | This directory contains file to generate source code that is part of the SwiftSyntax package. If you are looking to generate Swift code yourself, you might be interested in [SwiftSyntaxBuilder](../Sources/SwiftSyntaxBuilder). 4 | 5 | Some source code inside SwiftSyntax is generated using [SwiftSyntaxBuilder](../Sources/SwiftSyntaxBuilder), a Swift library whose purpose is to generate Swift code using Swift itself. This kind of code generation is performed by the Swift package defined in this directory. 6 | 7 | To re-generate the files after changing `CodeGeneration` run the following command on the command line. 8 | 9 | ```bash 10 | path/to/swift-syntax/swift-syntax-dev-utils generate-source-code 11 | ``` 12 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/SyntaxSupport/BuilderInitializableTypes.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// As keys, contains all node kinds that can be initialized using a result 14 | /// builder. If the value is not nil, the result builder construct the value's 15 | /// type and synthesize all other members to form the node. 16 | public let BUILDER_INITIALIZABLE_TYPES: [SyntaxNodeKind: SyntaxNodeKind?] = [ 17 | .arrayElementList: nil, 18 | .closureCaptureList: nil, 19 | .codeBlock: .codeBlockItemList, 20 | .codeBlockItemList: nil, 21 | .enumCaseElementList: nil, 22 | .exprList: nil, 23 | .functionParameterList: nil, 24 | .genericArgumentList: nil, 25 | .genericParameterList: nil, 26 | .genericRequirementList: nil, 27 | .inheritedTypeList: nil, 28 | .labeledExprList: nil, 29 | .memberBlock: .memberBlockItemList, 30 | .memberBlockItemList: nil, 31 | .patternBindingList: nil, 32 | .switchCaseItemList: nil, 33 | .switchCaseList: nil, 34 | .tuplePatternElementList: nil, 35 | ] 36 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/SyntaxSupport/InitSignature.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// Represents an initializer that should be generated. 14 | public struct InitSignature { 15 | /// The list of children which shoudl be given parameters and initialized by the initializer. 16 | public var children: [Child] 17 | 18 | /// Create an initializer with an arbitrary array of children. 19 | public init(children: [Child]) { 20 | self.children = children 21 | } 22 | 23 | /// Create an initializer for the (non-deprecated) children of a given layout node. 24 | public init(_ layoutNode: LayoutNode) { 25 | self.init(children: layoutNode.children) 26 | } 27 | 28 | /// Create an initializer for the (non-deprecated) children of a given trait. 29 | public init(_ trait: Trait) { 30 | self.init(children: trait.children) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/SyntaxSupport/RawSyntaxNodeKind.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | 15 | /// A wrapper of ``SyntaxNodeKind`` providing syntax type information for the raw side. 16 | public struct RawSyntaxNodeKind: TypeConvertible { 17 | public var syntaxNodeKind: SyntaxNodeKind 18 | 19 | public var isBase: Bool { 20 | self.syntaxNodeKind.isBase 21 | } 22 | 23 | public var syntaxType: TypeSyntax { 24 | "Raw\(self.syntaxNodeKind.syntaxType)" 25 | } 26 | 27 | public var protocolType: TypeSyntax { 28 | switch self { 29 | case .syntax, .syntaxCollection: 30 | return "RawSyntaxNodeProtocol" 31 | default: 32 | return "\(self.syntaxType)NodeProtocol" 33 | } 34 | } 35 | 36 | public var isAvailableInDocc: Bool { 37 | false 38 | } 39 | 40 | public static func ~= (lhs: SyntaxNodeKind, rhs: Self) -> Bool { 41 | lhs == rhs.syntaxNodeKind 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/SyntaxSupport/String+Extensions.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | extension StringProtocol { 14 | public var withFirstCharacterLowercased: String { 15 | guard first?.isLetter ?? false else { 16 | return String(first!) + dropFirst().withFirstCharacterLowercased 17 | } 18 | return prefix(1).lowercased() + dropFirst() 19 | } 20 | public var withFirstCharacterUppercased: String { 21 | guard first?.isLetter ?? false else { 22 | return String(first!) + dropFirst().withFirstCharacterUppercased 23 | } 24 | return prefix(1).uppercased() + dropFirst() 25 | } 26 | } 27 | 28 | extension String { 29 | public var droppingLeadingUnderscores: String { 30 | if first == "_" { 31 | return String(self.dropFirst()) 32 | } 33 | return self 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/Utils/CopyrightHeader.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | 15 | public var copyrightHeader: Trivia = 16 | """ 17 | //===----------------------------------------------------------------------===// 18 | // 19 | // This source file is part of the Swift.org open source project 20 | // 21 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 22 | // Licensed under Apache License v2.0 with Runtime Library Exception 23 | // 24 | // See https://swift.org/LICENSE.txt for license information 25 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 26 | // 27 | //===----------------------------------------------------------------------===// 28 | // Automatically generated by generate-swift-syntax 29 | // Do not edit directly! 30 | // swift-format-ignore-file 31 | """ + .newlines(2) 32 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/Utils/Utils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | extension String { 14 | /// Creates a single-line documentation string from indented 15 | /// documentation as written in `CodeGeneration`. 16 | public var flattened: String { 17 | self 18 | .replacingOccurrences(of: "\n", with: "") 19 | .trimmingCharacters(in: .whitespacesAndNewlines) 20 | } 21 | 22 | /// Removes all empty lines from a multi-line string. 23 | public var removingEmptyLines: String { 24 | return 25 | self 26 | .split(whereSeparator: \.isNewline) 27 | .filter { !$0.allSatisfy(\.isWhitespace) } 28 | .joined(separator: "\n") 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/generate-swift-syntax/templates/swiftparser/TokenSpecStaticMembersFile.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import SyntaxSupport 16 | import Utils 17 | 18 | let tokenSpecStaticMembersFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { 19 | importSwiftSyntax() 20 | 21 | try! ExtensionDeclSyntax("extension TokenSpec") { 22 | for tokenSpec in Token.allCases.map(\.spec) where tokenSpec.kind != .keyword { 23 | DeclSyntax("static var \(tokenSpec.varDeclName): TokenSpec { return TokenSpec(.\(tokenSpec.memberCallName)) }") 24 | } 25 | 26 | DeclSyntax("static func keyword(_ keyword: Keyword) -> TokenSpec { return TokenSpec(keyword) }") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /CodeGeneration/Sources/generate-swift-syntax/templates/swiftsyntaxbuilder/BuildableNodesFile.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import SyntaxSupport 16 | import Utils 17 | 18 | let buildableNodesFile = SourceFileSyntax(leadingTrivia: copyrightHeader) { 19 | importSwiftSyntax(accessLevel: .public) 20 | 21 | for node in SYNTAX_NODES.compactMap(\.layoutNode) { 22 | let type = node.type 23 | 24 | if let convenienceInit = try! InitSignature(node).createConvenienceBuilderInitializer() { 25 | DeclSyntax( 26 | """ 27 | extension \(type.syntaxBaseName) { 28 | \(convenienceInit) 29 | } 30 | """ 31 | ) 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /CodeGeneration/Tests/ValidateSyntaxNodes/Utils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | extension Collection { 14 | /// If the collection contains a single element, return it, otherwise `nil`. 15 | var only: Element? { 16 | if !isEmpty && index(after: startIndex) == endIndex { 17 | return self.first! 18 | } else { 19 | return nil 20 | } 21 | } 22 | } 23 | 24 | extension String { 25 | func dropPrefix(_ suffix: String) -> String { 26 | if hasPrefix(suffix) { 27 | return String(self.dropFirst(suffix.count)) 28 | } else { 29 | return self 30 | } 31 | } 32 | 33 | func dropSuffix(_ suffix: String) -> String { 34 | if hasSuffix(suffix) { 35 | return String(self.dropLast(suffix.count)) 36 | } else { 37 | return self 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /CodeGeneration/Tests/ValidateSyntaxNodes/ValidationFailure.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SyntaxSupport 14 | 15 | struct ValidationFailure: Equatable { 16 | /// The node that failed verification 17 | let node: SyntaxNodeKind 18 | 19 | /// A human-readable description of the validation failure 20 | let message: String 21 | } 22 | -------------------------------------------------------------------------------- /Contributor Documentation/API Breakage Checks.md: -------------------------------------------------------------------------------- 1 | # API Breakage Checks 2 | 3 | We have a CI jobs that checks for API breakages. Since swift-syntax releases increase the major version number, it is possible to make API-breaking changes – but we should avoid them whenever possible to avoid churn on clients when they update to a new swift-syntax version. 4 | 5 | If your change contains an API breaking change, add the change to `api-breakages.txt`. All API breaking changes should be accompanied by an [RFC](RFC%20Process.md). 6 | -------------------------------------------------------------------------------- /Contributor Documentation/Environment variables.md: -------------------------------------------------------------------------------- 1 | # Environment variables 2 | 3 | The following environment variables can be used to control some behavior in swift-syntax. 4 | 5 | ## Build time 6 | 7 | - `SWIFT_BUILD_SCRIPT_ENVIRONMENT`: Enable assertions in release builds and remove the dependency of swift-syntax on os_log. 8 | - `SWIFTCI_USE_LOCAL_DEPS`: Assume that all of SourceKit-LSP’s dependencies are checked out next to it and use those instead of cloning the repositories. Primarily intended for CI environments that check out related branches. 9 | - `SWIFTPARSER_ENABLE_ALTERNATE_TOKEN_INTROSPECTION`: Mutate the input of `assertParse` test cases. See [CONTRIBUTING](../CONTRIBUTING.md) for more information. 10 | - `SWIFTSYNTAX_BUILD_DYNAMIC_LIBRARY`: Instead of building object files for all modules to be statically linked, build a single dynamic library. This allows us to build swift-syntax as dynamic libraries, which in turn allows us to build SourceKit-LSP using SwiftPM on Windows. Linking swift-syntax statically into sourcekit-lsp exceeds the maximum number of exported symbols on Windows. 11 | - `SWIFTSYNTAX_ENABLE_RAWSYNTAX_VALIDATION`: Check that the layout of the syntax tree is correct when creating or modifying nodes. See [CONTRIBUTING](../CONTRIBUTING.md) for more information. 12 | 13 | ## Testing 14 | 15 | - `SKIP_LONG_TESTS`: Skip tests that typically take more than 1s to execute. 16 | -------------------------------------------------------------------------------- /Contributor Documentation/README.md: -------------------------------------------------------------------------------- 1 | # Contributor Documentation 2 | 3 | The following documentation documents are primarily intended for developers of swift-syntax. 4 | 5 | - [API Breakage Checks](API%20Breakage%20Checks.md) 6 | - [Changing Swift Syntax](Changing%20Swift%20Syntax.md) 7 | - [Filing Parser Bug Reports](Filing%20Parser%20Bug%20Reports.md) 8 | - [Fixing Bugs](Fixing%20Bugs.md) 9 | - [Parser Design](Parser%20Design.md) 10 | - [Parser Recovery](Parser%20Recovery.md) 11 | - [Parsing Basics](Parsing%20Basics.md) 12 | - [When to use protocols in SwiftSyntax](When%20to%20use%20protocols%20in%20SwiftSyntax.md) 13 | - [`@_spi` Attribute](SPI%20Attribute.md) 14 | -------------------------------------------------------------------------------- /Contributor Documentation/SPI Attribute.md: -------------------------------------------------------------------------------- 1 | # @_spi attribute 2 | 3 | Learn when SwiftSyntax exposes declaration annotated as `@_spi`. 4 | 5 | Functions marked as `@_spi(RawSyntax)` (where `RawSyntax` can be any name) are considered *SPI* (System Programming Interface) and are only accessible if the module that declares them is imported as `@_spi(RawSyntax)`. 6 | 7 | Since functions marked as SPI are not part of the public API, swift-syntax makes no guarantee to their source stability. swift-syntax makes no effort to keep its SPI stable. 8 | 9 | Declarations are typically marked as SPI because they have some kind of caveat that makes them unsafe to use in general. For example, when accessing `RawSyntax` nodes, you need to manually guarantee that the ``SyntaxArena`` they’re allocated in will not be de-allocated. Other declarations have an `@_spi` to share them between different modules within the swift-syntax package. These would use the [`package` modifier](https://github.com/apple/swift-evolution/blob/main/proposals/0386-package-access-modifier.md) if not for the fact that swift-syntax needed to compile with the last two Swift releases (see ). 10 | -------------------------------------------------------------------------------- /Contributor Documentation/When to use protocols in SwiftSyntax.md: -------------------------------------------------------------------------------- 1 | # When to use protocols in SwiftSyntax 2 | 3 | Learn when to use protocols value types like ``ExprSyntax`` over protocols like ``ExprSyntaxProtocol``. 4 | 5 | 6 | SwiftSyntax tries to minimize the use of existentials (aka. protocols spelled with `any` or protocols spelled without `some`) wherever possible. This is because when the stored value is more than 3 words (a word is the size of a pointer) large, these existentials store their data on the heap. The data stored inside `RawSyntax` is larger than 3 words and thus every time you pass a value around as a e.g. an `ExprSyntaxProtocol`, a new heap allocation will be made and that data needs to be reference-counted, which causes a very noticeable performance overhead. 7 | 8 | swift-syntax offers two alternatives: 9 | - When passing a single node around, use `some ExprSyntaxProtocol`. This allows the concrete expression node (e.g. an ``IntegerLiteralExprSyntax``) to be passed directly without the need to wrap it in an existential and thus avoid the performance overhead. 10 | - When multiple expression nodes need to be represented that might be of different types, eg. in an array of expressions, use the ``ExprSyntax`` type. ``ExprSyntax`` is a struct and can thus be allocated on the stack. The downside is that specific expression nodes need to explicitly be upcast to `ExprSyntax` (`ExprSyntax(integerLiteral)`) and downcast to more specific types using a custom `as` method (`expr.as(IntegerLiteralExprSyntax.self)`). 11 | -------------------------------------------------------------------------------- /EditorExtension/Host/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "mac", 5 | "size" : "16x16", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "mac", 10 | "size" : "16x16", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "mac", 15 | "size" : "32x32", 16 | "scale" : "1x" 17 | }, 18 | { 19 | "idiom" : "mac", 20 | "size" : "32x32", 21 | "scale" : "2x" 22 | }, 23 | { 24 | "idiom" : "mac", 25 | "size" : "128x128", 26 | "scale" : "1x" 27 | }, 28 | { 29 | "idiom" : "mac", 30 | "size" : "128x128", 31 | "scale" : "2x" 32 | }, 33 | { 34 | "idiom" : "mac", 35 | "size" : "256x256", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "mac", 40 | "size" : "256x256", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "mac", 45 | "size" : "512x512", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "mac", 50 | "size" : "512x512", 51 | "scale" : "2x" 52 | } 53 | ], 54 | "info" : { 55 | "version" : 1, 56 | "author" : "xcode" 57 | } 58 | } -------------------------------------------------------------------------------- /EditorExtension/Host/HostApp.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftUI 14 | 15 | @main struct HostApp: App { 16 | var body: some Scene { 17 | WindowGroup { 18 | Text("I am a stub! Please build and run the 'SwiftRefactorExtension' scheme instead.") 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /EditorExtension/Host/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleVersion 22 | 1 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | Copyright © 2023 Apple Inc. All rights reserved. 27 | NSPrincipalClass 28 | NSApplication 29 | 30 | 31 | -------------------------------------------------------------------------------- /EditorExtension/SwiftRefactorExtension.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /EditorExtension/SwiftRefactorExtension.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /EditorExtension/SwiftRefactorExtension/Bridge.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #include "stdint.h" 14 | 15 | struct ConformanceDescriptor { 16 | int32_t protocol; 17 | int32_t typeRef; 18 | int32_t witnessTablePattern; 19 | uint32_t flags; 20 | }; 21 | 22 | struct ContextDescriptor { 23 | uint32_t flags; 24 | int32_t parent; 25 | }; 26 | 27 | struct ModuleContextDescriptor { 28 | uint32_t flags; 29 | int32_t parent; 30 | int32_t name; 31 | }; 32 | 33 | struct TypeContextDescriptor { 34 | uint32_t flags; 35 | int32_t parent; 36 | int32_t name; 37 | int32_t accessor; 38 | }; 39 | -------------------------------------------------------------------------------- /EditorExtension/SwiftRefactorExtension/RefactoringRegistry.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftRefactor 14 | 15 | final class RefactoringRegistry { 16 | public static let shared = RefactoringRegistry() 17 | 18 | public private(set) var providers = [any SyntaxRefactoringProvider.Type]() 19 | private var providersByName = [String: any SyntaxRefactoringProvider.Type]() 20 | 21 | func register(_ provider: any SyntaxRefactoringProvider.Type) { 22 | self.providers.append(provider) 23 | self.providersByName[String(describing: provider)] = provider 24 | } 25 | 26 | subscript(identifier: String) -> (any SyntaxRefactoringProvider.Type)? { 27 | _read { yield self.providersByName[identifier] } 28 | } 29 | 30 | private init() {} 31 | } 32 | -------------------------------------------------------------------------------- /EditorExtension/SwiftRefactorExtension/SourceEditorExtension.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import Foundation 14 | import SwiftRefactor 15 | import XcodeKit 16 | 17 | final class SourceEditorExtension: NSObject, XCSourceEditorExtension { 18 | func extensionDidFinishLaunching() { 19 | Self.forEachRefactoringProvider { provider in 20 | RefactoringRegistry.shared.register(provider) 21 | } 22 | } 23 | 24 | var commandDefinitions: [[XCSourceEditorCommandDefinitionKey: Any]] { 25 | return RefactoringRegistry.shared.providers.map { provider in 26 | return [ 27 | .classNameKey: SourceEditorCommand.className(), 28 | .identifierKey: String(describing: provider), 29 | .nameKey: String(describing: provider), 30 | ] 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /EditorExtension/SwiftRefactorExtension/SwiftRefactorExtension.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Examples/Sources/Examples-all/empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This is a fake target that depends on all targets in the package. 14 | // We need to define it manually because the `Examples-Package` target doesn't exist for `swift build`. 15 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/Accessor/EnvironmentValueMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxMacros 15 | 16 | public struct EnvironmentValueMacro: AccessorMacro { 17 | public static func expansion( 18 | of node: AttributeSyntax, 19 | providingAccessorsOf declaration: some DeclSyntaxProtocol, 20 | in context: some MacroExpansionContext 21 | ) throws -> [AccessorDeclSyntax] { 22 | guard 23 | case let .argumentList(arguments) = node.arguments, 24 | let argument = arguments.first 25 | else { return [] } 26 | 27 | return [ 28 | """ 29 | get { self[\(argument.expression)] } 30 | """, 31 | """ 32 | set { self[\(argument.expression)] = newValue } 33 | """, 34 | ] 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/Declaration/FuncUniqueMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import SwiftSyntaxMacros 16 | 17 | /// Func With unique name. 18 | public enum FuncUniqueMacro: DeclarationMacro { 19 | public static func expansion( 20 | of node: some FreestandingMacroExpansionSyntax, 21 | in context: some MacroExpansionContext 22 | ) throws -> [DeclSyntax] { 23 | let name = context.makeUniqueName("unique") 24 | return [ 25 | """ 26 | class MyClass { 27 | func \(name)() {} 28 | } 29 | """ 30 | ] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/Diagnostics.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftDiagnostics 14 | import SwiftSyntax 15 | 16 | struct SimpleDiagnosticMessage: DiagnosticMessage, Error { 17 | let message: String 18 | let diagnosticID: MessageID 19 | let severity: DiagnosticSeverity 20 | } 21 | 22 | extension SimpleDiagnosticMessage: FixItMessage { 23 | var fixItID: MessageID { diagnosticID } 24 | } 25 | 26 | enum CustomError: Error, CustomStringConvertible { 27 | case message(String) 28 | 29 | var description: String { 30 | switch self { 31 | case .message(let text): 32 | return text 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/Expression/StringifyMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import SwiftSyntaxMacros 16 | 17 | /// Implementation of the `stringify` macro, which takes an expression 18 | /// of any type and produces a tuple containing the value of that expression 19 | /// and the source code that produced the value. For example 20 | /// 21 | /// #stringify(x + y) 22 | /// 23 | /// will expand to 24 | /// 25 | /// (x + y, "x + y") 26 | public enum StringifyMacro: ExpressionMacro { 27 | public static func expansion( 28 | of node: some FreestandingMacroExpansionSyntax, 29 | in context: some MacroExpansionContext 30 | ) -> ExprSyntax { 31 | guard let argument = node.arguments.first?.expression else { 32 | fatalError("compiler bug: the macro does not have any arguments") 33 | } 34 | 35 | return "(\(argument), \(literal: argument.description))" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/Extension/EquatableExtensionMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxMacros 15 | 16 | public enum EquatableExtensionMacro: ExtensionMacro { 17 | public static func expansion( 18 | of node: AttributeSyntax, 19 | attachedTo declaration: some DeclGroupSyntax, 20 | providingExtensionsOf type: some TypeSyntaxProtocol, 21 | conformingTo protocols: [TypeSyntax], 22 | in context: some MacroExpansionContext 23 | ) throws -> [ExtensionDeclSyntax] { 24 | let equatableExtension = try ExtensionDeclSyntax("extension \(type.trimmed): Equatable {}") 25 | 26 | return [equatableExtension] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/MemberAttribute/MemberDeprecatedMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxMacros 15 | 16 | /// Add '@available(*, deprecated)' to members. 17 | public enum MemberDeprecatedMacro: MemberAttributeMacro { 18 | public static func expansion( 19 | of node: AttributeSyntax, 20 | attachedTo declaration: some DeclGroupSyntax, 21 | providingAttributesFor member: some DeclSyntaxProtocol, 22 | in context: some MacroExpansionContext 23 | ) throws -> [AttributeSyntax] { 24 | return ["@available(*, deprecated)"] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Implementation/Peer/PeerValueWithSuffixNameMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxMacros 15 | 16 | /// Peer 'var' with the name suffixed with '_peer'. 17 | public enum PeerValueWithSuffixNameMacro: PeerMacro { 18 | public static func expansion( 19 | of node: AttributeSyntax, 20 | providingPeersOf declaration: some DeclSyntaxProtocol, 21 | in context: some MacroExpansionContext 22 | ) throws -> [DeclSyntax] { 23 | guard let identified = declaration.asProtocol(NamedDeclSyntax.self) else { 24 | return [] 25 | } 26 | return ["var \(raw: identified.name.text)_peer: Int { 1 }"] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Interface/AccessorMacros.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if canImport(SwiftUI) 14 | 15 | import SwiftUI 16 | 17 | // MARK: - EnvironmentValue Accessor 18 | 19 | /// Adds getter / setter to an attached environment value with specified EnvironmentKey 20 | @attached(accessor) 21 | public macro EnvironmentValue(for key: any EnvironmentKey.Type) = 22 | #externalMacro(module: "MacroExamplesImplementation", type: "EnvironmentValueMacro") 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Interface/DeclarationMacros.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // MARK: - Func Unique 14 | 15 | @freestanding(declaration, names: named(MyClass)) 16 | public macro FuncUnique() = #externalMacro(module: "MacroExamplesImplementation", type: "FuncUniqueMacro") 17 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Interface/MemberAttributeMacros.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // MARK: - Member Deprecated 14 | 15 | @attached(memberAttribute) 16 | public macro memberDeprecated() = #externalMacro(module: "MacroExamplesImplementation", type: "MemberDeprecatedMacro") 17 | 18 | // MARK: - Wrap Stored Properties 19 | 20 | /// Apply the specified attribute to each of the stored properties within the 21 | /// type or member to which the macro is attached. The string can be 22 | /// any attribute (without the `@`). 23 | @attached(memberAttribute) 24 | public macro wrapStoredProperties(_ attributeName: String) = 25 | #externalMacro(module: "MacroExamplesImplementation", type: "WrapStoredPropertiesMacro") 26 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Interface/PeerMacros.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // MARK: - Add Async 14 | 15 | @attached(peer, names: overloaded) 16 | public macro AddAsync() = #externalMacro(module: "MacroExamplesImplementation", type: "AddAsyncMacro") 17 | 18 | // MARK: - Add Completion Handler 19 | 20 | /// Adds a "completionHandler" variant of an async function, which creates a new 21 | /// task , calls the original async function, and delivers its result to the completion 22 | /// handler. 23 | @attached(peer, names: overloaded) 24 | public macro AddCompletionHandler() = 25 | #externalMacro(module: "MacroExamplesImplementation", type: "AddCompletionHandlerMacro") 26 | 27 | // MARK: - Peer Value With Suffix Name 28 | 29 | @attached(peer, names: suffixed(_peer)) 30 | public macro PeerValueWithSuffixName() = 31 | #externalMacro(module: "MacroExamplesImplementation", type: "PeerValueWithSuffixNameMacro") 32 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Interface/SourceLocationMacros.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | @freestanding(expression) 14 | public macro FileID() -> T = 15 | #externalMacro( 16 | module: "MacroExamplesImplementation", 17 | type: "NativeFileIDMacro" 18 | ) 19 | 20 | @freestanding(expression) 21 | public macro FilePath() -> T = 22 | #externalMacro( 23 | module: "MacroExamplesImplementation", 24 | type: "NativeFilePathMacro" 25 | ) 26 | 27 | @freestanding(expression) 28 | public macro Line() -> T = 29 | #externalMacro( 30 | module: "MacroExamplesImplementation", 31 | type: "NativeLineMacro" 32 | ) 33 | 34 | @freestanding(expression) 35 | public macro Column() -> T = 36 | #externalMacro( 37 | module: "MacroExamplesImplementation", 38 | type: "NativeColumnMacro" 39 | ) 40 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Playground/AccessorMacrosPlayground.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // MARK: - EnvironmentValue Accessor 14 | 15 | import MacroExamplesInterface 16 | 17 | #if canImport(SwiftUI) 18 | 19 | import SwiftUI 20 | 21 | private struct MyEnvironmentKey: EnvironmentKey { 22 | static let defaultValue: String = "Default value" 23 | } 24 | 25 | extension EnvironmentValues { 26 | @EnvironmentValue(for: MyEnvironmentKey.self) 27 | var myCustomValue: String 28 | } 29 | 30 | func runEnvironmentValueAccessorMacroPlayground() { 31 | var environmentValues = EnvironmentValues() 32 | print("Default myCustomValue: \(environmentValues.myCustomValue)") 33 | environmentValues.myCustomValue = "New value" 34 | print("New myCustomValue: \(environmentValues.myCustomValue)") 35 | } 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Playground/DeclarationMacrosPlayground.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import MacroExamplesInterface 14 | 15 | // MARK: - Func Unique 16 | 17 | #FuncUnique 18 | 19 | func runFuncUniqueMacroPlayground() { 20 | print("My Class Declaration with unique method: ", MyClass()) 21 | } 22 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Playground/ExtensionMacrosPlayground.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import MacroExamplesInterface 14 | 15 | // MARK: - Default Fatal Error Implementation 16 | 17 | @defaultFatalErrorImplementation 18 | protocol API { 19 | func getItems() -> [String] 20 | func removeItem(id: String) 21 | } 22 | 23 | struct MyAPI: API {} 24 | 25 | func runDefaultFatalErrorImplementationMacroPlayground() { 26 | let myAPI = MyAPI() 27 | 28 | print("Implementation of `API` protocol with default implementation: \(myAPI)") 29 | } 30 | 31 | // MARK: - Equatable Extension 32 | 33 | @equatable 34 | struct Pet { 35 | let name: String 36 | } 37 | 38 | func runEquatableExtensionMacroPlayground() { 39 | let cat = Pet(name: "Tom") 40 | let mouse = Pet(name: "Jerry") 41 | 42 | print("Has the cat \(cat) the same name as the mouse \(mouse)?", cat == mouse ? "Yes." : "No.") 43 | } 44 | -------------------------------------------------------------------------------- /Examples/Sources/MacroExamples/Playground/SourceLocationMacrosPlayground.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import MacroExamplesInterface 14 | 15 | func runSourceLoctionMacrosPlayground() { 16 | print("FileID: \(#FileID as String)") 17 | print("FilePath: \(#FilePath as String)") 18 | print("Line: \(#Line as Int)") 19 | print("Column: \(#Column as Int)") 20 | } 21 | -------------------------------------------------------------------------------- /Examples/Tests/Dummy/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | -------------------------------------------------------------------------------- /Examples/Tests/MacroExamples/Implementation/Declaration/FuncUniqueMacroTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import MacroExamplesImplementation 14 | import SwiftSyntaxMacros 15 | import SwiftSyntaxMacrosTestSupport 16 | import XCTest 17 | 18 | final class FuncUniqueMacroTests: XCTestCase { 19 | private let macros = ["FuncUnique": FuncUniqueMacro.self] 20 | 21 | func testExpansionCreatesDeclarationWithUniqueFunction() { 22 | assertMacroExpansion( 23 | """ 24 | #FuncUnique() 25 | """, 26 | expandedSource: #""" 27 | class MyClass { 28 | func __macro_local_6uniquefMu_() { 29 | } 30 | } 31 | """#, 32 | macros: macros, 33 | indentationWidth: .spaces(2) 34 | ) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Examples/Tests/MacroExamples/Implementation/Extension/EquatableExtensionMacroTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import MacroExamplesImplementation 14 | import SwiftSyntaxMacros 15 | import SwiftSyntaxMacrosTestSupport 16 | import XCTest 17 | 18 | final class EquatableExtensionMacroTests: XCTestCase { 19 | private let macros = ["equatable": EquatableExtensionMacro.self] 20 | 21 | func testExpansionAddsExtensionWithEquatableConformance() { 22 | assertMacroExpansion( 23 | """ 24 | @equatable 25 | final public class Message { 26 | let text: String 27 | let sender: String 28 | } 29 | """, 30 | expandedSource: """ 31 | final public class Message { 32 | let text: String 33 | let sender: String 34 | } 35 | 36 | extension Message: Equatable { 37 | } 38 | """, 39 | macros: macros, 40 | indentationWidth: .spaces(2) 41 | ) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MODULE.bazel: -------------------------------------------------------------------------------- 1 | ##===----------------------------------------------------------------------===## 2 | ## 3 | ## This source file is part of the Swift.org open source project 4 | ## 5 | ## Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | ## Licensed under Apache License v2.0 with Runtime Library Exception 7 | ## 8 | ## See https://swift.org/LICENSE.txt for license information 9 | ## See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | ## 11 | ##===----------------------------------------------------------------------===## 12 | 13 | module( 14 | name = "swift-syntax", 15 | version = "0", 16 | compatibility_level = 1, 17 | ) 18 | 19 | bazel_dep(name = "apple_support", version = "1.13.0", repo_name = "build_bazel_apple_support") 20 | bazel_dep(name = "rules_apple", version = "3.3.0", repo_name = "build_bazel_rules_apple") 21 | bazel_dep(name = "rules_swift", version = "1.18.0", max_compatibility_level = 2, repo_name = "build_bazel_rules_swift") 22 | -------------------------------------------------------------------------------- /Sources/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_subdirectory(_SwiftLibraryPluginProviderCShims) 10 | add_subdirectory(_SwiftSyntaxCShims) 11 | add_subdirectory(SwiftBasicFormat) 12 | add_subdirectory(SwiftSyntax) 13 | add_subdirectory(SwiftDiagnostics) 14 | add_subdirectory(SwiftLexicalLookup) 15 | add_subdirectory(SwiftLibraryPluginProvider) 16 | add_subdirectory(SwiftParser) 17 | add_subdirectory(SwiftParserDiagnostics) 18 | add_subdirectory(SwiftRefactor) 19 | add_subdirectory(SwiftOperators) 20 | add_subdirectory(SwiftIfConfig) 21 | add_subdirectory(SwiftSyntaxBuilder) 22 | add_subdirectory(SwiftSyntaxMacros) 23 | add_subdirectory(SwiftSyntaxMacroExpansion) 24 | add_subdirectory(SwiftCompilerPluginMessageHandling) 25 | add_subdirectory(SwiftIDEUtils) 26 | add_subdirectory(SwiftCompilerPlugin) 27 | add_subdirectory(VersionMarkerModules) 28 | -------------------------------------------------------------------------------- /Sources/SwiftBasicFormat/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftBasicFormat 10 | BasicFormat.swift 11 | Indenter.swift 12 | InferIndentation.swift 13 | Syntax+Extensions.swift 14 | SyntaxProtocol+Formatted.swift 15 | Trivia+FormatExtensions.swift 16 | ) 17 | 18 | target_link_swift_syntax_libraries(SwiftBasicFormat PUBLIC 19 | SwiftSyntax) 20 | -------------------------------------------------------------------------------- /Sources/SwiftBasicFormat/SwiftBasicFormat.docc/FilingBugReports.md: -------------------------------------------------------------------------------- 1 | # Filing BasicFormat Bug Reports 2 | 3 | Guide to provide steps for filing actionable bug reports for `BasicFormat` failures. 4 | 5 | - Attention: Keep in mind that the primary goal of BasicFormat is to add trivia to a SwiftSyntax tree in a way that allows the parser to parse the same tree again, e.g. making sure that a keyword and an identifier are separated by a space. BasicFormat intentionally has no functionality to e.g. split lines. 6 | 7 | Reducing a failure requires the `swift-parser-cli` utility that you can build by checking out `swift-syntax` and running 8 | ``` 9 | swift build --package-path SwiftParserCLI 10 | ``` 11 | or openning `SwiftParserCLI` package and building the `swift-parser-cli` target in Xcode. 12 | 13 | 1. After you have built `swift-parser-cli`, you can format a single source file using BasicFormat by running the following command. If you are only experiencing the issue while formatting a single node, e.g. while creating an `AccessorDeclSyntax` inside a macro, you can additionally pass the type of the node as `--node-type AccessorDeclSyntax` 14 | ``` 15 | swift-parser-cli basic-format /path/to/file/that/formats/incorrectly.swift 16 | ``` 17 | 2. Remove as much code from your source file while still experiencing the formatting issue. 18 | 3. File a bug report on with the reduced source code. 19 | -------------------------------------------------------------------------------- /Sources/SwiftBasicFormat/SyntaxProtocol+Formatted.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | extension SyntaxProtocol { 20 | /// Build a syntax node from this `Buildable` and format it with the given format. 21 | public func formatted(using format: BasicFormat = BasicFormat()) -> Syntax { 22 | format.reset() 23 | return format.rewrite(self) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Sources/SwiftCompilerPlugin/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftCompilerPlugin 10 | EXCLUDE_FROM_ALL 11 | CompilerPlugin.swift 12 | ) 13 | 14 | target_link_swift_syntax_libraries(SwiftCompilerPlugin PUBLIC 15 | SwiftSyntaxMacros 16 | SwiftCompilerPluginMessageHandling 17 | ) 18 | -------------------------------------------------------------------------------- /Sources/SwiftCompilerPluginMessageHandling/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftCompilerPluginMessageHandling 10 | CompilerPluginMessageHandler.swift 11 | Diagnostics.swift 12 | LRUCache.swift 13 | Macros.swift 14 | PluginMacroExpansionContext.swift 15 | PluginMessageCompatibility.swift 16 | PluginMessages.swift 17 | JSON/CodingUtilities.swift 18 | JSON/JSON.swift 19 | JSON/JSONDecoding.swift 20 | JSON/JSONEncoding.swift 21 | StandardIOMessageConnection.swift 22 | ) 23 | 24 | target_link_swift_syntax_libraries(SwiftCompilerPluginMessageHandling PUBLIC 25 | SwiftSyntax 26 | SwiftBasicFormat 27 | SwiftDiagnostics 28 | SwiftParser 29 | SwiftSyntaxMacros 30 | SwiftSyntaxMacroExpansion 31 | SwiftOperators 32 | ) 33 | 34 | target_link_swift_syntax_libraries(SwiftCompilerPluginMessageHandling PRIVATE 35 | _SwiftSyntaxCShims 36 | ) 37 | -------------------------------------------------------------------------------- /Sources/SwiftCompilerPluginMessageHandling/JSON/JSON.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | @_spi(PluginMessage) 14 | public enum JSON { 15 | /// Encode Swift value to an UInt8 array. 16 | public static func encode(_ value: T) throws -> [UInt8] { 17 | try encodeToJSON(value: value) 18 | } 19 | 20 | /// Decode a JSON data to a Swift value. 21 | public static func decode(_ type: T.Type, from json: UnsafeBufferPointer) throws -> T { 22 | try decodeFromJSON(json: json) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Sources/SwiftCompilerPluginMessageHandling/PluginMessageCompatibility.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// Old compiler might send '.declaration' as "freeStandingDeclaration". 14 | extension PluginMessage.MacroRole { 15 | @_spi(PluginMessage) public init(from decoder: Decoder) throws { 16 | let stringValue = try decoder.singleValueContainer().decode(String.self) 17 | if let role = Self(rawValue: stringValue) { 18 | self = role 19 | return 20 | } 21 | // Accept "freeStandingDeclaration" as '.declaration'. 22 | if stringValue == "freeStandingDeclaration" { 23 | self = Self.declaration 24 | return 25 | } 26 | throw DecodingError.dataCorrupted( 27 | DecodingError.Context( 28 | codingPath: decoder.codingPath, 29 | debugDescription: "Invalid string value for MacroRole: \(stringValue)" 30 | ) 31 | ) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Sources/SwiftDiagnostics/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftDiagnostics 10 | DiagnosticDecorators/ANSIDiagnosticDecorator.swift 11 | DiagnosticDecorators/BasicDiagnosticDecorator.swift 12 | DiagnosticDecorators/DiagnosticDecorator.swift 13 | 14 | Convenience.swift 15 | Diagnostic.swift 16 | DiagnosticsFormatter.swift 17 | FixIt.swift 18 | GroupedDiagnostics.swift 19 | Message.swift 20 | Note.swift 21 | ) 22 | 23 | target_link_swift_syntax_libraries(SwiftDiagnostics PUBLIC 24 | SwiftSyntax) 25 | -------------------------------------------------------------------------------- /Sources/SwiftIDEUtils/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftIDEUtils 10 | DeclNameLocation.swift 11 | FixItApplier.swift 12 | NameMatcher.swift 13 | SwiftIDEUtilsCompatibility.swift 14 | Syntax+Classifications.swift 15 | SyntaxClassification.swift 16 | SyntaxClassifier.swift 17 | Utils.swift 18 | ) 19 | 20 | target_link_swift_syntax_libraries(SwiftIDEUtils PUBLIC 21 | SwiftParser 22 | SwiftSyntax) 23 | -------------------------------------------------------------------------------- /Sources/SwiftIDEUtils/Utils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | internal import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | extension Range { 20 | /// Shift the range `utf8Offset` bytes to the right, ie. add `utf8Offset` to the upper and lower bound. 21 | func advanced(by utf8Offset: Int) -> Range { 22 | return self.lowerBound.advanced(by: utf8Offset).. 2 | 3 | 4 | 5 | CFBundleName 6 | SwiftIfConfig 7 | CFBundleDisplayName 8 | SwiftIfConfig 9 | CFBundleIdentifier 10 | com.apple.swift-if-config 11 | CFBundleDevelopmentRegion 12 | en 13 | CFBundleIconFile 14 | DocumentationIcon 15 | CFBundleIconName 16 | DocumentationIcon 17 | CFBundlePackageType 18 | DOCS 19 | CFBundleShortVersionString 20 | 0.1.0 21 | CDDefaultCodeListingLanguage 22 | swift 23 | CFBundleVersion 24 | 0.1.0 25 | CDAppleDefaultAvailability 26 | 27 | SwiftIfConfig 28 | 29 | 30 | name 31 | macOS 32 | version 33 | 10.15 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Sources/SwiftLexicalLookup/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftLexicalLookup 10 | IdentifiableSyntax.swift 11 | LookupName.swift 12 | LookupResult.swift 13 | SimpleLookupQueries.swift 14 | LookupConfig.swift 15 | 16 | Scopes/CanInterleaveResultsLaterScopeSyntax.swift 17 | Scopes/FunctionScopeSyntax.swift 18 | Scopes/GenericParameterScopeSyntax.swift 19 | Scopes/IntroducingToSequentialParentScopeSyntax.swift 20 | Scopes/LookInMembersScopeSyntax.swift 21 | Scopes/NominalTypeDeclSyntax.swift 22 | Scopes/ScopeImplementations.swift 23 | Scopes/ScopeSyntax.swift 24 | Scopes/SequentialScopeSyntax.swift 25 | Scopes/WithGenericParametersScopeSyntax.swift 26 | ) 27 | 28 | target_link_swift_syntax_libraries(SwiftLexicalLookup PUBLIC 29 | SwiftSyntax 30 | SwiftIfConfig) 31 | 32 | -------------------------------------------------------------------------------- /Sources/SwiftLexicalLookup/Scopes/CanInterleaveResultsLaterScopeSyntax.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | 15 | protocol CanInterleaveResultsLaterScopeSyntax: ScopeSyntax { 16 | /// Perform lookup in this scope and later introduce results 17 | /// passed as `resultsToInterleave`. 18 | /// The exact behavior depends on a specific scope. 19 | func lookupWithInterleavedResults( 20 | _ identifier: Identifier?, 21 | at lookUpPosition: AbsolutePosition, 22 | with config: LookupConfig, 23 | resultsToInterleave: [LookupResult] 24 | ) -> [LookupResult] 25 | } 26 | -------------------------------------------------------------------------------- /Sources/SwiftLexicalLookup/Scopes/IntroducingToSequentialParentScopeSyntax.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | 15 | protocol IntroducingToSequentialParentScopeSyntax: ScopeSyntax { 16 | /// Returns all names introduced to parent. 17 | var namesIntroducedToSequentialParent: [LookupName] { get } 18 | 19 | /// Returns results matching lookup that should be 20 | /// interleaved with results of the sequential parent. 21 | func lookupFromSequentialParent( 22 | _ identifier: Identifier?, 23 | at lookUpPosition: AbsolutePosition, 24 | with config: LookupConfig 25 | ) -> [LookupResult] 26 | } 27 | -------------------------------------------------------------------------------- /Sources/SwiftLexicalLookup/Scopes/LookInMembersScopeSyntax.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | 15 | public protocol LookInMembersScopeSyntax: SyntaxProtocol { 16 | /// Position used for member lookup. 17 | var lookupMembersPosition: AbsolutePosition { get } 18 | } 19 | -------------------------------------------------------------------------------- /Sources/SwiftLexicalLookup/SwiftLexicalLookup.docc/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleName 6 | SwiftLexicalLookup 7 | CFBundleDisplayName 8 | SwiftLexicalLookup 9 | CFBundleIdentifier 10 | com.apple.swift-lexical-lookup 11 | CFBundleDevelopmentRegion 12 | en 13 | CFBundleIconFile 14 | DocumentationIcon 15 | CFBundleIconName 16 | DocumentationIcon 17 | CFBundlePackageType 18 | DOCS 19 | CFBundleShortVersionString 20 | 0.1.0 21 | CDDefaultCodeListingLanguage 22 | swift 23 | CFBundleVersion 24 | 0.1.0 25 | CDAppleDefaultAvailability 26 | 27 | SwiftLexicalLookup 28 | 29 | 30 | name 31 | macOS 32 | version 33 | 10.15 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Sources/SwiftLibraryPluginProvider/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2024 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftLibraryPluginProvider 10 | LibraryPluginProvider.swift 11 | ) 12 | target_link_swift_syntax_libraries(SwiftLibraryPluginProvider PRIVATE 13 | _SwiftLibraryPluginProviderCShims 14 | ) 15 | target_link_swift_syntax_libraries(SwiftLibraryPluginProvider PUBLIC 16 | SwiftSyntaxMacros 17 | SwiftCompilerPluginMessageHandling 18 | ) 19 | -------------------------------------------------------------------------------- /Sources/SwiftOperators/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftOperators 10 | Operator.swift 11 | OperatorError+Diagnostics.swift 12 | OperatorError.swift 13 | OperatorTable+Defaults.swift 14 | OperatorTable+Folding.swift 15 | OperatorTable+Semantics.swift 16 | OperatorTable.swift 17 | PrecedenceGraph.swift 18 | PrecedenceGroup.swift 19 | SyntaxSynthesis.swift 20 | ) 21 | 22 | target_link_swift_syntax_libraries(SwiftOperators PUBLIC 23 | SwiftSyntax 24 | SwiftDiagnostics 25 | SwiftParser) 26 | -------------------------------------------------------------------------------- /Sources/SwiftOperators/SwiftOperators.docc/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleName 6 | SwiftOperators 7 | CFBundleDisplayName 8 | SwiftOperators 9 | CFBundleIdentifier 10 | com.apple.swift-operators 11 | CFBundleDevelopmentRegion 12 | en 13 | CFBundleIconFile 14 | DocumentationIcon 15 | CFBundleIconName 16 | DocumentationIcon 17 | CFBundlePackageType 18 | DOCS 19 | CFBundleShortVersionString 20 | 0.1.0 21 | CDDefaultCodeListingLanguage 22 | swift 23 | CFBundleVersion 24 | 0.1.0 25 | CDAppleDefaultAvailability 26 | 27 | SwiftOperators 28 | 29 | 30 | name 31 | macOS 32 | version 33 | 10.15 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Sources/SwiftParser/Lexer/Lexer.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// A lexical analyzer for the Swift programming language. 14 | /// 15 | /// - Seealso: ``Lexer/Lexeme`` 16 | /// - Seealso: ``Lexer/Cursor`` 17 | @_spi(Testing) 18 | public enum Lexer { 19 | } 20 | -------------------------------------------------------------------------------- /Sources/SwiftParser/README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | The `SwiftParser` framework implements a parser that accepts Swift source text as input and produces a SwiftSyntax syntax tree. 4 | 5 | ## Quickstart 6 | 7 | The easiest way to parse Swift source code is to call the `Parser.parse` method, providing it with a string containing the source code: 8 | 9 | ```swift 10 | import SwiftParser 11 | #if compiler(>=6) 12 | internal import SwiftSyntax 13 | #else 14 | import SwiftSyntax 15 | #endif 16 | 17 | let sourceText = 18 | """ 19 | func greeting(name: String) { 20 | print("Hello, \(name)!") 21 | } 22 | """ 23 | 24 | // Parse the source code in sourceText into a syntax tree 25 | let sourceFile: SourceFileSyntax = Parser.parse(source: sourceText) 26 | 27 | // The "description" of the source tree is the source-accurate view of what was parsed. 28 | assert(sourceFile.description == sourceText) 29 | 30 | // Visualize the complete syntax tree. 31 | dump(sourceFile) 32 | ``` 33 | -------------------------------------------------------------------------------- /Sources/SwiftParser/SwiftVersion.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | extension Parser { 14 | /// A Swift language version. 15 | public enum SwiftVersion: Comparable, Sendable { 16 | case v4 17 | case v5 18 | case v6 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Sources/SwiftParserDiagnostics/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftParserDiagnostics 10 | DiagnosticExtensions.swift 11 | LexerDiagnosticMessages.swift 12 | MissingNodesError.swift 13 | MissingTokenError.swift 14 | MultiLineStringLiteralDiagnosticsGenerator.swift 15 | ParserDiagnosticMessages.swift 16 | ParseDiagnosticsGenerator.swift 17 | PresenceUtils.swift 18 | SyntaxExtensions.swift 19 | Utils.swift 20 | 21 | generated/ChildNameForDiagnostics.swift 22 | generated/SyntaxKindNameForDiagnostics.swift 23 | generated/TokenNameForDiagnostics.swift 24 | ) 25 | 26 | target_link_swift_syntax_libraries(SwiftParserDiagnostics PUBLIC 27 | SwiftBasicFormat 28 | SwiftDiagnostics 29 | SwiftParser 30 | SwiftSyntax) 31 | -------------------------------------------------------------------------------- /Sources/SwiftRefactor/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftRefactor 10 | AddSeparatorsToIntegerLiteral.swift 11 | CallToTrailingClosures.swift 12 | ConvertComputedPropertyToStored.swift 13 | ConvertComputedPropertyToZeroParameterFunction.swift 14 | ConvertStoredPropertyToComputed.swift 15 | ConvertZeroParameterFunctionToComputedProperty.swift 16 | ExpandEditorPlaceholder.swift 17 | FormatRawStringLiteral.swift 18 | IntegerLiteralUtilities.swift 19 | MigrateToNewIfLetSyntax.swift 20 | OpaqueParameterToGeneric.swift 21 | RefactoringProvider.swift 22 | RemoveSeparatorsFromIntegerLiteral.swift 23 | SyntaxUtils.swift 24 | ) 25 | 26 | target_link_swift_syntax_libraries(SwiftRefactor PUBLIC 27 | SwiftBasicFormat 28 | SwiftParser 29 | SwiftSyntax 30 | SwiftSyntaxBuilder 31 | ) 32 | -------------------------------------------------------------------------------- /Sources/SwiftRefactor/RemoveSeparatorsFromIntegerLiteral.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | /// Format an integer literal by removing any existing separators. 20 | /// 21 | /// ## Before 22 | /// 23 | /// ```swift 24 | /// 123_456_789 25 | /// 0xF_FFFF_FFFF 26 | /// ``` 27 | /// ## After 28 | /// 29 | /// ```swift 30 | /// 123456789 31 | /// 0xFFFFFFFFF 32 | /// ``` 33 | public struct RemoveSeparatorsFromIntegerLiteral: SyntaxRefactoringProvider { 34 | public static func refactor(syntax lit: IntegerLiteralExprSyntax, in context: Void) -> IntegerLiteralExprSyntax? { 35 | guard lit.literal.text.contains("_") else { 36 | return lit 37 | } 38 | let formattedText = lit.literal.text.filter({ $0 != "_" }) 39 | return lit.with(\.literal, lit.literal.with(\.tokenKind, .integerLiteral(formattedText))) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Sources/SwiftRefactor/SyntaxUtils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | internal import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | extension TokenSyntax { 20 | var trivia: Trivia { 21 | return leadingTrivia + trailingTrivia 22 | } 23 | } 24 | 25 | extension Trivia { 26 | var droppingLeadingWhitespace: Trivia { 27 | return Trivia(pieces: self.drop(while: \.isWhitespace)) 28 | } 29 | 30 | var droppingTrailingWhitespace: Trivia { 31 | return Trivia(pieces: self.reversed().drop(while: \.isWhitespace).reversed()) 32 | } 33 | } 34 | 35 | extension TypeSyntax { 36 | var isVoid: Bool { 37 | switch self.as(TypeSyntaxEnum.self) { 38 | case .identifierType(let identifierType) where identifierType.name.text == "Void": return true 39 | case .tupleType(let tupleType) where tupleType.elements.isEmpty: return true 40 | default: return false 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax-all/empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This is a fake target that depends on all targets in the package. 14 | // We need to define it manually because the `SwiftSyntax-Package` target doesn't exist for `swift build`. 15 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/AbsolutePosition.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// An absolute position in a source file as text - the absolute utf8Offset from 14 | /// the start of the file. 15 | public struct AbsolutePosition: Comparable, Hashable, Sendable { 16 | public let utf8Offset: Int 17 | 18 | static let startOfFile = AbsolutePosition(utf8Offset: 0) 19 | 20 | public init(utf8Offset: Int) { 21 | self.utf8Offset = utf8Offset 22 | } 23 | 24 | public func advanced(by offset: Int) -> AbsolutePosition { 25 | return AbsolutePosition(utf8Offset: self.utf8Offset + offset) 26 | } 27 | 28 | public static func < (lhs: AbsolutePosition, rhs: AbsolutePosition) -> Bool { 29 | return lhs.utf8Offset < rhs.utf8Offset 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Glossary.md: -------------------------------------------------------------------------------- 1 | # Glossary 2 | 3 | Glossary of terms and abbreviations used in SwiftSyntax 4 | 5 | ## Abbreviations and Terms 6 | 7 | To avoid ongoing repetition of common long terms, SwiftSyntax uses a couple of abbreviations that are common in compiler projects. 8 | 9 | 10 | **Decl** Abbreviation for *Declaration* 11 | 12 | **Expr** Abbreviation for *Expression* 13 | 14 | **IfConfig** Abbrevation for *If Configuration*. Refers to `#if` clauses in the source code. 15 | 16 | **Layout Node** A layout node can have an arbitrary number of children and provides structure to the syntax tree. All ``Syntax`` nodes that aren’t ``TokenSyntax`` are layout nodes. For example a ``StructDeclSyntax`` consists of, among others, of the `struct` keyword, the name and the `memberBlock`. The latter is again a layout node that contains multiple children. Layout nodes never represent any source code in the syntax tree by themselves. All source code within the syntax tree is represented by *tokens*. 17 | 18 | **Node** A *layout node* or *token* 19 | 20 | **RawSyntax** The underlying storage of syntax nodes. These are manually memory managed inside an *arena*. You should not need to interact with them unless contributing to swift-syntax. 21 | 22 | **Stmt** Abbreviation for *Statement* 23 | 24 | **Token** See ``TokenSyntax`` 25 | 26 | **Trivia** See ``Trivia`` 27 | 28 | 29 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Formatter.step1.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | @main struct ImportFormatter { 4 | static func main() { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Formatter.step2.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | @main struct ImportFormatter { 4 | static func main() { 5 | guard CommandLine.arguments.count == 2 else { 6 | print("Not enough arguments!") 7 | return 8 | } 9 | 10 | let filePath = CommandLine.arguments[1] 11 | guard FileManager.default.fileExists(atPath: filePath) else { 12 | print("File doesn't exist at path: \(filePath)") 13 | return 14 | } 15 | 16 | guard let file = try? String(contentsOfFile: filePath) else { 17 | print("File at path isn't readable: \(filePath)") 18 | return 19 | } 20 | 21 | let formattedFile = ImportFormatter().formatImports(in: file) 22 | print(formattedFile) 23 | } 24 | 25 | func formatImports(in file: String) -> SourceFileSyntax { 26 | /* Formatter here */ 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Formatter.step3.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftParser 3 | import SwiftSyntax 4 | 5 | @main struct ImportFormatter { 6 | static func main() { 7 | guard CommandLine.arguments.count == 2 else { 8 | print("Not enough arguments!") 9 | return 10 | } 11 | 12 | let filePath = CommandLine.arguments[1] 13 | guard FileManager.default.fileExists(atPath: filePath) else { 14 | print("File doesn't exist at path: \(filePath)") 15 | return 16 | } 17 | 18 | guard let file = try? String(contentsOfFile: filePath) else { 19 | print("File at path isn't readable: \(filePath)") 20 | return 21 | } 22 | 23 | let formattedFile = ImportFormatter().formatImports(in: file) 24 | print(formattedFile) 25 | } 26 | 27 | func formatImports(in file: String) -> SourceFileSyntax { 28 | /* Formatter here */ 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Formatter.step4.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftParser 3 | import SwiftSyntax 4 | 5 | @main struct ImportFormatter { 6 | static func main() { 7 | guard CommandLine.arguments.count == 2 else { 8 | print("Not enough arguments!") 9 | return 10 | } 11 | 12 | let filePath = CommandLine.arguments[1] 13 | guard FileManager.default.fileExists(atPath: filePath) else { 14 | print("File doesn't exist at path: \(filePath)") 15 | return 16 | } 17 | 18 | guard let file = try? String(contentsOfFile: filePath) else { 19 | print("File at path isn't readable: \(filePath)") 20 | return 21 | } 22 | 23 | let formattedFile = ImportFormatter().formatImports(in: file) 24 | print(formattedFile) 25 | } 26 | 27 | func formatImports(in file: String) -> SourceFileSyntax { 28 | let sourceFile = Parser.parse(source: file) 29 | /* format source file */ 30 | return sourceFile 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Formatter.step5.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftParser 3 | import SwiftSyntax 4 | 5 | @main struct ImportFormatter { 6 | static func main() { 7 | guard CommandLine.arguments.count == 2 else { 8 | print("Not enough arguments!") 9 | return 10 | } 11 | 12 | let filePath = CommandLine.arguments[1] 13 | guard FileManager.default.fileExists(atPath: filePath) else { 14 | print("File doesn't exist at path: \(filePath)") 15 | return 16 | } 17 | 18 | guard let file = try? String(contentsOfFile: filePath) else { 19 | print("File at path isn't readable: \(filePath)") 20 | return 21 | } 22 | 23 | let formattedFile = ImportFormatter().formatImports(in: file) 24 | print(formattedFile) 25 | } 26 | 27 | func formatImports(in file: String) -> SourceFileSyntax { 28 | let sourceFile = Parser.parse(source: file) 29 | var items = classifyItems(in: sourceFile) 30 | return sourceFile 31 | } 32 | 33 | enum Item { 34 | case `import`(ImportDeclSyntax, CodeBlockItemSyntax) 35 | case other(CodeBlockItemSyntax) 36 | } 37 | 38 | func classifyItems(in file: SourceFileSyntax) -> [Item] { 39 | /* Classify items here */ 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Package.step1.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "importformatter", 8 | products: [ 9 | // Products define the executables and libraries a package produces, making them visible to other packages. 10 | .library( 11 | name: "importformatter", 12 | targets: ["importformatter"] 13 | ) 14 | ], 15 | targets: [ 16 | // Targets are the basic building blocks of a package, defining a module or a test suite. 17 | // Targets can depend on other targets in this package and products from dependencies. 18 | .target( 19 | name: "importformatter" 20 | ), 21 | .testTarget( 22 | name: "importformatterTests", 23 | dependencies: ["importformatter"] 24 | ), 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Package.step2.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "importformatter", 8 | products: [ 9 | // Products define the executables and libraries a package produces, making them visible to other packages. 10 | .executable( 11 | name: "importformatter", 12 | targets: ["importformatter"] 13 | ) 14 | ], 15 | targets: [ 16 | // Targets are the basic building blocks of a package, defining a module or a test suite. 17 | // Targets can depend on other targets in this package and products from dependencies. 18 | .executableTarget( 19 | name: "importformatter" 20 | ), 21 | .testTarget( 22 | name: "importformatterTests", 23 | dependencies: ["importformatter"] 24 | ), 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Package.step3.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "importformatter", 8 | products: [ 9 | // Products define the executables and libraries a package produces, making them visible to other packages. 10 | .executable( 11 | name: "importformatter", 12 | targets: ["importformatter"] 13 | ) 14 | ], 15 | dependencies: [ 16 | // Dependencies declare other packages that this package depends on. 17 | .package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main") 18 | ], 19 | targets: [ 20 | // Targets are the basic building blocks of a package, defining a module or a test suite. 21 | // Targets can depend on other targets in this package and products from dependencies. 22 | .executableTarget( 23 | name: "importformatter" 24 | ), 25 | .testTarget( 26 | name: "importformatterTests", 27 | dependencies: ["importformatter"] 28 | ), 29 | ] 30 | ) 31 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Package.step4.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "importformatter", 8 | products: [ 9 | // Products define the executables and libraries a package produces, making them visible to other packages. 10 | .executable( 11 | name: "importformatter", 12 | targets: ["importformatter"] 13 | ) 14 | ], 15 | dependencies: [ 16 | // Dependencies declare other packages that this package depends on. 17 | .package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main") 18 | ], 19 | targets: [ 20 | // Targets are the basic building blocks of a package, defining a module or a test suite. 21 | // Targets can depend on other targets in this package and products from dependencies. 22 | .executableTarget( 23 | name: "importformatter", 24 | dependencies: [ 25 | .product(name: "SwiftSyntax", package: "swift-syntax"), 26 | .product(name: "SwiftParser", package: "swift-syntax"), 27 | ] 28 | ), 29 | .testTarget( 30 | name: "importformatterTests", 31 | dependencies: ["importformatter"] 32 | ), 33 | ] 34 | ) 35 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/Package.step5.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "importformatter", 8 | platforms: [ 9 | .macOS(.v10_15) 10 | ], 11 | products: [ 12 | // Products define the executables and libraries a package produces, making them visible to other packages. 13 | .executable( 14 | name: "importformatter", 15 | targets: ["importformatter"] 16 | ) 17 | ], 18 | dependencies: [ 19 | // Dependencies declare other packages that this package depends on. 20 | .package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main") 21 | ], 22 | targets: [ 23 | // Targets are the basic building blocks of a package, defining a module or a test suite. 24 | // Targets can depend on other targets in this package and products from dependencies. 25 | .executableTarget( 26 | name: "importformatter", 27 | dependencies: [ 28 | .product(name: "SwiftSyntax", package: "swift-syntax"), 29 | .product(name: "SwiftParser", package: "swift-syntax"), 30 | ] 31 | ), 32 | .testTarget( 33 | name: "importformatterTests", 34 | dependencies: ["importformatter"] 35 | ), 36 | ] 37 | ) 38 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/importformatter-package-project.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-syntax/8d2c20fec97eaea0b843b000f25e83723e265d60/Sources/SwiftSyntax/Documentation.docc/Resources/importformatter-package-project.png -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/swift-syntax.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-syntax/8d2c20fec97eaea0b843b000f25e83723e265d60/Sources/SwiftSyntax/Documentation.docc/Resources/swift-syntax.png -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Resources/swift-syntax@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-syntax/8d2c20fec97eaea0b843b000f25e83723e265d60/Sources/SwiftSyntax/Documentation.docc/Resources/swift-syntax@2x.png -------------------------------------------------------------------------------- /Sources/SwiftSyntax/Documentation.docc/Tutorials/Tutorial Table of Contents.tutorial: -------------------------------------------------------------------------------- 1 | @Tutorials(name: "SwiftSyntax") { 2 | @Intro(title: "Introduction to SwiftSyntax") { 3 | SwiftSyntax provides the foundation for tools that inspect, manipulate, 4 | and transform Swift source code. 5 | } 6 | 7 | @Chapter(name: "SwiftSyntax By Example") { 8 | @Image(source: "swift-syntax.png", alt: "") 9 | 10 | Explore the SwiftSyntax API by building a tool that sorts imports in a 11 | Swift file. 12 | 13 | @TutorialReference(tutorial: "doc:SwiftSyntax-By-Example") 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/SourcePresence.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// An indicator of whether a Syntax node was found or written in the source. 14 | /// 15 | /// A `missing` node does not mean, necessarily, that the source item is 16 | /// considered "implicit", but rather that it was not found in the source. 17 | public enum SourcePresence: Sendable { 18 | /// The syntax was authored by a human and found, or was generated. 19 | case present 20 | 21 | /// The syntax was expected or optional, but not found in the source. 22 | case missing 23 | } 24 | -------------------------------------------------------------------------------- /Sources/SwiftSyntax/SyntaxHashable.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// Protocol that provides a common Hashable implementation for all syntax nodes 14 | public protocol SyntaxHashable: Hashable { 15 | var _syntaxNode: Syntax { get } 16 | } 17 | 18 | extension SyntaxHashable { 19 | public func hash(into hasher: inout Hasher) { 20 | return _syntaxNode.id.hash(into: &hasher) 21 | } 22 | 23 | public static func == (lhs: Self, rhs: Self) -> Bool { 24 | return lhs._syntaxNode.id == rhs._syntaxNode.id 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxBuilder/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftSyntaxBuilder 10 | ConvenienceInitializers.swift 11 | DeclSyntaxParseable.swift 12 | Indenter.swift 13 | ListBuilder.swift 14 | ResultBuilderExtensions.swift 15 | SwiftSyntaxBuilderCompatibility.swift 16 | Syntax+StringInterpolation.swift 17 | SyntaxNodeWithBody.swift 18 | SyntaxParsable+ExpressibleByStringInterpolation.swift 19 | ValidatingSyntaxNodes.swift 20 | WithTrailingCommaSyntax+EnsuringTrailingComma.swift 21 | 22 | 23 | generated/BuildableNodes.swift 24 | generated/ResultBuilders.swift 25 | generated/RenamedChildrenBuilderCompatibility.swift 26 | generated/SyntaxExpressibleByStringInterpolationConformances.swift 27 | ) 28 | 29 | # Don't depend on OSLog when we are building for the compiler. 30 | # In that case we don't want any dependencies on the SDK. 31 | target_compile_options(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntaxBuilder PRIVATE 32 | $<$:-D;SWIFTSYNTAX_NO_OSLOG_DEPENDENCY>) 33 | 34 | target_link_swift_syntax_libraries(SwiftSyntaxBuilder PUBLIC 35 | SwiftBasicFormat 36 | SwiftParser 37 | SwiftParserDiagnostics 38 | SwiftSyntax 39 | ) 40 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxBuilder/Documentation.docc/Index.md: -------------------------------------------------------------------------------- 1 | # ``SwiftSyntaxBuilder`` 2 | 3 | SwiftSyntaxBuilder is a tool for generating Swift code in a convenient way using result builders. 4 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxBuilder/WithTrailingCommaSyntax+EnsuringTrailingComma.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | internal import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | extension WithTrailingCommaSyntax { 20 | func ensuringTrailingComma() -> Self { 21 | if trailingComma == nil { 22 | return self.with(\.trailingComma, .commaToken()) 23 | } else { 24 | return self 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacroExpansion/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_swift_syntax_library(SwiftSyntaxMacroExpansion 2 | BasicMacroExpansionContext.swift 3 | FunctionParameterUtils.swift 4 | IndentationUtils.swift 5 | MacroArgument.swift 6 | MacroExpansion.swift 7 | MacroExpansionDiagnosticMessages.swift 8 | MacroReplacement.swift 9 | MacroSpec.swift 10 | MacroSystem.swift 11 | ) 12 | 13 | target_link_swift_syntax_libraries(SwiftSyntaxMacroExpansion PUBLIC 14 | SwiftBasicFormat 15 | SwiftDiagnostics 16 | SwiftOperators 17 | SwiftSyntax 18 | SwiftSyntaxBuilder 19 | SwiftSyntaxMacros 20 | ) 21 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacroExpansion/FunctionParameterUtils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | extension FunctionParameterSyntax { 20 | /// Retrieve the name of the parameter as it is used in source. 21 | /// 22 | /// Example: 23 | /// 24 | /// func f(a: Int, _ b: Int, c see: Int) { ... } 25 | /// 26 | /// The parameter names for these three parameters are `a`, `b`, and `see`, 27 | /// respectively. 28 | @_spi(Testing) 29 | public var parameterName: TokenSyntax? { 30 | // If there were two names, the second is the parameter name. 31 | if let secondName { 32 | if secondName.text == "_" { 33 | return nil 34 | } 35 | 36 | return secondName 37 | } 38 | 39 | if firstName.text == "_" { 40 | return nil 41 | } 42 | 43 | return firstName 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacroExpansion/MacroExpansionDiagnosticMessages.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntaxMacros 15 | #else 16 | import SwiftSyntaxMacros 17 | #endif 18 | 19 | @available(*, deprecated, message: "MacroExpansionErrorMessage has been moved to the SwiftSyntaxMacros module") 20 | public typealias MacroExpansionErrorMessage = SwiftSyntaxMacros.MacroExpansionErrorMessage 21 | 22 | @available(*, deprecated, message: "MacroExpansionWarningMessage has been moved to the SwiftSyntaxMacros module") 23 | public typealias MacroExpansionWarningMessage = SwiftSyntaxMacros.MacroExpansionWarningMessage 24 | 25 | @available(*, deprecated, message: "MacroExpansionFixItMessage has been moved to the SwiftSyntaxMacros module") 26 | public typealias MacroExpansionFixItMessage = SwiftSyntaxMacros.MacroExpansionFixItMessage 27 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | add_swift_syntax_library(SwiftSyntaxMacros 10 | MacroProtocols/AccessorMacro.swift 11 | MacroProtocols/AttachedMacro.swift 12 | MacroProtocols/BodyMacro.swift 13 | MacroProtocols/CodeItemMacro.swift 14 | MacroProtocols/DeclarationMacro.swift 15 | MacroProtocols/ExpressionMacro.swift 16 | MacroProtocols/ExtensionMacro.swift 17 | MacroProtocols/FreestandingMacro.swift 18 | MacroProtocols/Macro.swift 19 | MacroProtocols/Macro+Format.swift 20 | MacroProtocols/MemberAttributeMacro.swift 21 | MacroProtocols/MemberMacro.swift 22 | MacroProtocols/PeerMacro.swift 23 | MacroProtocols/PreambleMacro.swift 24 | 25 | AbstractSourceLocation.swift 26 | MacroExpansionContext.swift 27 | MacroExpansionDiagnosticMessages.swift 28 | Syntax+LexicalContext.swift 29 | ) 30 | 31 | target_link_swift_syntax_libraries(SwiftSyntaxMacros PUBLIC 32 | SwiftSyntaxBuilder 33 | ) 34 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/AccessorMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | /// Describes a macro that adds accessors to a given declaration. 20 | public protocol AccessorMacro: AttachedMacro { 21 | /// Expand a macro that's expressed as a custom attribute attached to 22 | /// the given declaration. The result is a set of accessors for the 23 | /// declaration. 24 | static func expansion( 25 | of node: AttributeSyntax, 26 | providingAccessorsOf declaration: some DeclSyntaxProtocol, 27 | in context: some MacroExpansionContext 28 | ) throws -> [AccessorDeclSyntax] 29 | } 30 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/AttachedMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// Describes a macro that is attached, meaning that it is used with 14 | /// custom attribute syntax and attached to another entity. 15 | public protocol AttachedMacro: Macro { 16 | } 17 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/CodeItemMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | /// Describes a macro that forms code items in a function or closure body. 20 | public protocol CodeItemMacro: FreestandingMacro { 21 | /// Expand a macro described by the given freestanding macro expansion 22 | /// declaration within the given context to produce a set of declarations. 23 | static func expansion( 24 | of node: some FreestandingMacroExpansionSyntax, 25 | in context: some MacroExpansionContext 26 | ) throws -> [CodeBlockItemSyntax] 27 | } 28 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/ExpressionMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | /// Describes a macro that is explicitly expanded as an expression. 20 | public protocol ExpressionMacro: FreestandingMacro { 21 | /// Expand a macro described by the given freestanding macro expansion 22 | /// within the given context to produce a replacement expression. 23 | static func expansion( 24 | of node: some FreestandingMacroExpansionSyntax, 25 | in context: some MacroExpansionContext 26 | ) throws -> ExprSyntax 27 | } 28 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/FreestandingMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// Describes a macro that is freestanding, meaning that it is used with the 14 | /// `#` syntax. 15 | public protocol FreestandingMacro: Macro { 16 | } 17 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/Macro+Format.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | /// Describes the mode to use to format the result of an expansion. 14 | public enum FormatMode: Sendable { 15 | /// Perform a basic format of the expansion. This is primarily for inserting 16 | /// whitespace as required (eg. between two keywords), but also adds simple 17 | /// newline and indentation. 18 | case auto 19 | 20 | /// Disable automatically formatting the expanded macro. Trivia must be 21 | /// manually inserted where required (eg. adding spaces between keywords). 22 | case disabled 23 | } 24 | 25 | extension Macro { 26 | public static var formatMode: FormatMode { 27 | return .auto 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/Macro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6.2) 14 | /// Describes a macro. 15 | public protocol Macro: SendableMetatype { 16 | /// How the resulting expansion should be formatted, `.auto` by default. 17 | /// Use `.disabled` for the expansion to be used as is. 18 | static var formatMode: FormatMode { get } 19 | } 20 | #else 21 | /// Describes a macro. 22 | public protocol Macro { 23 | /// How the resulting expansion should be formatted, `.auto` by default. 24 | /// Use `.disabled` for the expansion to be used as is. 25 | static var formatMode: FormatMode { get } 26 | } 27 | #endif 28 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/MacroProtocols/PeerMacro.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | public import SwiftSyntax 15 | #else 16 | import SwiftSyntax 17 | #endif 18 | 19 | public protocol PeerMacro: AttachedMacro { 20 | /// Expand a macro described by the given custom attribute and 21 | /// attached to the given declaration and evaluated within a 22 | /// particular expansion context. 23 | /// 24 | /// The macro expansion can introduce "peer" declarations that sit alongside 25 | /// the given declaration. 26 | static func expansion( 27 | of node: AttributeSyntax, 28 | providingPeersOf declaration: some DeclSyntaxProtocol, 29 | in context: some MacroExpansionContext 30 | ) throws -> [DeclSyntax] 31 | } 32 | -------------------------------------------------------------------------------- /Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.docc/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleName 6 | SwiftSyntaxMacros 7 | CFBundleDisplayName 8 | SwiftSyntaxMacros 9 | CFBundleIdentifier 10 | com.apple.swift-syntax-macros 11 | CFBundleDevelopmentRegion 12 | en 13 | CFBundleIconFile 14 | DocumentationIcon 15 | CFBundleIconName 16 | DocumentationIcon 17 | CFBundlePackageType 18 | DOCS 19 | CFBundleShortVersionString 20 | 0.1.0 21 | CDDefaultCodeListingLanguage 22 | swift 23 | CFBundleVersion 24 | 0.1.0 25 | CDAppleDefaultAvailability 26 | 27 | SwiftSyntaxMacros 28 | 29 | 30 | name 31 | macOS 32 | version 33 | 10.15 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift.org open source project 2 | # 3 | # Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See http://swift.org/LICENSE.txt for license information 7 | # See http://swift.org/CONTRIBUTORS.txt for Swift project authors 8 | 9 | # Version Marker Modules. 10 | # See the 'Macro Versioning.md' document for more details. 11 | add_library(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntax509 STATIC 12 | SwiftSyntax509/Empty.swift) 13 | add_library(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntax510 STATIC 14 | SwiftSyntax510/Empty.swift) 15 | add_library(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntax600 STATIC 16 | SwiftSyntax600/Empty.swift) 17 | add_library(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntax601 STATIC 18 | SwiftSyntax601/Empty.swift) 19 | add_library(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntax602 STATIC 20 | SwiftSyntax602/Empty.swift) 21 | add_library(${SWIFTSYNTAX_TARGET_NAMESPACE}SwiftSyntax603 STATIC 22 | SwiftSyntax603/Empty.swift) 23 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/SwiftSyntax509/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // The SwiftSyntax509 module is intentionally empty. 14 | // It serves as an indicator which version of swift-syntax a package is building against. 15 | // See the 'Macro Versioning.md' document for more details. 16 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/SwiftSyntax510/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // The SwiftSyntax510 module is intentionally empty. 14 | // It serves as an indicator which version of swift-syntax a package is building against. 15 | // See the 'Macro Versioning.md' document for more details. 16 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/SwiftSyntax600/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // The SwiftSyntax600 module is intentionally empty. 14 | // It serves as an indicator which version of swift-syntax a package is building against. 15 | // See the 'Macro Versioning.md' document for more details. 16 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/SwiftSyntax601/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // The SwiftSyntax601 module is intentionally empty. 14 | // It serves as an indicator which version of swift-syntax a package is building against. 15 | // See the 'Macro Versioning.md' document for more details. 16 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/SwiftSyntax602/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // The SwiftSyntax602 module is intentionally empty. 14 | // It serves as an indicator which version of swift-syntax a package is building against. 15 | // See the 'Macro Versioning.md' document for more details. 16 | -------------------------------------------------------------------------------- /Sources/VersionMarkerModules/SwiftSyntax603/Empty.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // The SwiftSyntax603 module is intentionally empty. 14 | // It serves as an indicator which version of swift-syntax a package is building against. 15 | // See the 'Macro Versioning.md' document for more details. 16 | -------------------------------------------------------------------------------- /Sources/_InstructionCounter/include/InstructionsExecuted.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #include 14 | 15 | /// On macOS returns the number of instructions the process has executed since 16 | /// it was launched, on all other platforms returns 0. 17 | uint64_t getInstructionsExecuted(); 18 | -------------------------------------------------------------------------------- /Sources/_InstructionCounter/src/InstructionsExecuted.c: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if __APPLE__ 14 | #include 15 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 16 | #define TARGET_IS_MACOS 1 17 | #endif 18 | #endif 19 | 20 | #include "InstructionsExecuted.h" 21 | 22 | #ifdef TARGET_IS_MACOS 23 | #include 24 | #include 25 | #include 26 | 27 | uint64_t getInstructionsExecuted() { 28 | struct rusage_info_v4 ru; 29 | if (proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)&ru) == 0) { 30 | return ru.ri_instructions; 31 | } 32 | return 0; 33 | } 34 | #else 35 | uint64_t getInstructionsExecuted() { 36 | return 0; 37 | } 38 | #endif 39 | -------------------------------------------------------------------------------- /Sources/_SwiftLibraryPluginProviderCShims/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target ${SWIFTSYNTAX_TARGET_NAMESPACE}_SwiftLibraryPluginProviderCShims) 2 | add_library(${target} STATIC 3 | LoadLibrary.c 4 | ) 5 | target_include_directories(${target} PUBLIC "include") 6 | set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS ${target}) 7 | install(TARGETS ${target} EXPORT SwiftSyntaxTargets) 8 | -------------------------------------------------------------------------------- /Sources/_SwiftLibraryPluginProviderCShims/LoadLibrary.c: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #include "LoadLibrary.h" 14 | 15 | #ifdef _WIN32 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | void *swiftlibrarypluginprovider_LoadLibraryW(uint16_t *lpLibFileName) { 22 | return LoadLibraryW(lpLibFileName); 23 | } 24 | 25 | unsigned long swiftlibrarypluginprovider_GetLastError() { 26 | return GetLastError(); 27 | } 28 | 29 | #endif /* _WIN32 */ 30 | -------------------------------------------------------------------------------- /Sources/_SwiftLibraryPluginProviderCShims/include/LoadLibrary.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #ifndef SWIFT_LIBRARY_PLUGIN_PROVIDER_LOAD_LIBRARY_H 14 | #define SWIFT_LIBRARY_PLUGIN_PROVIDER_LOAD_LIBRARY_H 15 | 16 | #ifdef _WIN32 17 | 18 | #include 19 | 20 | void *swiftlibrarypluginprovider_LoadLibraryW(uint16_t *lpLibFileName); 21 | unsigned long swiftlibrarypluginprovider_GetLastError(); 22 | 23 | #endif /* _WIN32 */ 24 | 25 | #endif /* SWIFT_LIBRARY_PLUGIN_PROVIDER_LOAD_LIBRARY_H */ 26 | -------------------------------------------------------------------------------- /Sources/_SwiftLibraryPluginProviderCShims/include/module.modulemap: -------------------------------------------------------------------------------- 1 | module _SwiftLibraryPluginProviderCShims { 2 | header "LoadLibrary.h" 3 | export * 4 | } 5 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(target ${SWIFTSYNTAX_TARGET_NAMESPACE}_SwiftSyntaxCShims) 2 | add_library(${target} STATIC 3 | PlatformMutex.c 4 | ) 5 | target_include_directories(${target} PUBLIC "include") 6 | set_property(GLOBAL APPEND PROPERTY SWIFT_EXPORTS ${target}) 7 | install(TARGETS ${target} EXPORT SwiftSyntaxTargets) 8 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/PlatformMutex.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #ifndef SWIFTSYNTAX_PLATFORMMUTEX_H 14 | #define SWIFTSYNTAX_PLATFORMMUTEX_H 15 | 16 | #include "_bridging.h" 17 | 18 | typedef struct PlatformMutex { 19 | void *opaque; 20 | } PlatformMutex; 21 | 22 | SWIFT_NAME_S("PlatformMutex.create()") 23 | PlatformMutex swiftsyntax_platform_mutex_create(void); 24 | 25 | SWIFT_NAME_S("PlatformMutex.lock(self:)") 26 | void swiftsyntax_platform_mutex_lock(PlatformMutex m); 27 | 28 | SWIFT_NAME_S("PlatformMutex.unlock(self:)") 29 | void swiftsyntax_platform_mutex_unlock(PlatformMutex m); 30 | 31 | SWIFT_NAME_S("PlatformMutex.destroy(self:)") 32 | void swiftsyntax_platform_mutex_destroy(PlatformMutex m); 33 | 34 | #endif // SWIFTSYNTAX_PLATFORMMUTEX_H 35 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/SwiftSyntaxCShims.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #include "_includes.h" 14 | #include "Atomics.h" 15 | #include "PlatformMutex.h" 16 | #include "swiftsyntax_errno.h" 17 | #include "swiftsyntax_stdio.h" 18 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/_bridging.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #ifndef SWIFTSYNTAX_BRIDGING_H 14 | #define SWIFTSYNTAX_BRIDGING_H 15 | 16 | #if __has_attribute(swift_name) 17 | #define SWIFT_NAME_S(NAME) __attribute__((swift_name(NAME))) 18 | #else 19 | #define SWIFT_NAME_S(NAME) 20 | #endif 21 | 22 | #endif // SWIFTSYNTAX_BRIDGING_H 23 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/_includes.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | // 13 | // This file is for, instead of importing platform modules in Swift file, like: 14 | // 15 | // #if canImport(Darwin) 16 | // import Darwin 17 | // #elseif canImport(Glibc) 18 | // import Glibc 19 | // ... 20 | // 21 | // Just include them here using C facilities, so that Swift module can just: 22 | // 23 | // import _SwiftSyntaxCShims 24 | // 25 | //===----------------------------------------------------------------------===// 26 | 27 | #if defined(_WIN32) 28 | // NOTE: Do NOT include "WinSDK" headers here. 29 | // This is a part of compiler. If we use 'WinSDK' here, the compiler links with 30 | // swiftWinSDK.dll when (re)bulding it, and fails because it's used. 31 | #include 32 | 33 | #elif defined(__unix__) || defined(__APPLE__) 34 | #include 35 | #endif 36 | 37 | #include 38 | #include 39 | #include 40 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/module.modulemap: -------------------------------------------------------------------------------- 1 | module _SwiftSyntaxCShims { 2 | header "_includes.h" 3 | header "Atomics.h" 4 | header "PlatformMutex.h" 5 | header "swiftsyntax_errno.h" 6 | header "swiftsyntax_stdio.h" 7 | 8 | textual header "_bridging.h" 9 | 10 | export * 11 | } 12 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/swiftsyntax_errno.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #ifndef SWIFTSYNTAX_ERRNO_H 14 | #define SWIFTSYNTAX_ERRNO_H 15 | 16 | #include "_bridging.h" 17 | 18 | #include 19 | 20 | SWIFT_NAME_S("getter:swift_syntax_errno()") 21 | static inline int swiftsyntax_errno(void) { 22 | return errno; 23 | } 24 | 25 | #endif // SWIFTSYNTAX_ERRNO_H 26 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxCShims/include/swiftsyntax_stdio.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #ifndef SWIFTSYNTAX_STDIO_H 14 | #define SWIFTSYNTAX_STDIO_H 15 | 16 | #include "_bridging.h" 17 | 18 | #include 19 | 20 | SWIFT_NAME_S("getter:swift_syntax_stdout()") 21 | static inline FILE *swiftsyntax_stdout(void) { 22 | return stdout; 23 | } 24 | 25 | SWIFT_NAME_S("getter:swift_syntax_stdin()") 26 | static inline FILE *swiftsyntax_stdin(void) { 27 | return stdin; 28 | } 29 | 30 | SWIFT_NAME_S("getter:swift_syntax_stderr()") 31 | static inline FILE *swiftsyntax_stderr(void) { 32 | return stderr; 33 | } 34 | 35 | #endif // SWIFTSYNTAX_STDIO_H 36 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxGenericTestSupport/String+TrimmingTrailingWhitespace.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | extension String { 14 | public func trimmingTrailingWhitespace() -> String { 15 | return 16 | self 17 | .split(separator: "\n", omittingEmptySubsequences: false) 18 | .map { $0.droppingLast(while: \.isWhitespace) } 19 | .joined(separator: "\n") 20 | } 21 | } 22 | 23 | public extension StringProtocol { 24 | func droppingLast(while predicate: (Character) -> Bool) -> String { 25 | return String(self.reversed().drop(while: predicate).reversed()) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Sources/_SwiftSyntaxTestSupport/LongTestsDisabled.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if compiler(>=6) 14 | private import Foundation 15 | #else 16 | import Foundation 17 | #endif 18 | 19 | public var longTestsDisabled: Bool { 20 | if let value = ProcessInfo.processInfo.environment["SKIP_LONG_TESTS"] { 21 | return value == "1" || value == "YES" 22 | } 23 | return false 24 | } 25 | -------------------------------------------------------------------------------- /SwiftParserCLI/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.7 2 | 3 | import Foundation 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "SwiftParserCLI", 8 | platforms: [ 9 | .macOS(.v10_15) 10 | ], 11 | products: [ 12 | .executable(name: "swift-parser-cli", targets: ["swift-parser-cli"]) 13 | ], 14 | dependencies: [ 15 | .package(path: "..") 16 | ], 17 | targets: [ 18 | .target( 19 | name: "InstructionCounter" 20 | ), 21 | 22 | .executableTarget( 23 | name: "swift-parser-cli", 24 | dependencies: [ 25 | "InstructionCounter", 26 | .product(name: "SwiftBasicFormat", package: "swift-syntax"), 27 | .product(name: "SwiftDiagnostics", package: "swift-syntax"), 28 | .product(name: "SwiftOperators", package: "swift-syntax"), 29 | .product(name: "SwiftParser", package: "swift-syntax"), 30 | .product(name: "SwiftParserDiagnostics", package: "swift-syntax"), 31 | .product(name: "SwiftSyntax", package: "swift-syntax"), 32 | .product(name: "ArgumentParser", package: "swift-argument-parser"), 33 | ] 34 | ), 35 | ] 36 | ) 37 | 38 | if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { 39 | // Building standalone. 40 | package.dependencies += [ 41 | .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.2") 42 | ] 43 | } else { 44 | package.dependencies += [ 45 | .package(path: "../../swift-argument-parser") 46 | ] 47 | } 48 | -------------------------------------------------------------------------------- /SwiftParserCLI/README.md: -------------------------------------------------------------------------------- 1 | # SwiftParserCLI 2 | 3 | This directory contains the source files of the `swift-parser-cli` program. 4 | 5 | You can build `swift-parser-cli` by checking out `swift-syntax` and running 6 | ``` 7 | swift build --package-path SwiftParserCLI 8 | ``` 9 | or entering this directory and running 10 | ``` 11 | swift build 12 | ``` 13 | 14 | You can also open the `SwiftParserCLI` package and building the `swift-parser-cli` target in Xcode. 15 | -------------------------------------------------------------------------------- /SwiftParserCLI/Sources/InstructionCounter/include/InstructionsExecuted.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #include 14 | 15 | /// On macOS returns the number of instructions the process has executed since 16 | /// it was launched, on all other platforms returns 0. 17 | uint64_t getInstructionsExecuted(); 18 | -------------------------------------------------------------------------------- /SwiftParserCLI/Sources/InstructionCounter/src/InstructionsExecuted.c: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | #if __APPLE__ 14 | #include 15 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 16 | #define TARGET_IS_MACOS 1 17 | #endif 18 | #endif 19 | 20 | #include "InstructionsExecuted.h" 21 | 22 | #ifdef TARGET_IS_MACOS 23 | #include 24 | #include 25 | #include 26 | 27 | uint64_t getInstructionsExecuted() { 28 | struct rusage_info_v4 ru; 29 | if (proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)&ru) == 0) { 30 | return ru.ri_instructions; 31 | } 32 | return 0; 33 | } 34 | #else 35 | uint64_t getInstructionsExecuted() { 36 | return 0; 37 | } 38 | #endif 39 | -------------------------------------------------------------------------------- /SwiftParserCLI/Sources/swift-parser-cli/Commands/PrintTree.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import ArgumentParser 14 | import SwiftParser 15 | import SwiftSyntax 16 | 17 | struct PrintTree: ParsableCommand, ParseCommand { 18 | static var configuration = CommandConfiguration( 19 | commandName: "print-tree", 20 | abstract: "Print the syntax tree produced by parsing a source file" 21 | ) 22 | 23 | @OptionGroup 24 | var arguments: ParseArguments 25 | 26 | @Flag(name: .long, help: "Include trivia in the output") 27 | var includeTrivia: Bool = false 28 | 29 | func run() throws { 30 | try sourceFileContents.withUnsafeBufferPointer { sourceBuffer in 31 | let tree = Parser.parse(source: sourceBuffer) 32 | 33 | let resultTree: Syntax 34 | if foldSequences { 35 | resultTree = foldAllSequences(tree).0 36 | } else { 37 | resultTree = Syntax(tree) 38 | } 39 | 40 | print(resultTree.debugDescription(includeTrivia: includeTrivia)) 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /SwiftParserCLI/Sources/swift-parser-cli/SyntaxUtils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftDiagnostics 14 | import SwiftOperators 15 | import SwiftSyntax 16 | 17 | /// Fold all of the sequences in the given source file. 18 | func foldAllSequences(_ tree: some SyntaxProtocol) -> (Syntax, [Diagnostic]) { 19 | var diags: [Diagnostic] = [] 20 | 21 | let recordOperatorError: (OperatorError) -> Void = { error in 22 | diags.append(error.asDiagnostic) 23 | } 24 | var operatorTable = OperatorTable.standardOperators 25 | if let sourceFile = tree as? SourceFileSyntax { 26 | operatorTable.addSourceFile(sourceFile, errorHandler: recordOperatorError) 27 | } 28 | let resultTree = operatorTable.foldAll(tree, errorHandler: recordOperatorError) 29 | return (resultTree, diags) 30 | } 31 | -------------------------------------------------------------------------------- /SwiftParserCLI/Sources/swift-parser-cli/Utils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import Foundation 14 | 15 | func getContentsOfSourceFile(at path: String?) throws -> [UInt8] { 16 | let source: Data 17 | if let path { 18 | let sourceURL = URL(fileURLWithPath: path) 19 | source = try Data(contentsOf: sourceURL) 20 | } else { 21 | source = FileHandle.standardInput.readDataToEndOfFile() 22 | } 23 | return [UInt8](source) 24 | } 25 | 26 | /// Print the given message to stderr 27 | func printerr(_ message: String, terminator: String = "\n") { 28 | FileHandle.standardError.write((message + terminator).data(using: .utf8)!) 29 | } 30 | -------------------------------------------------------------------------------- /SwiftParserCLI/Sources/swift-parser-cli/swift-parser-cli.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import ArgumentParser 14 | import Foundation 15 | import InstructionCounter 16 | import SwiftDiagnostics 17 | import SwiftOperators 18 | import SwiftParser 19 | import SwiftParserDiagnostics 20 | import SwiftSyntax 21 | 22 | #if os(Windows) 23 | import WinSDK 24 | #endif 25 | 26 | @main 27 | class SwiftParserCli: ParsableCommand { 28 | required init() {} 29 | 30 | static var configuration = CommandConfiguration( 31 | abstract: "Utility to test SwiftSyntax syntax tree creation.", 32 | subcommands: [ 33 | BasicFormat.self, 34 | PerformanceTest.self, 35 | PrintDiags.self, 36 | PrintTree.self, 37 | Reduce.self, 38 | VerifyRoundTrip.self, 39 | ] 40 | ) 41 | } 42 | -------------------------------------------------------------------------------- /SwiftSyntaxDevUtils/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.7 2 | 3 | import Foundation 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "swift-syntax-dev-utils", 8 | platforms: [ 9 | .macOS(.v13) 10 | ], 11 | products: [ 12 | .executable(name: "swift-syntax-dev-utils", targets: ["swift-syntax-dev-utils"]) 13 | ], 14 | targets: [ 15 | .executableTarget( 16 | name: "swift-syntax-dev-utils", 17 | dependencies: [ 18 | .product(name: "ArgumentParser", package: "swift-argument-parser") 19 | ] 20 | ) 21 | ] 22 | ) 23 | 24 | if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { 25 | // Building standalone. 26 | package.dependencies += [ 27 | .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.2") 28 | ] 29 | } else { 30 | package.dependencies += [ 31 | .package(path: "../../swift-argument-parser") 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /SwiftSyntaxDevUtils/README.md: -------------------------------------------------------------------------------- 1 | # swift-syntax-dev-utils 2 | 3 | Scripts to help build swift-syntax in CI. In most cases, you should not need to run these scripts yourself. The [Contributing Guide](../CONTRIBUTING.md) contains information of how to build swift-syntax locally. 4 | -------------------------------------------------------------------------------- /SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/Logger.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import Foundation 14 | 15 | func logSection(_ text: String) { 16 | print("** \(text) **") 17 | } 18 | 19 | extension Process { 20 | var command: String { 21 | var message = "" 22 | 23 | for (key, value) in environment?.sorted(by: { $0.key < $1.key }) ?? [] { 24 | message += "\(key)='\(value)' " 25 | } 26 | 27 | if let executableURL = executableURL { 28 | message += executableURL.path 29 | } 30 | 31 | if let arguments = arguments { 32 | message += " \(arguments.joined(separator: " "))" 33 | } 34 | 35 | return message 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/ScriptExectutionError.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | struct ScriptExectutionError: Error { 14 | let message: String 15 | } 16 | 17 | extension ScriptExectutionError: CustomStringConvertible { 18 | var description: String { 19 | message 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/SourceCodeGeneratorArguments.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import ArgumentParser 14 | import Foundation 15 | 16 | struct SourceCodeGeneratorArguments: ParsableArguments { 17 | @Option( 18 | name: .customLong("toolchain"), 19 | help: "The path to the toolchain that shall be used to build SwiftSyntax.", 20 | transform: URL.init(fileURLWithPath:) 21 | ) 22 | var _toolchain: URL? = defaultToolchain() 23 | 24 | var toolchain: URL { 25 | get throws { 26 | guard let toolchain = self._toolchain else { 27 | throw ScriptExectutionError(message: "Toolchain could not be inferred. Specify toolchain using --toolchain") 28 | } 29 | return toolchain 30 | } 31 | } 32 | 33 | @Flag(help: "Enable verbose logging.") 34 | var verbose: Bool = false 35 | } 36 | -------------------------------------------------------------------------------- /Tests/PerformanceTest/ParsingPerformanceTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftParser 14 | import SwiftSyntax 15 | import XCTest 16 | import _SwiftSyntaxTestSupport 17 | 18 | class ParsingPerformanceTests: XCTestCase { 19 | 20 | var inputFile: URL { 21 | return URL(fileURLWithPath: #filePath) 22 | .deletingLastPathComponent() 23 | .appendingPathComponent("Inputs") 24 | .appendingPathComponent("MinimalCollections.swift.input") 25 | } 26 | 27 | func testNativeParsingPerformance() throws { 28 | try XCTSkipIf(longTestsDisabled) 29 | 30 | let source = try String(contentsOf: inputFile, encoding: .utf8) 31 | 32 | try measureInstructions { 33 | _ = Parser.parse(source: source) 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftIDEUtils 14 | import SwiftParser 15 | import SwiftSyntax 16 | import XCTest 17 | import _SwiftSyntaxTestSupport 18 | 19 | class SyntaxClassifierPerformanceTests: XCTestCase { 20 | 21 | var inputFile: URL { 22 | return URL(fileURLWithPath: #filePath) 23 | .deletingLastPathComponent() 24 | .appendingPathComponent("Inputs") 25 | .appendingPathComponent("MinimalCollections.swift.input") 26 | } 27 | 28 | func testClassifierPerformance() throws { 29 | try XCTSkipIf(longTestsDisabled) 30 | 31 | let source = try String(contentsOf: inputFile, encoding: .utf8) 32 | let parsed = Parser.parse(source: source) 33 | 34 | try measureInstructions { 35 | for _ in 0..<10 { 36 | for _ in parsed.classifications {} 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Tests/SwiftCompilerPluginTest/LRUCacheTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2024 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | @_spi(Testing) import SwiftCompilerPluginMessageHandling 14 | import XCTest 15 | 16 | final class LRUCacheTests: XCTestCase { 17 | func testBasic() { 18 | let cache = LRUCache(capacity: 2) 19 | cache["foo"] = 0 20 | cache["bar"] = 1 21 | XCTAssertEqual(cache["foo"], 0) 22 | cache["baz"] = 2 23 | XCTAssertEqual(cache["foo"], 0) 24 | XCTAssertEqual(cache["bar"], nil) 25 | XCTAssertEqual(cache["baz"], 2) 26 | XCTAssertEqual(cache.count, 2) 27 | 28 | cache["qux"] = nil 29 | cache["baz"] = nil 30 | cache["foo"] = 10 31 | XCTAssertEqual(cache["foo"], 10) 32 | XCTAssertEqual(cache["bar"], nil) 33 | XCTAssertEqual(cache["baz"], nil) 34 | XCTAssertEqual(cache["qux"], nil) 35 | XCTAssertEqual(cache.count, 1) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Tests/SwiftDiagnosticsTest/DiagnosticFormatterTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftDiagnostics 14 | import XCTest 15 | 16 | final class DiagnosticFormatterTests: XCTestCase { 17 | func testFormattedMessage() { 18 | let message = SimpleDiagnosticMessage( 19 | message: "something went wrong", 20 | diagnosticID: MessageID(domain: "swift-syntax", id: "testing"), 21 | severity: .error, 22 | category: DiagnosticCategory( 23 | name: "Testing", 24 | documentationURL: "http://example.com" 25 | ) 26 | ) 27 | 28 | let formattedText = DiagnosticsFormatter().formattedMessage(message) 29 | XCTAssertEqual(formattedText, "error: something went wrong [#Testing]") 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/AbsolutePositionTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftParser 14 | import SwiftSyntax 15 | import XCTest 16 | import _SwiftSyntaxTestSupport 17 | 18 | class AbsolutePositionTests: ParserTestCase { 19 | public func testTokenAt() { 20 | let source = 21 | """ 22 | func f(a: Int) { } 23 | """ 24 | 25 | let parsed = Parser.parse(source: source) 26 | for expectedToken in parsed.tokens(viewMode: .sourceAccurate) { 27 | let tokenStart = expectedToken.position.utf8Offset 28 | let tokenEnd = expectedToken.endPosition.utf8Offset 29 | for offset in tokenStart.. () 22 | """ 23 | ) 24 | } 25 | 26 | func testSendingArgMiddle() { 27 | assertParse( 28 | """ 29 | class Klass {} 30 | func transferMain(_ y: Klass, _ x: sending Klass, _ z: Klass) -> () 31 | """ 32 | ) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/Utils.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | @_spi(Testing) import SwiftParser 14 | 15 | func withParser(source: String, _ body: (inout Parser) throws -> T) rethrows -> T { 16 | var source = source 17 | return try source.withUTF8 { buffer in 18 | var parser = Parser(buffer) 19 | return try body(&parser) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/AlwaysEmitConformanceMetadataAttrTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/alwaysEmitConformanceMetadata_attr.swift 14 | 15 | import XCTest 16 | 17 | final class AlwaysEmitConformanceMetadataAttrTests: ParserTestCase { 18 | func testAlwaysEmitConformanceMetadataAttr() { 19 | assertParse( 20 | """ 21 | @_alwaysEmitConformanceMetadata 22 | protocol Test {} 23 | """ 24 | ) 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/BorrowExprTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/borrow_expr.swift 14 | 15 | @_spi(ExperimentalLanguageFeatures) import SwiftParser 16 | import SwiftSyntax 17 | import XCTest 18 | 19 | final class BorrowExprTests: ParserTestCase { 20 | func testBorrowExpr1() { 21 | assertParse( 22 | """ 23 | func useString(_ str: String) {} 24 | var global: String = "123" 25 | func testGlobal() { 26 | useString(_borrow global) 27 | } 28 | """, 29 | experimentalFeatures: [.oldOwnershipOperatorSpellings] 30 | ) 31 | } 32 | 33 | func testBorrowExpr2() { 34 | assertParse( 35 | """ 36 | func useString(_ str: String) {} 37 | func testVar() { 38 | var t = String() 39 | t = String() 40 | useString(_borrow t) 41 | } 42 | """, 43 | experimentalFeatures: [.oldOwnershipOperatorSpellings] 44 | ) 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/BraceRecoveryEofTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/brace_recovery_eof.swift 14 | 15 | import XCTest 16 | 17 | final class BraceRecoveryEofTests: ParserTestCase { 18 | func testBraceRecoveryEof1() { 19 | assertParse( 20 | """ 21 | // Make sure source ranges satisfy the verifier. 22 | for foo in [1, 2] ℹ️{ 23 | _ = foo1️⃣ 24 | """, 25 | diagnostics: [ 26 | DiagnosticSpec( 27 | message: "expected '}' to end 'for' statement", 28 | notes: [ 29 | NoteSpec(message: "to match this opening '{'") 30 | ], 31 | fixIts: ["insert '}'"] 32 | ) 33 | ], 34 | fixedSource: """ 35 | // Make sure source ranges satisfy the verifier. 36 | for foo in [1, 2] { 37 | _ = foo 38 | } 39 | """ 40 | ) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/DebuggerTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/debugger.swift 14 | 15 | import XCTest 16 | 17 | final class DebuggerTests: ParserTestCase { 18 | func testDebugger1() { 19 | assertParse( 20 | """ 21 | import Nonexistent_Module 22 | """ 23 | ) 24 | } 25 | 26 | func testDebugger2() { 27 | assertParse( 28 | """ 29 | var ($x0, $x1) = (4, 3) 30 | var z = $x0 + $x1 31 | """ 32 | ) 33 | } 34 | 35 | func testDebugger3() { 36 | assertParse( 37 | """ 38 | z // no error. 39 | """ 40 | ) 41 | } 42 | 43 | func testDebugger4() { 44 | assertParse( 45 | """ 46 | var x: Double = z 47 | """ 48 | ) 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/DelayedExtensionTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/delayed_extension.swift 14 | 15 | import XCTest 16 | 17 | final class DelayedExtensionTests: ParserTestCase { 18 | func testDelayedExtension1() { 19 | assertParse( 20 | """ 21 | extension X { } 22 | _ = 1 23 | f() 24 | """ 25 | ) 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/GuardTopLevelTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/guard-top-level.swift 14 | 15 | import XCTest 16 | 17 | final class GuardTopLevelTests: ParserTestCase { 18 | func testGuardTopLevel1() { 19 | assertParse( 20 | """ 21 | let a: Int? = 1 22 | guard let b = a else { 23 | } 24 | """ 25 | ) 26 | } 27 | 28 | func testGuardTopLevel2() { 29 | assertParse( 30 | """ 31 | func foo() {} // to interrupt the TopLevelCodeDecl 32 | """ 33 | ) 34 | } 35 | 36 | func testGuardTopLevel3() { 37 | assertParse( 38 | """ 39 | let c = b 40 | """ 41 | ) 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/HashbangMainTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/hashbang_main.swift 14 | 15 | import XCTest 16 | 17 | final class HashbangMainTests: ParserTestCase { 18 | func testHashbangMain1() { 19 | assertParse( 20 | """ 21 | #!/usr/bin/swift 22 | let x = 42 23 | x + x 24 | // Check that we skip the hashbang at the beginning of the file. 25 | """ 26 | ) 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/PatternWithoutVariablesScriptTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/pattern_without_variables_script.swift 14 | 15 | import XCTest 16 | 17 | final class PatternWithoutVariablesScriptTests: ParserTestCase { 18 | func testPatternWithoutVariablesScript1() { 19 | assertParse( 20 | """ 21 | _ = 1 22 | """ 23 | ) 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/PlaygroundLvaluesTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/playground_lvalues.swift 14 | 15 | import XCTest 16 | 17 | final class PlaygroundLvaluesTests: ParserTestCase { 18 | func testPlaygroundLvalues1() { 19 | assertParse( 20 | """ 21 | var a = 1, b = 2 22 | let z = 3 23 | """ 24 | ) 25 | } 26 | 27 | func testPlaygroundLvalues2() { 28 | assertParse( 29 | """ 30 | a 31 | (a, b) 32 | (a, z) 33 | """ 34 | ) 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/PrefixSlashTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/StringProcessing/Parse/prefix-slash.swift 14 | 15 | import XCTest 16 | 17 | final class PrefixSlashTests: ParserTestCase { 18 | func testPrefixSlash2() { 19 | assertParse( 20 | """ 21 | prefix operator / 22 | prefix func / (_ x: T) -> T { x } 23 | """ 24 | ) 25 | } 26 | 27 | func testPrefixSlash4() { 28 | assertParse( 29 | """ 30 | _ = /E.e 31 | (/E.e).foo(/0) 32 | """ 33 | ) 34 | } 35 | 36 | func testPrefixSlash6() { 37 | assertParse( 38 | """ 39 | foo(/E.e, /E.e) 40 | foo((/E.e), /E.e) 41 | foo((/)(E.e), /E.e) 42 | """ 43 | ) 44 | } 45 | 46 | func testPrefixSlash8() { 47 | assertParse( 48 | """ 49 | _ = bar(/E.e) / 2 50 | """ 51 | ) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/RegexParseEndOfBufferTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/StringProcessing/Parse/regex_parse_end_of_buffer.swift 14 | 15 | import XCTest 16 | 17 | final class RegexParseEndOfBufferTests: ParserTestCase { 18 | func testRegexParseEndOfBuffer1() { 19 | assertParse( 20 | "var unterminated = #/(xy1️⃣", 21 | diagnostics: [ 22 | DiagnosticSpec(message: "expected '/#' to end regex literal", fixIts: ["insert '/#'"]) 23 | ], 24 | fixedSource: """ 25 | var unterminated = #/(xy/# 26 | """ 27 | ) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Tests/SwiftParserTest/translated/SwitchIncompleteTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | // This test file has been translated from swift/test/Parse/switch_incomplete.swift 14 | 15 | import XCTest 16 | 17 | final class SwitchIncompleteTests: ParserTestCase { 18 | func testSwitchIncomplete1() { 19 | // Incomplete switch was parsing to an AST that 20 | // triggered an assertion failure. 21 | assertParse( 22 | """ 23 | switch 1 ℹ️{ 24 | case 1:1️⃣ 25 | """, 26 | diagnostics: [ 27 | DiagnosticSpec( 28 | message: "expected '}' to end 'switch' statement", 29 | notes: [ 30 | NoteSpec(message: "to match this opening '{'") 31 | ], 32 | fixIts: ["insert '}'"] 33 | ) 34 | ], 35 | fixedSource: """ 36 | switch 1 { 37 | case 1: 38 | } 39 | """ 40 | ) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/AccessorDeclTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class AccessorDeclTests: XCTestCase { 18 | func testCreateAccessorWithHeaderAndBody() throws { 19 | let accessor = try AccessorDeclSyntax("get") { 20 | ExprSyntax("1") 21 | } 22 | XCTAssertEqual(accessor.body?.statements.count, 1) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/Assertions.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | import _SwiftSyntaxTestSupport 17 | 18 | func assertBuildResult( 19 | _ buildable: T, 20 | _ expectedResult: String, 21 | trimTrailingWhitespace: Bool = true, 22 | format: Bool = true, 23 | file: StaticString = #filePath, 24 | line: UInt = #line 25 | ) { 26 | var buildableDescription = 27 | format 28 | ? buildable.formatted().description 29 | : buildable.description 30 | var expectedResult = expectedResult 31 | if trimTrailingWhitespace { 32 | buildableDescription = buildableDescription.trimmingTrailingWhitespace() 33 | expectedResult = expectedResult.trimmingTrailingWhitespace() 34 | } 35 | assertStringsEqualWithDiff( 36 | buildableDescription, 37 | expectedResult, 38 | file: file, 39 | line: line 40 | ) 41 | } 42 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/AttributeListSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class AttributeListSyntaxTests: XCTestCase { 18 | func testAttributeListSyntaxSpacing() { 19 | let buildable = AttributeListSyntax { 20 | AttributeSyntax("@inlinable") 21 | AttributeSyntax("@discardableResult") 22 | } 23 | assertBuildResult( 24 | buildable, 25 | """ 26 | @inlinable @discardableResult 27 | """ 28 | ) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/BooleanLiteralTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class BooleanLiteralTests: XCTestCase { 18 | func testBooleanLiteral() { 19 | let testCases: [UInt: (BooleanLiteralExprSyntax, String)] = [ 20 | #line: (BooleanLiteralExprSyntax(literal: .keyword(.true)), "true"), 21 | #line: (BooleanLiteralExprSyntax(literal: .keyword(.false)), "false"), 22 | #line: (BooleanLiteralExprSyntax(true), "true"), 23 | #line: (BooleanLiteralExprSyntax(false), "false"), 24 | #line: (true, "true"), 25 | #line: (false, "false"), 26 | ] 27 | 28 | for (line, testCase) in testCases { 29 | let (builder, expected) = testCase 30 | assertBuildResult(builder, expected, line: line) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/BreakStmtSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class BreakStmtSyntaxTests: XCTestCase { 18 | func testBreakStmtSyntax() { 19 | let testCases: [UInt: (StmtSyntax, String)] = [ 20 | #line: (StmtSyntax(BreakStmtSyntax()), "break"), 21 | #line: (StmtSyntax("break"), "break"), 22 | ] 23 | 24 | for (line, testCase) in testCases { 25 | let (builder, expected) = testCase 26 | assertBuildResult(builder, expected, trimTrailingWhitespace: false, line: line) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/CustomAttributeTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class CustomAttributeTests: XCTestCase { 18 | func testCustomAttributeConvenienceInitializer() { 19 | let testCases: [UInt: (AttributeSyntax, String)] = [ 20 | #line: (AttributeSyntax(attributeName: TypeSyntax("Test")), "@Test"), 21 | #line: (AttributeSyntax("WithParens") {}, "@WithParens()"), 22 | #line: ( 23 | AttributeSyntax("WithArgs") { 24 | LabeledExprSyntax(expression: ExprSyntax("value1")) 25 | LabeledExprSyntax(label: "labelled", expression: ExprSyntax("value2")) 26 | }, "@WithArgs(value1, labelled: value2)" 27 | ), 28 | ] 29 | 30 | for (line, testCase) in testCases { 31 | let (builder, expected) = testCase 32 | assertBuildResult(builder, expected, line: line) 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/ExprListTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class ExprListTests: XCTestCase { 18 | func testExprList() { 19 | let testCases: [UInt: (ExprListSyntax, String)] = [ 20 | #line: ( 21 | ExprListSyntax( 22 | [ 23 | ExprSyntax(IntegerLiteralExprSyntax(1)), 24 | ExprSyntax(BinaryOperatorExprSyntax(text: "+")), 25 | ExprSyntax(FloatLiteralExprSyntax(2.34)), 26 | ] 27 | ), "1 + 2.34" 28 | ), 29 | #line: ( 30 | [ 31 | ExprSyntax(IntegerLiteralExprSyntax(1)), 32 | ExprSyntax(BinaryOperatorExprSyntax(text: "+")), 33 | ExprSyntax(FloatLiteralExprSyntax(2.34)), 34 | ], "1 + 2.34" 35 | ), 36 | ] 37 | 38 | for (line, testCase) in testCases { 39 | let (builder, expected) = testCase 40 | assertBuildResult(builder, expected, line: line) 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/FunctionParameterSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class FunctionParameterSyntaxTests: XCTestCase { 18 | func testFunctionParameterSyntaxSpacing() { 19 | let builder = FunctionParameterSyntax(firstName: "on", secondName: "eventLoop", type: TypeSyntax("EventLoop")) 20 | assertBuildResult( 21 | builder, 22 | """ 23 | on eventLoop: EventLoop 24 | """ 25 | ) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/FunctionSignatureSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class FunctionSignatureSyntaxTests: XCTestCase { 18 | func testFunctionEffectSpecifiersSyntax() throws { 19 | let functionEffects = FunctionEffectSpecifiersSyntax( 20 | asyncSpecifier: .keyword(.async), 21 | throwsClause: ThrowsClauseSyntax(throwsSpecifier: .keyword(.rethrows)) 22 | ) 23 | let buildable = FunctionSignatureSyntax( 24 | parameterClause: .init(parameters: []), 25 | effectSpecifiers: functionEffects, 26 | returnClause: .init(type: TypeSyntax("String")) 27 | ) 28 | 29 | assertBuildResult( 30 | buildable, 31 | """ 32 | () async rethrows -> String 33 | """ 34 | ) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/FunctionTypeSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class FunctionTypeSyntaxTests: XCTestCase { 18 | func testFunctionEffectSpecifiersSyntax() throws { 19 | let typeEffects = TypeEffectSpecifiersSyntax( 20 | asyncSpecifier: .keyword(.async), 21 | throwsClause: ThrowsClauseSyntax(throwsSpecifier: .keyword(.throws)) 22 | ) 23 | let buildable = FunctionTypeSyntax( 24 | parameters: [], 25 | effectSpecifiers: typeEffects, 26 | returnClause: .init(type: TypeSyntax("String")) 27 | ) 28 | 29 | assertBuildResult( 30 | buildable, 31 | """ 32 | () async throws -> String 33 | """ 34 | ) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/ImportDeclSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class ImportDeclSyntaxTests: XCTestCase { 18 | func testImportDeclSyntax() { 19 | let identifier = TokenSyntax.identifier("SwiftSyntax") 20 | 21 | let importDecl = ImportDeclSyntax( 22 | path: ImportPathComponentListSyntax([ImportPathComponentSyntax(name: identifier)]) 23 | ) 24 | 25 | assertBuildResult(importDecl, "import SwiftSyntax") 26 | } 27 | 28 | func testImportWithAttribute() { 29 | let buildable = ImportDeclSyntax( 30 | attributes: [.attribute("@_exported")], 31 | path: [ImportPathComponentSyntax(name: "SwiftSyntax")] 32 | ) 33 | 34 | assertBuildResult( 35 | buildable, 36 | """ 37 | @_exported import SwiftSyntax 38 | """ 39 | ) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/LabeledExprSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class LabeledExprSyntaxTests: XCTestCase { 18 | func testLabeledExprSyntax() { 19 | let syntax = LabeledExprSyntax(label: "arg", expression: NilLiteralExprSyntax()) 20 | assertBuildResult(syntax, "arg: nil", format: false) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/ProtocolDeclTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class ProtocolDeclTests: XCTestCase { 18 | func testProtocolDecl() throws { 19 | let buildable = try ProtocolDeclSyntax("public protocol DeclListBuildable") { 20 | DeclSyntax("func buildDeclList(format: Format, leadingTrivia: Trivia?) -> [DeclSyntax]") 21 | } 22 | 23 | assertBuildResult( 24 | buildable, 25 | """ 26 | public protocol DeclListBuildable { 27 | func buildDeclList(format: Format, leadingTrivia: Trivia?) -> [DeclSyntax] 28 | } 29 | """ 30 | ) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/SourceFileTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class SourceFileTests: XCTestCase { 18 | func testSourceFile() { 19 | let source = SourceFileSyntax { 20 | DeclSyntax("import Foundation") 21 | DeclSyntax("import UIKit") 22 | ClassDeclSyntax( 23 | classKeyword: .keyword(.class), 24 | name: "SomeViewController", 25 | memberBlockBuilder: { 26 | DeclSyntax("let tableView: UITableView") 27 | } 28 | ) 29 | } 30 | 31 | assertBuildResult( 32 | source, 33 | """ 34 | import Foundation 35 | import UIKit 36 | class SomeViewController { 37 | let tableView: UITableView 38 | } 39 | """, 40 | trimTrailingWhitespace: false 41 | ) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxBuilderTest/SwitchCaseLabelSyntaxTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import SwiftSyntaxBuilder 15 | import XCTest 16 | 17 | final class SwitchCaseLabelSyntaxTests: XCTestCase { 18 | func testSwitchCaseLabelSyntax() { 19 | let testCases: [UInt: (SwitchCaseSyntax, String)] = [ 20 | #line: ( 21 | SwitchCaseSyntax("default:") { 22 | StmtSyntax("return nil") 23 | 24 | }, 25 | """ 26 | default: 27 | return nil 28 | """ 29 | ), 30 | #line: ( 31 | SwitchCaseSyntax("case .foo:") { 32 | StmtSyntax("return nil") 33 | 34 | }, 35 | """ 36 | case .foo: 37 | return nil 38 | """ 39 | ), 40 | ] 41 | 42 | for (line, testCase) in testCases { 43 | let (builder, expected) = testCase 44 | assertBuildResult(builder, expected, trimTrailingWhitespace: false, line: line) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxTest/DummyParseToken.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | @_spi(RawSyntax) import SwiftSyntax 14 | 15 | /// Dummy trivia parsing function. 16 | func dummyParseToken(source: SyntaxText, position: TriviaPosition) -> [RawTriviaPiece] { 17 | // Emit a single `unexpectedText` trivia of the whole trivia text. 18 | return [.unexpectedText(source)] 19 | } 20 | -------------------------------------------------------------------------------- /Tests/SwiftSyntaxTest/SyntaxTreeModifierTests.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift.org open source project 4 | // 5 | // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | // 11 | //===----------------------------------------------------------------------===// 12 | 13 | import SwiftSyntax 14 | import XCTest 15 | 16 | fileprivate func cannedVarDecl() -> VariableDeclSyntax { 17 | let identifierPattern = IdentifierPatternSyntax( 18 | identifier: .identifier("a") 19 | ) 20 | let pattern = PatternBindingSyntax( 21 | pattern: identifierPattern, 22 | typeAnnotation: TypeAnnotationSyntax( 23 | colon: .colonToken(trailingTrivia: .space), 24 | type: IdentifierTypeSyntax(name: .identifier("Int")) 25 | ) 26 | ) 27 | return VariableDeclSyntax( 28 | bindingSpecifier: .keyword(.let, trailingTrivia: .space), 29 | bindings: PatternBindingListSyntax([pattern]) 30 | ) 31 | } 32 | 33 | class SyntaxTreeModifierTests: XCTestCase { 34 | 35 | public func testAccessorAsModifier() { 36 | var VD = cannedVarDecl() 37 | XCTAssertEqual("\(VD)", "let a: Int") 38 | VD.bindingSpecifier = .keyword(.var, trailingTrivia: .space) 39 | XCTAssertEqual("\(VD)", "var a: Int") 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /WORKSPACE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-syntax/8d2c20fec97eaea0b843b000f25e83723e265d60/WORKSPACE -------------------------------------------------------------------------------- /cmake/modules/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | if(PROJECT_IS_TOP_LEVEL OR SWIFT_SYNTAX_INSTALL_TARGETS) 2 | export(EXPORT SwiftSyntaxTargets 3 | FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftSyntaxConfig.cmake 4 | NAMESPACE SwiftSyntax::) 5 | endif() 6 | -------------------------------------------------------------------------------- /swift-syntax-dev-utils: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | swift run --package-path "$(dirname $0)/SwiftSyntaxDevUtils" swift-syntax-dev-utils "$@" 4 | -------------------------------------------------------------------------------- /utils/bazel/BUILD.bazel: -------------------------------------------------------------------------------- 1 | ##===----------------------------------------------------------------------===## 2 | ## 3 | ## This source file is part of the Swift.org open source project 4 | ## 5 | ## Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors 6 | ## Licensed under Apache License v2.0 with Runtime Library Exception 7 | ## 8 | ## See https://swift.org/LICENSE.txt for license information 9 | ## See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors 10 | ## 11 | ##===----------------------------------------------------------------------===## 12 | --------------------------------------------------------------------------------