-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathNode.swift
433 lines (383 loc) · 13.2 KB
/
Node.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//===----------------------------------------------------------------------===//
//
// 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 Foundation
import SwiftSyntax
/// The definition of a syntax node that, when generated, conforms to
/// `SyntaxProtocol`.
///
/// There are two fundamentally different kinds of nodes:
/// - Layout nodes contain a fixed number of children of possibly different,
/// but fixed types.
/// - Collection nodes contains an arbitrary number of children but all those
/// children are of the same type.
public class Node: NodeChoiceConvertible {
fileprivate enum Data {
case layout(children: [Child], traits: [String])
case collection(choices: [SyntaxNodeKind])
}
/// Contains the layout or collection specific data of this syntax node.
///
/// To access this, use the `layoutNode` or `collectionNode` properties, which
/// offer the members.
fileprivate let data: Data
/// The kind of the node. There must be exactly one `Node` for every case in
/// `SyntaxNodeKind`.
public let kind: SyntaxNodeKind
/// The kind of node’s supertype. This kind must have `isBase == true`
public let base: SyntaxNodeKind
public let experimentalFeature: ExperimentalFeature?
/// When the node name is printed for diagnostics, this name is used.
/// If `nil`, `nameForDiagnostics` will print the parent node’s name.
public let nameForDiagnostics: String?
/// A doc comment describing the node.
///
/// The comment does not end with a newline.
public let documentation: SwiftSyntax.Trivia
/// If the syntax node can be constructed by parsing a string, the parser
/// function that should be invoked to create this node.
public let parserFunction: TokenSyntax?
public let disableSameTypeForUniqueChoice: Bool
public var syntaxNodeKind: SyntaxNodeKind {
self.kind
}
/// A name for this node as an identifier.
public var identifier: TokenSyntax {
return kind.identifier
}
/// If this is a layout node, return a view of the node that provides access
/// to the layout-node specific properties.
public var layoutNode: LayoutNode? {
switch data {
case .layout:
if kind.isBase {
return nil
} else {
return LayoutNode(node: self)
}
default:
return nil
}
}
/// If this is a collection node, return a view of the node that provides access
/// to the collection node specific properties.
public var collectionNode: CollectionNode? {
switch data {
case .layout:
return nil
default:
return CollectionNode(node: self)
}
}
/// Retrieve the attributes that should be printed on any API for the
/// generated node. If `forRaw` is true, this is for the raw syntax node.
public func apiAttributes(forRaw: Bool = false) -> AttributeListSyntax {
let attrList = AttributeListSyntax {
if isExperimental {
// SPI for enum cases currently requires Swift 5.8 to work correctly.
let experimentalSPI: AttributeListSyntax = """
#if compiler(>=5.8)
@_spi(ExperimentalLanguageFeatures)
#endif
"""
experimentalSPI.with(\.trailingTrivia, .newline)
}
if forRaw {
"@_spi(RawSyntax)"
}
}
return attrList.with(\.trailingTrivia, attrList.isEmpty ? [] : .newline)
}
public var apiAttributes: AttributeListSyntax {
self.apiAttributes()
}
/// Construct the specification for a layout syntax node.
init(
kind: SyntaxNodeKind,
base: SyntaxNodeKind,
experimentalFeature: ExperimentalFeature? = nil,
nameForDiagnostics: String?,
documentation: String? = nil,
disableSameTypeForUniqueChoice: Bool = false,
parserFunction: TokenSyntax? = nil,
traits: [String] = [],
children: [Child] = []
) {
precondition(base != .syntaxCollection)
precondition(base.isBase, "unknown base kind '\(base)' for node '\(kind)'")
self.kind = kind
self.base = base
self.experimentalFeature = experimentalFeature
self.nameForDiagnostics = nameForDiagnostics
self.documentation = SwiftSyntax.Trivia.docCommentTrivia(from: documentation)
self.disableSameTypeForUniqueChoice = disableSameTypeForUniqueChoice
self.parserFunction = parserFunction
let childrenWithUnexpected: [Child]
if children.isEmpty {
childrenWithUnexpected = [
Child(
name: "unexpected",
kind: .collection(kind: .unexpectedNodes, collectionElementName: "Unexpected"),
isOptional: true
)
]
} else {
// Add implicitly generated UnexpectedNodes children between
// any two defined children
childrenWithUnexpected =
children.enumerated().flatMap { (i, child) -> [Child] in
let childName = child.name.withFirstCharacterUppercased
let unexpectedName: String
let unexpectedDeprecatedName: String?
if i == 0 {
unexpectedName = "unexpectedBefore\(childName)"
unexpectedDeprecatedName = child.deprecatedName.map { "unexpectedBefore\($0.withFirstCharacterUppercased)" }
} else {
unexpectedName = "unexpectedBetween\(children[i - 1].name.withFirstCharacterUppercased)And\(childName)"
if let deprecatedName = children[i - 1].deprecatedName?.withFirstCharacterUppercased {
unexpectedDeprecatedName =
"unexpectedBetween\(deprecatedName)And\(child.deprecatedName?.withFirstCharacterUppercased ?? childName)"
} else if let deprecatedName = child.deprecatedName?.withFirstCharacterUppercased {
unexpectedDeprecatedName =
"unexpectedBetween\(children[i - 1].name.withFirstCharacterUppercased)And\(deprecatedName)"
} else {
unexpectedDeprecatedName = nil
}
}
let unexpectedBefore = Child(
name: unexpectedName,
deprecatedName: unexpectedDeprecatedName,
kind: .collection(kind: .unexpectedNodes, collectionElementName: unexpectedName),
isOptional: true
)
return [unexpectedBefore, child]
} + [
Child(
name: "unexpectedAfter\(children.last!.name.withFirstCharacterUppercased)",
deprecatedName: children.last!.deprecatedName.map { "unexpectedAfter\($0.withFirstCharacterUppercased)" },
kind: .collection(
kind: .unexpectedNodes,
collectionElementName: "UnexpectedAfter\(children.last!.name.withFirstCharacterUppercased)"
),
isOptional: true
)
]
}
self.data = .layout(children: childrenWithUnexpected, traits: traits)
}
/// A doc comment that lists all the nodes in which this node occurs as a child in.
public var containedIn: SwiftSyntax.Trivia {
if kind == .unexpectedNodes {
// We don't want to generate a 'Contained In' section for UnexpectedNodesSyntax
// because all nodes contain an UnexpectedNodesSyntax.
return []
}
var childIn: [(node: SyntaxNodeKind, child: Child?)] = []
for node in SYNTAX_NODES where !node.isExperimental {
if let layout = node.layoutNode {
for child in layout.children {
if child.kinds.contains(self.kind) {
childIn.append((node.kind, child))
}
}
} else if let collection = node.collectionNode {
if collection.elementChoices.contains(self.kind) {
childIn.append((node.kind, nil))
}
}
}
guard !childIn.isEmpty else {
return []
}
let list =
childIn
.map {
if let childName = $0.child?.identifier {
// This will repeat the syntax type before and after the dot, which is
// a little unfortunate, but it's the only way I found to get docc to
// generate a fully-qualified type + member.
if $0.node.isAvailableInDocc {
return " - \($0.node.doccLink).``\($0.node.syntaxType)/\(childName)``"
} else {
return " - \($0.node.doccLink).`\($0.node.syntaxType)/\(childName)`"
}
} else {
return " - \($0.node.doccLink)"
}
}
.joined(separator: "\n")
return .docCommentTrivia(
from: """
### Contained in
\(list)
"""
)
}
/// A doc comment that lists all the subtypes in which this node occurs as a base type in.
public var subtypes: SwiftSyntax.Trivia {
if kind == .unexpectedNodes {
return []
}
let list =
SYNTAX_NODES
.filter { $0.base == self.kind && !$0.isExperimental && !$0.kind.isDeprecated }
.map { "- \($0.kind.doccLink)" }
.joined(separator: "\n")
guard !list.isEmpty else {
return []
}
return .docCommentTrivia(
from: """
### Subtypes
\(list)
"""
)
}
/// Construct the specification for a collection syntax node.
///
/// `base` must be `.syntaxCollection`.
init(
kind: SyntaxNodeKind,
base: SyntaxNodeKind,
experimentalFeature: ExperimentalFeature? = nil,
nameForDiagnostics: String?,
documentation: String? = nil,
disableSameTypeForUniqueChoice: Bool = false,
parserFunction: TokenSyntax? = nil,
elementChoices: [SyntaxNodeKind]
) {
self.kind = kind
precondition(base == .syntaxCollection)
self.base = base
self.experimentalFeature = experimentalFeature
self.nameForDiagnostics = nameForDiagnostics
self.documentation = SwiftSyntax.Trivia.docCommentTrivia(from: documentation)
self.disableSameTypeForUniqueChoice = disableSameTypeForUniqueChoice
self.parserFunction = parserFunction
assert(!elementChoices.isEmpty)
self.data = .collection(choices: elementChoices)
}
}
/// Provides a view into a layout node that offers access to the layout-specific
/// properties.
@dynamicMemberLookup
public struct LayoutNode {
/// The underlying node
public let node: Node
fileprivate init(node: Node) {
switch node.data {
case .layout:
break
default:
preconditionFailure("NodeLayoutView must wrap a `Node` with data `.layout`")
}
self.node = node
}
/// Allow transparent accesss to the properties of the underlying `Node`.
public subscript<T>(dynamicMember keyPath: KeyPath<Node, T>) -> T {
return node[keyPath: keyPath]
}
/// The children of the layout node.
///
/// This includes unexpected children
public var children: [Child] {
switch node.data {
case .layout(children: let children, traits: _):
return children
case .collection:
preconditionFailure("NodeLayoutView must wrap a Node with data `.layout`")
}
}
/// All children in the node that are not unexpected.
public var nonUnexpectedChildren: [Child] {
return children.filter { !$0.isUnexpectedNodes }
}
/// Traits that the node conforms to.
public var traits: [String] {
switch node.data {
case .layout(children: _, traits: let traits):
return traits
case .collection:
preconditionFailure("NodeLayoutView must wrap a Node with data `.layout`")
}
}
public var grammar: SwiftSyntax.Trivia {
guard !children.isEmpty else {
return []
}
return .docCommentTrivia(
from: """
### Children
\(GrammarGenerator.childrenList(for: children))
"""
)
}
}
/// Provides a view into a collection node that offers access to the
/// collection-specific properties.
@dynamicMemberLookup
public struct CollectionNode {
/// The underlying node
public let node: Node
fileprivate init(node: Node) {
switch node.data {
case .collection:
break
default:
preconditionFailure("NodeLayoutView must wrap a `Node` with data `.layout`")
}
self.node = node
}
/// Allow transparent access to the properties of the underlying `Node`.
public subscript<T>(dynamicMember keyPath: KeyPath<Node, T>) -> T {
return node[keyPath: keyPath]
}
/// The kinds the elements can have.
///
/// This can be more than one in which case each element can have either of
/// these kinds.
public var elementChoices: [SyntaxNodeKind] {
switch node.data {
case .layout:
preconditionFailure("NodeLayoutView must wrap a Node with data `.collection`")
case .collection(choices: let choices):
return choices
}
}
public var grammar: SwiftSyntax.Trivia {
let grammar: String
if let onlyElement = elementChoices.only {
grammar = "\(onlyElement.doccLink) `*`"
} else {
grammar = "(\(elementChoices.map { "\($0.doccLink)" }.joined(separator: " | "))) `*`"
}
return .docCommentTrivia(
from: """
### Children
\(grammar)
"""
)
}
}
fileprivate extension Child {
var kinds: [SyntaxNodeKind] {
switch kind {
case .node(let kind):
return [kind]
case .nodeChoices(let choices):
return choices.flatMap(\.kinds)
case .collection(kind: let kind, _, _, _):
return [kind]
case .token:
return [.token]
}
}
}