Skip to content

Commit fe30a08

Browse files
committed
Update CodeGeneration to use new convenience initializers
1 parent d49ea0a commit fe30a08

File tree

7 files changed

+53
-130
lines changed

7 files changed

+53
-130
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/ahoppen/swift-syntax.git", revision: "81f9396d4bcc969df4ace1153e54bcaa264ac329"),
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
@@ -68,7 +68,7 @@ public extension Child {
6868
}))
6969
}
7070
let disjunction = ExprList(assertChoices.flatMap { [$0, Expr(BinaryOperatorExpr(text: "||"))] }.dropLast())
71-
return FunctionCallExpr(calledExpression: Expr("assert")) {
71+
return FunctionCallExpr(calledExpression: "assert") {
7272
TupleExprElement(expression: SequenceExpr(elements: disjunction))
7373
}
7474
}

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(calledExpression: 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 {
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(calledExpression: 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(calledExpression: "self.init") {
233212
for arg in delegatedInitArgs {
234213
arg
235214
}

CodeGeneration/Sources/generate-swiftsyntaxbuilder/ResultBuildersFile.swift

Lines changed: 19 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -133,38 +133,26 @@ let resultBuildersFile = SourceFile {
133133
"""
134134
)
135135

136-
FunctionDecl(
137-
leadingTrivia: [
138-
.newlines(1),
139-
.docLineComment("/// If declared, this will be called on the partial result from the outermost"),
140-
.newlines(1),
141-
.docLineComment("/// block statement to produce the final returned result."),
142-
.newlines(1)],
143-
modifiers: [DeclModifier(name: .public), DeclModifier(name: .static)],
144-
identifier: .identifier("buildFinalResult"),
145-
signature: FunctionSignature(
146-
input: ParameterClause {
147-
FunctionParameter(
148-
firstName: .wildcard,
149-
secondName: .identifier("component"),
150-
colon: .colon,
151-
type: Type("Component"))
152-
},
153-
output: ReturnClause(returnType: Type("FinalResult")))) {
154-
if elementType.isToken {
155-
ReturnStmt("return .init(component)")
156-
} else if elementType.hasWithTrailingCommaTrait {
157-
VariableDecl("let lastIndex = component.count - 1")
136+
FunctionDecl("""
137+
138+
/// If declared, this will be called on the partial result from the outermost
139+
/// block statement to produce the final returned result.
140+
public static func buildFinalResult(_ component: Component) -> FinalResult
141+
""") {
142+
if elementType.isToken {
143+
ReturnStmt("return .init(component)")
144+
} else if elementType.hasWithTrailingCommaTrait {
145+
VariableDecl("let lastIndex = component.count - 1")
158146

159-
ReturnStmt("""
160-
return .init(component.enumerated().map { index, source in
161-
return index < lastIndex ? source.ensuringTrailingComma() : source
162-
})
163-
""")
164-
} else {
165-
ReturnStmt("return .init(component)")
166-
}
167-
}
147+
ReturnStmt("""
148+
return .init(component.enumerated().map { index, source in
149+
return index < lastIndex ? source.ensuringTrailingComma() : source
150+
})
151+
""")
152+
} else {
153+
ReturnStmt("return .init(component)")
154+
}
155+
}
168156
}
169157

170158
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)