-
Notifications
You must be signed in to change notification settings - Fork 434
/
Copy pathGenerateSwiftSyntax.swift
282 lines (256 loc) · 10.8 KB
/
GenerateSwiftSyntax.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import Dispatch
import Foundation
import SwiftSyntax
import SwiftSyntaxBuilder
import SyntaxSupport
import Utils
private let generatedDirName = "generated"
private let swiftBasicFormatGeneratedDir = ["SwiftBasicFormat", generatedDirName]
private let swiftideUtilsGeneratedDir = ["SwiftIDEUtils", generatedDirName]
private let swiftParserGeneratedDir = ["SwiftParser", generatedDirName]
private let swiftParserDiagnosticsGeneratedDir = ["SwiftParserDiagnostics", generatedDirName]
private let swiftSyntaxGeneratedDir = ["SwiftSyntax", generatedDirName]
private let swiftSyntaxBuilderGeneratedDir = ["SwiftSyntaxBuilder", generatedDirName]
private let swiftSyntaxMacroExpansionGeneratedDir = ["SwiftSyntaxMacroExpansion", generatedDirName]
private let swiftSyntaxMacrosGenericTestSupportGeneratedDir = ["SwiftSyntaxMacrosGenericTestSupport", generatedDirName]
private let swiftSyntaxMacrosTestSupportGeneratedDir = ["SwiftSyntaxMacrosTestSupport", generatedDirName]
private let BASE_KIND_FILES: [SyntaxNodeKind: String] = [
.decl: "SyntaxDeclNodes.swift",
.expr: "SyntaxExprNodes.swift",
.pattern: "SyntaxPatternNodes.swift",
.stmt: "SyntaxStmtNodes.swift",
.syntax: "SyntaxNodes.swift",
.type: "SyntaxTypeNodes.swift",
]
struct GeneratedFileSpec {
let pathComponents: [String]
private let contentsGenerator: () -> String
var contents: String {
return self.contentsGenerator()
}
init(_ pathComponents: [String], _ contents: @escaping @autoclosure () -> String) {
self.pathComponents = pathComponents
self.contentsGenerator = contents
}
init(
_ pathComponents: [String],
_ contents: @escaping @autoclosure () -> SourceFileSyntax,
format: CodeGenerationFormat = CodeGenerationFormat()
) {
self.init(pathComponents, "\(contents().formatted(using: format))\n")
}
}
struct TemplateSpec {
let sourceFileGenerator: () -> SourceFileSyntax
var sourceFile: SourceFileSyntax {
return self.sourceFileGenerator()
}
let module: String
let filename: String
init(sourceFile: @escaping @autoclosure () -> SourceFileSyntax, module: String, filename: String) {
self.sourceFileGenerator = sourceFile
self.module = module
self.filename = filename
}
}
@main
struct GenerateSwiftSyntax: AsyncParsableCommand {
@Argument(
help: "The path to the source directory (i.e. 'swift-syntax/Sources') where the source files are to be generated"
)
var destination: String = {
let sourcesURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Sources")
return sourcesURL.path
}()
@Flag(help: "Enable verbose output")
var verbose: Bool = false
func run() async throws {
let destination = URL(fileURLWithPath: self.destination).standardizedFileURL
var fileSpecs: [GeneratedFileSpec] = [
// SwiftParser
GeneratedFileSpec(swiftParserGeneratedDir + ["ExperimentalFeatures.swift"], experimentalFeaturesFile),
GeneratedFileSpec(swiftParserGeneratedDir + ["IsLexerClassified.swift"], isLexerClassifiedFile),
GeneratedFileSpec(swiftParserGeneratedDir + ["LayoutNodes+Parsable.swift"], layoutNodesParsableFile),
GeneratedFileSpec(swiftParserGeneratedDir + ["Parser+TokenSpecSet.swift"], parserTokenSpecSetFile),
GeneratedFileSpec(swiftParserGeneratedDir + ["TokenSpecStaticMembers.swift"], tokenSpecStaticMembersFile),
// SwiftParserDiagnostics
GeneratedFileSpec(
swiftParserDiagnosticsGeneratedDir + ["ChildNameForDiagnostics.swift"],
childNameForDiagnosticFile
),
GeneratedFileSpec(
swiftParserDiagnosticsGeneratedDir + ["SyntaxKindNameForDiagnostics.swift"],
syntaxKindNameForDiagnosticFile
),
GeneratedFileSpec(
swiftParserDiagnosticsGeneratedDir + ["TokenNameForDiagnostics.swift"],
tokenNameForDiagnosticFile
),
// SwiftSyntax
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["ChildNameForKeyPath.swift"], childNameForKeyPathFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["Keyword.swift"], keywordFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["raw", "RawSyntaxValidation.swift"], rawSyntaxValidationFile),
GeneratedFileSpec(
swiftSyntaxGeneratedDir + ["RenamedChildrenCompatibility.swift"],
renamedChildrenCompatibilityFile
),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["RenamedNodesCompatibility.swift"], renamedSyntaxNodesFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxAnyVisitor.swift"], syntaxAnyVisitorFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxBaseNodes.swift"], syntaxBaseNodesFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxCollections.swift"], syntaxCollectionsFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxEnum.swift"], syntaxEnumFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxKind.swift"], syntaxKindFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxRewriter.swift"], syntaxRewriterFile),
GeneratedFileSpec(
swiftSyntaxGeneratedDir + ["AsyncSyntaxRewriter.swift"],
makeSyntaxRewriterFile(
className: "AsyncSyntaxRewriter",
functionEffectSpecifiers: "async",
functionCallOperators: "await",
spiName: "MacroExpansion"
)
),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["SyntaxTraits.swift"], syntaxTraitsFile),
GeneratedFileSpec(
swiftSyntaxGeneratedDir + ["SyntaxVisitor.swift"],
syntaxVisitorFile,
format: CodeGenerationFormat(maxElementsOnSameLine: 4)
),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["TokenKind.swift"], tokenKindFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["Tokens.swift"], tokensFile),
GeneratedFileSpec(swiftSyntaxGeneratedDir + ["TriviaPieces.swift"], triviaPiecesFile),
GeneratedFileSpec(["SwiftSyntax", "Documentation.docc", "generated", "SwiftSyntax.md"], swiftSyntaxDoccIndex),
// SwiftSyntaxBuilder
GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["BuildableNodes.swift"], buildableNodesFile),
GeneratedFileSpec(swiftSyntaxBuilderGeneratedDir + ["ResultBuilders.swift"], resultBuildersFile),
GeneratedFileSpec(
swiftSyntaxBuilderGeneratedDir + ["SyntaxExpressibleByStringInterpolationConformances.swift"],
syntaxExpressibleByStringInterpolationConformancesFile
),
GeneratedFileSpec(
swiftSyntaxBuilderGeneratedDir + ["RenamedChildrenBuilderCompatibility.swift"],
renamedChildrenBuilderCompatibilityFile
),
// SwiftSyntaxMacroExpansion
GeneratedFileSpec(
swiftSyntaxMacroExpansionGeneratedDir + ["MacroExpansion.swift"],
macroExpansionFile
),
GeneratedFileSpec(
swiftSyntaxMacroExpansionGeneratedDir + ["MacroSystem.swift"],
macroSystemFile
),
// SwiftSyntaxMacrosGenericTestSupport
GeneratedFileSpec(
swiftSyntaxMacrosGenericTestSupportGeneratedDir + ["Assertions.swift"],
genericMacroAssertionsFile
),
// SwiftSyntaxMacrosTestSupport
GeneratedFileSpec(
swiftSyntaxMacrosTestSupportGeneratedDir + ["Assertions.swift"],
macroAssertionsFile
),
]
// This split of letters produces files for the syntax nodes that have about equal size, which improves compile time
fileSpecs += ["AB", "C", "D", "EF", "GHI", "JKLMN", "OP", "QRS", "TUVWXYZ"].flatMap {
(letters: String) -> [GeneratedFileSpec] in
[
GeneratedFileSpec(
swiftSyntaxGeneratedDir + ["syntaxNodes", "SyntaxNodes\(letters).swift"],
syntaxNode(nodesStartingWith: Array(letters))
),
GeneratedFileSpec(
swiftSyntaxGeneratedDir + ["raw", "RawSyntaxNodes\(letters).swift"],
rawSyntaxNodesFile(nodesStartingWith: Array(letters))
),
]
}
let modules = Set(fileSpecs.compactMap { $0.pathComponents.first })
var previouslyGeneratedFiles = Set(
modules.flatMap { (module) -> [URL] in
let generatedDir =
destination
.appendingPathComponent(module)
.appendingPathComponent("generated")
return FileManager.default
.enumerator(at: generatedDir, includingPropertiesForKeys: nil)!
.compactMap { $0 as? URL }
.filter { !$0.hasDirectoryPath }
.map { $0.resolvingSymlinksInPath() }
}
)
await withTaskGroup(of: (url: URL, error: Error?).self) { group in
for fileSpec in fileSpecs {
group.addTask {
do {
var destination = destination
for component in fileSpec.pathComponents {
destination = destination.appendingPathComponent(component)
}
do {
try generateFile(
contents: fileSpec.contents,
destination: destination,
verbose: verbose
)
} catch {
// If we throw from here, we'll lose the URL,
// and we'll end up removing a file that is still
// included in the files we intend to generate,
// even if we failed to do so on this run.
return (destination, error)
}
return (destination, nil)
}
}
}
for await result in group {
_ = previouslyGeneratedFiles.remove(result.url)
if let error = result.error {
print("Error when generating file at \(result.url):", error)
}
}
}
for file in previouslyGeneratedFiles {
// All files in `previouslyGeneratedFiles` that haven't been removed from
// the set above no longer exist. Remove them.
try FileManager.default.removeItem(at: file)
}
}
}
fileprivate func generateFile(
contents: @autoclosure () -> String,
destination: URL,
verbose: Bool
) throws {
try FileManager.default.createDirectory(
atPath: destination.deletingLastPathComponent().path,
withIntermediateDirectories: true,
attributes: nil
)
if verbose {
print("Generating \(destination.path)...")
}
let start = Date()
try contents().write(to: destination, atomically: true, encoding: .utf8)
if verbose {
print("Generated \(destination.path) in \((Date().timeIntervalSince(start) * 1000).rounded() / 1000)s")
}
}