Skip to content

Commit e621e8a

Browse files
authored
Merge pull request #1008 from ahoppen/ahoppen/update-codegen-to-simplified-swiftsyntaxbuilder
Update CodeGeneration to latest SwiftSyntaxBuilder
2 parents fa7ff05 + b951846 commit e621e8a

14 files changed

+610
-609
lines changed

CodeGeneration/Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ let package = Package(
1212
.executable(name: "generate-swiftsyntaxbuilder", targets: ["generate-swiftsyntaxbuilder"]),
1313
],
1414
dependencies: [
15-
.package(url: "https://github.com/apple/swift-syntax.git", revision: "0663a530c4e51066343c3c2fbd95f8e626b8d631"),
15+
.package(url: "https://github.com/apple/swift-syntax.git", revision: "fa7ff05591294db031e3061e704994aa3b89d1bc"),
1616
.package(url: "https://github.com/apple/swift-argument-parser.git", .upToNextMinor(from: "1.1.4")),
1717
],
1818
targets: [

CodeGeneration/Sources/Utils/CodeGenerationFormat.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ import SwiftSyntax
1717
public class CodeGenerationFormat: BasicFormat {
1818
public override var indentation: TriviaPiece { .spaces(indentationLevel * 2) }
1919

20-
public override func visit(_ node: MemberDeclListItemSyntax) -> Syntax {
20+
public override func visit(_ node: MemberDeclListItemSyntax) -> MemberDeclListItemSyntax {
2121
let formatted = super.visit(node)
2222
return formatted.withLeadingTrivia(indentedNewline + (formatted.leadingTrivia ?? []))
2323
}
2424

25-
public override func visit(_ node: CodeBlockItemSyntax) -> Syntax {
25+
public override func visit(_ node: CodeBlockItemSyntax) -> CodeBlockItemSyntax {
2626
if node.parent?.parent?.is(SourceFileSyntax.self) == true, !node.item.is(ImportDeclSyntax.self) {
2727
let formatted = super.visit(node)
2828
return formatted.withLeadingTrivia(indentedNewline + indentedNewline + (formatted.leadingTrivia ?? []))

CodeGeneration/Sources/Utils/GenerateTemplates.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
//===----------------------------------------------------------------------===//
1212

1313
import Foundation
14+
import SwiftSyntax
1415
import SwiftSyntaxBuilder
1516
import SwiftBasicFormat
1617

@@ -26,7 +27,7 @@ public func generateTemplates(templates: [(SourceFile, String)], destination: UR
2627
if verbose {
2728
print("Generating \(fileURL.path)...")
2829
}
29-
let syntax = sourceFile.build(format: CodeGenerationFormat())
30+
let syntax = sourceFile.formatted(using: CodeGenerationFormat())
3031
try "\(syntax)\n".write(to: fileURL, atomically: true, encoding: .utf8)
3132
}
3233
}

CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public extension Child {
3535
/// If this node is a token that can't contain arbitrary text, generate a Swift
3636
/// `assert` statement that verifies the variable with name var_name and of type
3737
/// `TokenSyntax` contains one of the supported text options. Otherwise return `nil`.
38-
func generateAssertStmtTextChoices(varName: String) -> ExpressibleAsExprBuildable? {
38+
func generateAssertStmtTextChoices(varName: String) -> FunctionCallExpr? {
3939
guard type.isToken else {
4040
return nil
4141
}
@@ -52,24 +52,24 @@ public extension Child {
5252
return nil
5353
}
5454

55-
var assertChoices: [ExpressibleAsExprBuildable] = []
55+
var assertChoices: [Expr] = []
5656
if type.isOptional {
57-
assertChoices.append(SequenceExpr {
58-
varName
59-
BinaryOperatorExpr("==")
57+
assertChoices.append(Expr(SequenceExpr {
58+
IdentifierExpr(identifier: .identifier(varName))
59+
BinaryOperatorExpr(text: "==")
6060
NilLiteralExpr()
61-
})
61+
}))
6262
}
6363
for textChoice in choices {
64-
assertChoices.append(SequenceExpr {
65-
MemberAccessExpr(base: type.forceUnwrappedIfNeeded(expr: varName), name: "text")
66-
BinaryOperatorExpr("==")
67-
StringLiteralExpr(raw: textChoice)
68-
})
64+
assertChoices.append(Expr(SequenceExpr {
65+
MemberAccessExpr(base: type.forceUnwrappedIfNeeded(expr: Expr(varName)), name: "text")
66+
BinaryOperatorExpr(text: "==")
67+
StringLiteralExpr(content: textChoice)
68+
}))
6969
}
70-
let disjunction = ExprList(assertChoices.flatMap { [$0, BinaryOperatorExpr("||")] }.dropLast())
71-
return FunctionCallExpr(calledExpression: "assert") {
72-
SequenceExpr(elements: disjunction)
70+
let disjunction = ExprList(assertChoices.flatMap { [$0, Expr(BinaryOperatorExpr(text: "||"))] }.dropLast())
71+
return FunctionCallExpr(calledExpression: Expr("assert")) {
72+
TupleExprElement(expression: SequenceExpr(elements: disjunction))
7373
}
7474
}
7575
}

CodeGeneration/Sources/Utils/SyntaxBuildableType.swift

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,14 @@ public struct SyntaxBuildableType: Hashable {
5353
/// with fixed test), return an expression of the form ` = defaultValue`
5454
/// that can be used as the default value for a function parameter.
5555
/// Otherwise, return the empty string.
56-
public var defaultInitialization: ExpressibleAsExprBuildable? {
56+
public var defaultInitialization: Expr? {
5757
if isOptional {
58-
return NilLiteralExpr()
58+
return Expr(NilLiteralExpr())
5959
} else if isToken {
6060
if let token = token, token.text != nil {
61-
return MemberAccessExpr(base: "Token", name: lowercaseFirstWord(name: token.name).backticked)
61+
return Expr(MemberAccessExpr(base: "Token", name: lowercaseFirstWord(name: token.name).backticked))
6262
} else if tokenKind == "EOFToken" {
63-
return MemberAccessExpr(base: "Token", name: "eof")
63+
return Expr(MemberAccessExpr(base: "Token", name: "eof"))
6464
}
6565
}
6666
return nil
@@ -86,8 +86,8 @@ public struct SyntaxBuildableType: Hashable {
8686
/// - For base kinds: `<BaseKind>Buildable`, e.g. `ExprBuildable` (these are implemented as protocols)
8787
/// - For token: `TokenSyntax` (tokens don't have a dedicated type in SwiftSyntaxBuilder)
8888
/// If the type is optional, the type is wrapped in an `OptionalType`.
89-
public var buildable: TypeBuildable {
90-
optionalWrapped(type: shorthandName).createTypeBuildable()
89+
public var buildable: Type {
90+
optionalWrapped(type: Type(shorthandName))
9191
}
9292

9393
/// Whether parameters of this type should be initializable by a result builder.
@@ -125,8 +125,8 @@ public struct SyntaxBuildableType: Hashable {
125125
/// The corresponding `*Syntax` type defined in the `SwiftSyntax` module,
126126
/// which will eventually get built from `SwiftSyntaxBuilder`. If the type
127127
/// is optional, this terminates with a `?`.
128-
public var syntax: TypeBuildable {
129-
optionalWrapped(type: syntaxBaseName)
128+
public var syntax: TypeSyntax {
129+
return optionalWrapped(type: TypeSyntax(syntaxBaseName))
130130
}
131131

132132
/// The type that is used for paramters in SwiftSyntaxBuilder that take this
@@ -139,8 +139,8 @@ public struct SyntaxBuildableType: Hashable {
139139
}
140140
}
141141

142-
public var parameterType: TypeBuildable {
143-
return optionalWrapped(type: parameterBaseType)
142+
public var parameterType: TypeSyntax {
143+
return optionalWrapped(type: TypeSyntax(parameterBaseType))
144144
}
145145

146146
/// Assuming that this is a collection type, the non-optional type of the result builder
@@ -165,29 +165,29 @@ public struct SyntaxBuildableType: Hashable {
165165
}
166166

167167
/// Wraps a type in an optional depending on whether `isOptional` is true.
168-
public func optionalWrapped(type: ExpressibleAsTypeBuildable) -> TypeBuildable {
168+
public func optionalWrapped(type: TypeSyntaxProtocol) -> TypeSyntax {
169169
if isOptional {
170-
return OptionalType(wrappedType: type)
170+
return TypeSyntax(OptionalType(wrappedType: type))
171171
} else {
172-
return type.createTypeBuildable()
172+
return TypeSyntax(type)
173173
}
174174
}
175175

176176
/// Wraps a type in an optional chaining depending on whether `isOptional` is true.
177-
public func optionalChained(expr: ExpressibleAsExprBuildable) -> ExpressibleAsExprBuildable {
177+
public func optionalChained(expr: ExprSyntaxProtocol) -> Expr {
178178
if isOptional {
179-
return OptionalChainingExpr(expression: expr)
179+
return Expr(OptionalChainingExpr(expression: expr))
180180
} else {
181-
return expr
181+
return Expr(expr)
182182
}
183183
}
184184

185185
/// Wraps a type in a force unwrap expression depending on whether `isOptional` is true.
186-
public func forceUnwrappedIfNeeded(expr: ExpressibleAsExprBuildable) -> ExpressibleAsExprBuildable {
186+
public func forceUnwrappedIfNeeded(expr: ExprSyntaxProtocol) -> ExprSyntax {
187187
if isOptional {
188-
return ForcedValueExpr(expression: expr)
188+
return ExprSyntax(ForcedValueExpr(expression: expr))
189189
} else {
190-
return expr
190+
return ExprSyntax(expr)
191191
}
192192
}
193193
}

CodeGeneration/Sources/generate-swiftbasicformat/BasicFormatFile.swift

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ import Utils
1919
let basicFormatFile = SourceFile {
2020
ImportDecl(
2121
leadingTrivia: .docLineComment(copyrightHeader),
22-
path: "SwiftSyntax"
22+
path: [AccessPathComponent(name: "SwiftSyntax")]
2323
)
2424

25-
ClassDecl(modifiers: [Token.open], identifier: "BasicFormat", inheritanceClause: TypeInheritanceClause { InheritedType(typeName: "SyntaxRewriter") }) {
25+
ClassDecl(modifiers: [DeclModifier(name: .open)], identifier: "BasicFormat", inheritanceClause: TypeInheritanceClause { InheritedType(typeName: Type("SyntaxRewriter")) }) {
2626
VariableDecl("public var indentationLevel: Int = 0")
2727
VariableDecl("open var indentation: TriviaPiece { .spaces(indentationLevel * 4) }")
2828
VariableDecl("public var indentedNewline: Trivia { Trivia(pieces: [.newlines(1), indentation]) }")
@@ -40,15 +40,15 @@ let basicFormatFile = SourceFile {
4040
}
4141
}
4242

43-
private func createChildVisitCall(childType: SyntaxBuildableType, rewrittenExpr: ExprBuildable) -> ExprBuildable {
43+
private func createChildVisitCall(childType: SyntaxBuildableType, rewrittenExpr: ExprSyntaxProtocol) -> FunctionCallExpr {
4444
let visitCall: FunctionCallExpr
4545
if childType.isOptional {
4646
visitCall = FunctionCallExpr("\(rewrittenExpr).map(self.visit)")
4747
} else {
4848
visitCall = FunctionCallExpr("self.visit(\(rewrittenExpr))")
4949
}
5050
if childType.baseType?.baseName != "Syntax", childType.baseType?.isSyntaxCollection != true, childType.baseType != nil {
51-
let optionalChained = childType.optionalChained(expr: visitCall).createExprBuildable()
51+
let optionalChained = childType.optionalChained(expr: visitCall)
5252
return FunctionCallExpr("\(optionalChained).cast(\(childType.syntaxBaseName).self)")
5353
} else {
5454
return visitCall
@@ -64,19 +64,19 @@ private func makeLayoutNodeRewriteFunc(node: Node) -> FunctionDecl {
6464
}
6565
return FunctionDecl(
6666
leadingTrivia: .newline,
67-
modifiers: [Token.open, Token(tokenSyntax: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
67+
modifiers: [DeclModifier(name: .open), DeclModifier(name: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
6868
identifier: .identifier("visit"),
6969
signature: FunctionSignature(
7070
input: ParameterClause(parameterList: [
7171
FunctionParameter(
7272
firstName: Token.wildcard,
7373
secondName: .identifier("node"),
7474
colon: .colon,
75-
type: node.type.syntaxBaseName
75+
type: Type(node.type.syntaxBaseName)
7676

7777
)
7878
]),
79-
output: rewriteResultType
79+
output: ReturnClause(returnType: Type(rewriteResultType))
8080
)
8181
) {
8282
for child in node.children {
@@ -98,11 +98,11 @@ private func makeLayoutNodeRewriteFunc(node: Node) -> FunctionDecl {
9898
SequenceExpr("indentationLevel -= 1")
9999
}
100100
}
101-
let reconstructed = FunctionCallExpr(calledExpression: "\(node.type.syntaxBaseName)") {
101+
let reconstructed = FunctionCallExpr(calledExpression: Expr("\(node.type.syntaxBaseName)")) {
102102
for child in node.children {
103103
TupleExprElement(
104104
label: child.isUnexpectedNodes ? nil : child.swiftName,
105-
expression: child.swiftName
105+
expression: Expr(child.swiftName)
106106
)
107107
}
108108
}
@@ -118,19 +118,19 @@ private func makeSyntaxCollectionRewriteFunc(node: Node) -> FunctionDecl {
118118
let rewriteResultType = node.type.syntaxBaseName
119119
return FunctionDecl(
120120
leadingTrivia: .newline,
121-
modifiers: [Token.open, Token(tokenSyntax: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
121+
modifiers: [DeclModifier(name: .open), DeclModifier(name: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
122122
identifier: .identifier("visit"),
123123
signature: FunctionSignature(
124124
input: ParameterClause(parameterList: [
125125
FunctionParameter(
126126
firstName: Token.wildcard,
127127
secondName: .identifier("node"),
128128
colon: .colon,
129-
type: node.type.syntaxBaseName
129+
type: Type(node.type.syntaxBaseName)
130130

131131
)
132132
]),
133-
output: rewriteResultType
133+
output: ReturnClause(returnType: Type(rewriteResultType))
134134
)
135135
) {
136136
let formattedChildrenVarLet = node.elementsSeparatedByNewline ? "var" : "let"
@@ -161,26 +161,26 @@ private func makeSyntaxCollectionRewriteFunc(node: Node) -> FunctionDecl {
161161
private func createTokenFormatFunction() -> FunctionDecl {
162162
return FunctionDecl(
163163
leadingTrivia: .newline,
164-
modifiers: [Token.open, Token(tokenSyntax: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
164+
modifiers: [DeclModifier(name: .open), DeclModifier(name: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
165165
identifier: .identifier("visit"),
166166
signature: FunctionSignature(
167167
input: ParameterClause(parameterList: [
168168
FunctionParameter(
169169
firstName: Token.wildcard,
170170
secondName: .identifier("node"),
171171
colon: .colon,
172-
type: "TokenSyntax"
172+
type: Type("TokenSyntax")
173173

174174
)
175175
]),
176-
output: "TokenSyntax"
176+
output: ReturnClause(returnType: Type("TokenSyntax"))
177177
)
178178
) {
179179
VariableDecl("var leadingTrivia = node.leadingTrivia")
180180
VariableDecl("var trailingTrivia = node.trailingTrivia")
181181
SwitchStmt(expression: MemberAccessExpr(base: "node", name: "tokenKind")) {
182182
for token in SYNTAX_TOKENS where token.name != "ContextualKeyword" {
183-
SwitchCase(label: SwitchCaseLabel(caseItems: CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: token.swiftKind))))) {
183+
SwitchCase(label: SwitchCaseLabel(caseItems: [CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: token.swiftKind)))])) {
184184
if token.requiresLeadingSpace {
185185
IfStmt(
186186
"""
@@ -204,10 +204,10 @@ private func createTokenFormatFunction() -> FunctionDecl {
204204
}
205205
}
206206
}
207-
SwitchCase(label: SwitchCaseLabel(caseItems: CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: "eof"))))) {
207+
SwitchCase(label: SwitchCaseLabel(caseItems: [CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: "eof")))])) {
208208
BreakStmt("break")
209209
}
210-
SwitchCase(label: SwitchCaseLabel(caseItems: CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: "contextualKeyword"))))) {
210+
SwitchCase(label: SwitchCaseLabel(caseItems: [CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: "contextualKeyword")))])) {
211211
SwitchStmt(
212212
"""
213213
switch node.text {

CodeGeneration/Sources/generate-swiftsyntaxbuilder/BuildableCollectionNodesFile.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import SwiftBasicFormat
2020
let buildableCollectionNodesFile = SourceFile {
2121
ImportDecl(
2222
leadingTrivia: .docLineComment(copyrightHeader),
23-
path: "SwiftSyntax"
23+
path: [AccessPathComponent(name: "SwiftSyntax")]
2424
)
2525

2626
for node in SYNTAX_NODES where node.isSyntaxCollection {
@@ -31,8 +31,8 @@ let buildableCollectionNodesFile = SourceFile {
3131
leadingTrivia: node.documentation.isEmpty
3232
? []
3333
: .docLineComment("/// \(node.documentation)") + .newline,
34-
extendedType: node.type.shorthandName,
35-
inheritanceClause: TypeInheritanceClause { InheritedType(typeName: "ExpressibleByArrayLiteral") }
34+
extendedType: Type(node.type.shorthandName),
35+
inheritanceClause: TypeInheritanceClause { InheritedType(typeName: Type("ExpressibleByArrayLiteral")) }
3636
) {
3737
// Generate initializers
3838
if elementType.isBaseType {

0 commit comments

Comments
 (0)