Skip to content

Commit 033cbdf

Browse files
committed
Update CodeGeneration to use new convenience initializers
1 parent 5e9dcce commit 033cbdf

File tree

7 files changed

+54
-131
lines changed

7 files changed

+54
-131
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: "fa7ff05591294db031e3061e704994aa3b89d1bc"),
15+
.package(url: "https://github.com/apple/swift-syntax.git", revision: "5e9dcce1dc5c81e48b658ced23f0848be4671a0c"),
1616
.package(url: "https://github.com/apple/swift-argument-parser.git", .upToNextMinor(from: "1.1.4")),
1717
],
1818
targets: [

CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public extension Child {
8080
}))
8181
}
8282
let disjunction = ExprList(assertChoices.flatMap { [$0, Expr(BinaryOperatorExpr(text: "||"))] }.dropLast())
83-
return FunctionCallExpr(calledExpression: Expr("assert")) {
83+
return FunctionCallExpr(callee: "assert") {
8484
TupleExprElement(expression: SequenceExpr(elements: disjunction))
8585
}
8686
}

CodeGeneration/Sources/generate-swiftbasicformat/BasicFormatFile.swift

Lines changed: 13 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -62,23 +62,10 @@ private func makeLayoutNodeRewriteFunc(node: Node) -> FunctionDecl {
6262
} else {
6363
rewriteResultType = node.type.baseType?.syntaxBaseName ?? node.type.syntaxBaseName
6464
}
65-
return FunctionDecl(
66-
leadingTrivia: .newline,
67-
modifiers: [DeclModifier(name: .open), DeclModifier(name: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
68-
identifier: .identifier("visit"),
69-
signature: FunctionSignature(
70-
input: ParameterClause(parameterList: [
71-
FunctionParameter(
72-
firstName: Token.wildcard,
73-
secondName: .identifier("node"),
74-
colon: .colon,
75-
type: Type(node.type.syntaxBaseName)
65+
return FunctionDecl("""
7666
77-
)
78-
]),
79-
output: ReturnClause(returnType: Type(rewriteResultType))
80-
)
81-
) {
67+
open override func visit(_ node: \(node.type.syntaxBaseName)) -> \(rewriteResultType)
68+
""") {
8269
for child in node.children {
8370
if child.isIndented {
8471
SequenceExpr("indentationLevel += 1")
@@ -98,7 +85,7 @@ private func makeLayoutNodeRewriteFunc(node: Node) -> FunctionDecl {
9885
SequenceExpr("indentationLevel -= 1")
9986
}
10087
}
101-
let reconstructed = FunctionCallExpr(calledExpression: Expr("\(node.type.syntaxBaseName)")) {
88+
let reconstructed = FunctionCallExpr(callee: node.type.syntaxBaseName) {
10289
for child in node.children {
10390
TupleExprElement(
10491
label: child.isUnexpectedNodes ? nil : child.swiftName,
@@ -116,23 +103,10 @@ private func makeLayoutNodeRewriteFunc(node: Node) -> FunctionDecl {
116103

117104
private func makeSyntaxCollectionRewriteFunc(node: Node) -> FunctionDecl {
118105
let rewriteResultType = node.type.syntaxBaseName
119-
return FunctionDecl(
120-
leadingTrivia: .newline,
121-
modifiers: [DeclModifier(name: .open), DeclModifier(name: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
122-
identifier: .identifier("visit"),
123-
signature: FunctionSignature(
124-
input: ParameterClause(parameterList: [
125-
FunctionParameter(
126-
firstName: Token.wildcard,
127-
secondName: .identifier("node"),
128-
colon: .colon,
129-
type: Type(node.type.syntaxBaseName)
106+
return FunctionDecl("""
130107
131-
)
132-
]),
133-
output: ReturnClause(returnType: Type(rewriteResultType))
134-
)
135-
) {
108+
open override func visit(_ node: \(node.type.syntaxBaseName)) -> \(rewriteResultType)
109+
""") {
136110
let formattedChildrenVarLet = node.elementsSeparatedByNewline ? "var" : "let"
137111
VariableDecl(
138112
"""
@@ -159,28 +133,15 @@ private func makeSyntaxCollectionRewriteFunc(node: Node) -> FunctionDecl {
159133
}
160134

161135
private func createTokenFormatFunction() -> FunctionDecl {
162-
return FunctionDecl(
163-
leadingTrivia: .newline,
164-
modifiers: [DeclModifier(name: .open), DeclModifier(name: TokenSyntax.contextualKeyword("override", trailingTrivia: .space))],
165-
identifier: .identifier("visit"),
166-
signature: FunctionSignature(
167-
input: ParameterClause(parameterList: [
168-
FunctionParameter(
169-
firstName: Token.wildcard,
170-
secondName: .identifier("node"),
171-
colon: .colon,
172-
type: Type("TokenSyntax")
136+
return FunctionDecl("""
173137
174-
)
175-
]),
176-
output: ReturnClause(returnType: Type("TokenSyntax"))
177-
)
178-
) {
138+
open override func visit(_ node: TokenSyntax) -> TokenSyntax
139+
""") {
179140
VariableDecl("var leadingTrivia = node.leadingTrivia")
180141
VariableDecl("var trailingTrivia = node.trailingTrivia")
181142
SwitchStmt(expression: MemberAccessExpr(base: "node", name: "tokenKind")) {
182143
for token in SYNTAX_TOKENS where token.name != "ContextualKeyword" {
183-
SwitchCase(label: SwitchCaseLabel(caseItems: [CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: token.swiftKind)))])) {
144+
SwitchCase("case .\(token.swiftKind):") {
184145
if token.requiresLeadingSpace {
185146
IfStmt(
186147
"""
@@ -204,10 +165,10 @@ private func createTokenFormatFunction() -> FunctionDecl {
204165
}
205166
}
206167
}
207-
SwitchCase(label: SwitchCaseLabel(caseItems: [CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: "eof")))])) {
168+
SwitchCase("case .eof:") {
208169
BreakStmt("break")
209170
}
210-
SwitchCase(label: SwitchCaseLabel(caseItems: [CaseItem(pattern: ExpressionPattern(expression: MemberAccessExpr(name: "contextualKeyword")))])) {
171+
SwitchCase("case .contextualKeyword:") {
211172
SwitchStmt(
212173
"""
213174
switch node.text {

CodeGeneration/Sources/generate-swiftsyntaxbuilder/BuildableCollectionNodesFile.swift

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,9 @@ let buildableCollectionNodesFile = SourceFile {
2626
for node in SYNTAX_NODES where node.isSyntaxCollection {
2727
let elementType = node.collectionElementType
2828

29+
let docComment = node.documentation.isEmpty ? "" : "/// \(node.documentation)\n"
2930
// Generate collection node struct
30-
ExtensionDecl(
31-
leadingTrivia: node.documentation.isEmpty
32-
? []
33-
: .docLineComment("/// \(node.documentation)") + .newline,
34-
extendedType: Type(node.type.shorthandName),
35-
inheritanceClause: TypeInheritanceClause { InheritedType(typeName: Type("ExpressibleByArrayLiteral")) }
36-
) {
31+
ExtensionDecl("\(docComment)extension \(node.type.shorthandName): ExpressibleByArrayLiteral") {
3732
// Generate initializers
3833
if elementType.isBaseType && node.collectionElementChoices?.isEmpty ?? true {
3934
InitializerDecl(

CodeGeneration/Sources/generate-swiftsyntaxbuilder/BuildableNodesFile.swift

Lines changed: 16 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,9 @@ let buildableNodesFile = SourceFile {
2626
let type = node.type
2727
let hasTrailingComma = node.traits.contains("WithTrailingComma")
2828

29-
// Generate node struct
29+
let docComment: SwiftSyntax.Trivia = node.documentation.isEmpty ? [] : .docLineComment("/// \(node.documentation)") + .newline
3030
ExtensionDecl(
31-
leadingTrivia: node.documentation.isEmpty
32-
? []
33-
: .docLineComment("/// \(node.documentation)") + .newline,
31+
leadingTrivia: docComment,
3432
extendedType: Type(type.shorthandName),
3533
inheritanceClause: hasTrailingComma ? TypeInheritanceClause { InheritedType(typeName: Type("HasTrailingComma")) } : nil
3634
) {
@@ -89,12 +87,7 @@ private func createDefaultInitializer(node: Node) -> InitializerDecl {
8987
signature: FunctionSignature(
9088
input: ParameterClause {
9189
for trivia in ["leadingTrivia", "trailingTrivia"] {
92-
FunctionParameter(
93-
firstName: .identifier(trivia),
94-
colon: .colon,
95-
type: Type("Trivia"),
96-
defaultArgument: InitializerClause(value: ArrayExpr())
97-
)
90+
FunctionParameter("\(trivia): Trivia = []", for: .functionParameters)
9891
}
9992
for child in node.children {
10093
FunctionParameter(
@@ -112,7 +105,7 @@ private func createDefaultInitializer(node: Node) -> InitializerDecl {
112105
assertStmt
113106
}
114107
}
115-
let nodeConstructorCall = FunctionCallExpr(calledExpression: Expr(type.syntaxBaseName)) {
108+
let nodeConstructorCall = FunctionCallExpr(callee: type.syntaxBaseName) {
116109
for child in node.children {
117110
TupleExprElement(
118111
label: child.isUnexpectedNodes ? nil : child.swiftName,
@@ -156,21 +149,16 @@ private func createConvenienceInitializer(node: Node) -> InitializerDecl? {
156149
} else {
157150
produceExpr = Expr(FunctionCallExpr("\(child.swiftName)Builder()"))
158151
}
152+
let defaultArgument = ClosureExpr {
153+
if child.type.isOptional {
154+
NilLiteralExpr()
155+
} else {
156+
FunctionCallExpr("\(builderInitializableType.syntax)([])")
157+
}
158+
}
159159
builderParameters.append(FunctionParameter(
160-
attributes: [CustomAttribute(attributeName: Type(builderInitializableType.resultBuilderBaseName), argumentList: nil)],
161-
firstName: .identifier("\(child.swiftName)Builder").withLeadingTrivia(.space),
162-
colon: .colon,
163-
type: FunctionType(
164-
arguments: [],
165-
returnType: builderInitializableType.syntax
166-
),
167-
defaultArgument: InitializerClause(value: ClosureExpr {
168-
if child.type.isOptional {
169-
NilLiteralExpr()
170-
} else {
171-
FunctionCallExpr("\(builderInitializableType.syntax)([])")
172-
}
173-
})
160+
"@\(builderInitializableType.resultBuilderBaseName) \(child.swiftName)Builder: () -> \(builderInitializableType.syntax) = \(defaultArgument)",
161+
for: .functionParameters
174162
))
175163
} else if let token = child.type.token, token.text == nil {
176164
// Allow initializing identifiers and other tokens without default text with a String
@@ -182,11 +170,7 @@ private func createConvenienceInitializer(node: Node) -> InitializerDecl? {
182170
} else {
183171
produceExpr = Expr(FunctionCallExpr("\(tokenExpr)(\(child.swiftName))"))
184172
}
185-
normalParameters.append(FunctionParameter(
186-
firstName: .identifier(child.swiftName),
187-
colon: .colon,
188-
type: paramType
189-
))
173+
normalParameters.append(FunctionParameter("\(child.swiftName): \(paramType)", for: .functionParameters))
190174
} else {
191175
produceExpr = convertFromSyntaxProtocolToSyntaxType(child: child)
192176
normalParameters.append(FunctionParameter(
@@ -217,19 +201,14 @@ private func createConvenienceInitializer(node: Node) -> InitializerDecl? {
217201
modifiers: [DeclModifier(name: .public)],
218202
signature: FunctionSignature(
219203
input: ParameterClause {
220-
FunctionParameter(
221-
firstName: .identifier("leadingTrivia"),
222-
colon: .colon,
223-
type: Type("Trivia"),
224-
defaultArgument: InitializerClause(value: ArrayExpr())
225-
)
204+
FunctionParameter("leadingTrivia: Trivia = []", for: .functionParameters)
226205
for param in normalParameters + builderParameters {
227206
param
228207
}
229208
}
230209
)
231210
) {
232-
FunctionCallExpr(calledExpression: MemberAccessExpr("self.init")) {
211+
FunctionCallExpr(callee: "self.init") {
233212
for arg in delegatedInitArgs {
234213
arg
235214
}

CodeGeneration/Sources/generate-swiftsyntaxbuilder/ResultBuildersFile.swift

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ let resultBuildersFile = SourceFile {
2727
let expressionType: Type = (node.collectionElementChoices?.isEmpty ?? true) ? elementType.parameterType : Type(MemberTypeIdentifier("\(type.buildable).Element"))
2828

2929
StructDecl(
30-
attributes: [CustomAttribute(trailingTrivia: .newline, attributeName: Type("resultBuilder"))],
30+
attributes: [.customAttribute(CustomAttribute(trailingTrivia: .newline, attributeName: Type("resultBuilder")))],
3131
modifiers: [DeclModifier(name: .public)],
3232
identifier: "\(type.syntaxKind)Builder") {
3333

@@ -146,38 +146,26 @@ let resultBuildersFile = SourceFile {
146146
"""
147147
)
148148

149-
FunctionDecl(
150-
leadingTrivia: [
151-
.newlines(1),
152-
.docLineComment("/// If declared, this will be called on the partial result from the outermost"),
153-
.newlines(1),
154-
.docLineComment("/// block statement to produce the final returned result."),
155-
.newlines(1)],
156-
modifiers: [DeclModifier(name: .public), DeclModifier(name: .static)],
157-
identifier: .identifier("buildFinalResult"),
158-
signature: FunctionSignature(
159-
input: ParameterClause {
160-
FunctionParameter(
161-
firstName: .wildcard,
162-
secondName: .identifier("component"),
163-
colon: .colon,
164-
type: Type("Component"))
165-
},
166-
output: ReturnClause(returnType: Type("FinalResult")))) {
167-
if elementType.isToken {
168-
ReturnStmt("return .init(component)")
169-
} else if elementType.hasWithTrailingCommaTrait {
170-
VariableDecl("let lastIndex = component.count - 1")
149+
FunctionDecl("""
150+
151+
/// If declared, this will be called on the partial result from the outermost
152+
/// block statement to produce the final returned result.
153+
public static func buildFinalResult(_ component: Component) -> FinalResult
154+
""") {
155+
if elementType.isToken {
156+
ReturnStmt("return .init(component)")
157+
} else if elementType.hasWithTrailingCommaTrait {
158+
VariableDecl("let lastIndex = component.count - 1")
171159

172-
ReturnStmt("""
173-
return .init(component.enumerated().map { index, source in
174-
return index < lastIndex ? source.ensuringTrailingComma() : source
175-
})
176-
""")
177-
} else {
178-
ReturnStmt("return .init(component)")
179-
}
180-
}
160+
ReturnStmt("""
161+
return .init(component.enumerated().map { index, source in
162+
return index < lastIndex ? source.ensuringTrailingComma() : source
163+
})
164+
""")
165+
} else {
166+
ReturnStmt("return .init(component)")
167+
}
168+
}
181169
}
182170

183171
ExtensionDecl(

CodeGeneration/Sources/generate-swiftsyntaxbuilder/TokenFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ let tokenFile = SourceFile {
2222
path: [AccessPathComponent(name: "SwiftSyntax")]
2323
)
2424

25-
ExtensionDecl(modifiers: [DeclModifier(name: .public)], extendedType: Type("TokenSyntax")) {
25+
ExtensionDecl("public extension TokenSyntax") {
2626
for token in SYNTAX_TOKENS {
2727
if token.isKeyword {
2828
VariableDecl("""

0 commit comments

Comments
 (0)