-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathast.go
More file actions
362 lines (321 loc) · 10.1 KB
/
ast.go
File metadata and controls
362 lines (321 loc) · 10.1 KB
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
// Copyright 2025 TypeFox GmbH
// This program and the accompanying materials are made available under the
// terms of the MIT License, which is available in the project root.
package fastbelt
import (
"iter"
"strings"
"sync/atomic"
)
type AstNodeBase struct {
document *Document
container AstNode
tokens []*Token
segment TextSegment
}
func (node *AstNodeBase) Document() *Document {
if node != nil {
return node.document
} else {
return nil
}
}
func (node *AstNodeBase) SetDocument(document *Document) {
if node != nil {
node.document = document
}
}
func (node *AstNodeBase) Container() AstNode {
if node != nil {
return node.container
} else {
return nil
}
}
// TODO: If concrete methods gain access to generics, refactor this into a method
// See https://github.com/golang/go/issues/77273
func ContainerOfType[T AstNode](node AstNode) T {
var zero T
if node == nil {
return zero
}
current := node.Container()
for current != nil {
if casted, ok := current.(T); ok {
return casted
}
current = current.Container()
}
return zero
}
func (node *AstNodeBase) SetContainer(container AstNode) {
if node != nil {
node.container = container
}
}
func (node *AstNodeBase) Tokens() []*Token {
if node != nil {
return node.tokens
} else {
return nil
}
}
func (node *AstNodeBase) SetSegmentStartToken(token *Token) {
if node != nil && token != nil {
node.segment.Indices.Start = token.TextSegment.Indices.Start
node.segment.Range.Start = token.TextSegment.Range.Start
}
}
func (node *AstNodeBase) SetSegmentEndToken(token *Token) {
if node != nil && token != nil {
node.segment.Indices.End = token.TextSegment.Indices.End
node.segment.Range.End = token.TextSegment.Range.End
}
}
func (node *AstNodeBase) SetSegment(segment *TextSegment) {
if node != nil {
node.segment = *segment
}
}
func (node *AstNodeBase) Segment() *TextSegment {
if node != nil {
return &node.segment
} else {
return nil
}
}
func (node *AstNodeBase) SetToken(token *Token) {
if node != nil && token != nil {
node.tokens = append(node.tokens, token)
}
}
func (node *AstNodeBase) SetTokens(tokens []*Token) {
if node != nil {
// The method is called to set all tokens of the node at once
// The old node is discarded in the process
// Therefore, we don't append but replace the token slice
node.tokens = tokens
}
}
func (node *AstNodeBase) Text() string {
if node == nil || node.document == nil || node.document.TextDoc == nil {
return ""
} else {
return node.document.TextDoc.Text(nil)[node.segment.Indices.Start:node.segment.Indices.End]
}
}
func (node *AstNodeBase) ForEachNode(fn func(AstNode)) {
// This base implementation does not have any contained nodes.
}
func (node *AstNodeBase) ForEachReference(fn func(UntypedReference)) {
// This base implementation does not have any references.
}
// AstNode is the base interface for all AST nodes.
type AstNode interface {
Document() *Document
SetDocument(document *Document)
Container() AstNode
SetContainer(container AstNode)
Tokens() []*Token
SetToken(token *Token)
SetTokens(tokens []*Token)
Segment() *TextSegment
SetSegment(segment *TextSegment)
// Sets the start of the node's segment to the start of the given token's segment.
// Should only be called by the parser. Use SetSegment to set both start and end manually.
SetSegmentStartToken(token *Token)
// Sets the end of the node's segment to the end of the given token's segment.
// Should only be called by the parser. Use SetSegment to set both start and end manually.
SetSegmentEndToken(token *Token)
Text() string
// ForEachNode calls the given function for each direct child node of this node.
// Note that this does not traverse the entire subtree. Use [AllNodes] or [AllChildren] for that.
//
// Calling this method directly is not recommended. Use [ChildNodes] instead for better readability.
ForEachNode(fn func(AstNode))
// ForEachReference calls the given function for each reference contained in this node.
//
// Calling this method directly is not recommended. Use [References] instead for better readability.
ForEachReference(fn func(UntypedReference))
}
// Performance note about traversal function:
// Theoretically, we could have ChildNodes and References directly as methods on the AstNode interface.
// However, implementing the deep traversal on top of an iter.Seq is very inefficient.
// In benchmarks, it is roughly 5x slower than the current implementation.
// By using a callback-based approach, we can traverse the entire subtree with minimal overhead.
// But we lose the ability to short-circuit the traversal when we find what we're looking for.
// In practice, this is not a big issue, because most traversals will need to visit most of the nodes anyway.
// AllNodes and AllChildren are slightly less efficient than traverseContent,
// but only by roughly 10%, and they provide a much nicer API for most use cases, so the trade-off is worth it.
// Traverses all children of the given node, calling the specified function for each child.
// Does not call the function for the given node itself.
//
// Note that this function will traverse the entire subtree, without short-circuiting.
func traverseContent(node AstNode, fn func(AstNode)) {
node.ForEachNode(func(child AstNode) {
fn(child)
traverseContent(child, fn)
})
}
// [AllNodes] creates an iterator over the given node and all its descendant nodes.
//
// Early loop exit is honoured correctly, but does not short-circuit the traversal.
func AllNodes(node AstNode) iter.Seq[AstNode] {
return func(yield func(AstNode) bool) {
if !yield(node) {
return
}
stopped := false
traverseContent(node, func(n AstNode) {
if !stopped && !yield(n) {
stopped = true
}
})
}
}
// [AllChildren] creates an iterator over all descendant nodes of the given node, excluding the node itself.
//
// Early loop exit is honoured correctly, but does not short-circuit the traversal.
func AllChildren(node AstNode) iter.Seq[AstNode] {
return func(yield func(AstNode) bool) {
stopped := false
traverseContent(node, func(n AstNode) {
if !stopped && !yield(n) {
stopped = true
}
})
}
}
// [ChildNodes] creates an iterator over the direct child nodes of the given node.
//
// This function wraps [AstNode.ForEachNode] in an [iter.Seq].
// Early loop exit is honoured correctly, but does not short-circuit the traversal.
func ChildNodes(node AstNode) iter.Seq[AstNode] {
return func(yield func(AstNode) bool) {
stopped := false
node.ForEachNode(func(child AstNode) {
if !stopped && !yield(child) {
stopped = true
}
})
}
}
// [References] creates an iterator over all references of the given node.
//
// This function wraps [AstNode.ForEachReference] in an [iter.Seq].
// Early loop exit is honoured correctly, but does not short-circuit the traversal.
func References(node AstNode) iter.Seq[UntypedReference] {
return func(yield func(UntypedReference) bool) {
stopped := false
node.ForEachReference(func(ref UntypedReference) {
if !stopped && !yield(ref) {
stopped = true
}
})
}
}
func NewAstNode() AstNodeBase {
return AstNodeBase{
tokens: []*Token{},
}
}
func AssignToken(node AstNode, token *Token, kind int) {
if node != nil && token != nil {
node.SetToken(token)
token.Element = node
token.Kind = kind
}
}
func AssignTokens(node AstNode, tokens []*Token) {
if node != nil {
node.SetTokens(tokens)
for _, token := range tokens {
token.Element = node
}
}
}
func MergeTokens(newNode AstNode, oldTokens []*Token) {
if newNode != nil && len(oldTokens) > 0 {
// Prepend old tokens to the new node's tokens
AssignTokens(newNode, append(oldTokens, newNode.Tokens()...))
}
}
func AssignContainers(doc *Document, root AstNode) {
root.SetDocument(doc)
root.ForEachNode(func(child AstNode) {
child.SetDocument(doc)
child.SetContainer(root)
AssignContainers(doc, child)
})
root.ForEachReference(func(ur UntypedReference) {
unit := ur.Unit()
if stringNode, ok := unit.(CompositeNode); ok {
stringNode.SetDocument(doc)
stringNode.SetContainer(root)
}
})
}
// Represents a node whose name is accessible as a string in the Name field.
type NamedNode interface {
AstNode
Name() string
}
// Represents a node whose name is represented by a [Token], stored in the "Name" field of the node.
type NamedTokenNode interface {
NamedNode
NameToken() *Token
}
// Represents a node whose name is represented by a [CompositeNode], stored in the "Name" field of the node.
type NamedCompositeNode interface {
NamedNode
NameNode() CompositeNode
}
// [StringUnit] is a common interface for both [Token] and [CompositeNode], as both can serve as the "name" of a reference.
type StringUnit interface {
Owner() AstNode
Segment() *TextSegment
String() string
}
// [CompositeNode] represents a composed string value that is made up of multiple tokens.
// A common example for this is a fully qualified name that consists of multiple identifiers and dots, e.g. "a.b.c".
// Every "composite" rule of a grammar will be represented as a [CompositeNode] in the AST, even if it only consists of a single token.
type CompositeNode interface {
AstNode
StringUnit
IsCompositeNode()
}
func NewCompositeNode() CompositeNode {
return &CompositeNodeBase{
AstNodeBase: NewAstNode(),
}
}
type CompositeNodeBase struct {
AstNodeBase
// We could use a sync.Once here, but that would add some overhead
// In benchmarks, using an atomic pointer here is much faster (roughly 2x)
cache atomic.Pointer[string]
}
func (node *CompositeNodeBase) IsCompositeNode() {}
func (node *CompositeNodeBase) Owner() AstNode {
return node.container
}
func (node *CompositeNodeBase) String() string {
// Cache the string value, as it is accessed frequently
// Since this operation can be done in parallel, we need an atomic pointer here
if p := node.cache.Load(); p != nil {
return *p
} else {
s := node.stringSlow()
node.cache.Store(&s)
return s
}
}
func (node *CompositeNodeBase) stringSlow() string {
// Construct the string value by concatenating the text of all tokens of the node
// Only need to do this once, as the tokens are usually not modified after parsing
var sb strings.Builder
for _, token := range node.Tokens() {
sb.WriteString(token.Image)
}
return sb.String()
}