-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtree.ts
More file actions
1724 lines (1546 loc) · 66.2 KB
/
tree.ts
File metadata and controls
1724 lines (1546 loc) · 66.2 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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Parser} from "./parse"
/// The default maximum length of a `TreeBuffer` node.
export const DefaultBufferLength = 1024
let nextPropID = 0
export class Range {
constructor(readonly from: number, readonly to: number) {}
}
/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
/// can have metadata associated with it in props. Instances of this
/// class represent prop names.
export class NodeProp<T> {
/// @internal
id: number
/// Indicates whether this prop is stored per [node
/// type](#common.NodeType) or per [tree node](#common.Tree).
perNode: boolean
/// A method that deserializes a value of this prop from a string.
/// Can be used to allow a prop to be directly written in a grammar
/// file.
deserialize: (str: string) => T
/// @internal
combine: ((a: T, b: T) => T) | null
/// Create a new node prop type.
constructor(config: {
/// The [deserialize](#common.NodeProp.deserialize) function to
/// use for this prop, used for example when directly providing
/// the prop from a grammar file. Defaults to a function that
/// raises an error.
deserialize?: (str: string) => T,
/// If configuring another value for this prop when it already
/// exists on a node should combine the old and new values, rather
/// than overwrite the old value, you can pass a function that
/// does the combining here.
combine?: (a: T, b: T) => T
/// By default, node props are stored in the [node
/// type](#common.NodeType). It can sometimes be useful to directly
/// store information (usually related to the parsing algorithm)
/// in [nodes](#common.Tree) themselves. Set this to true to enable
/// that for this prop.
perNode?: boolean
} = {}) {
this.id = nextPropID++
this.perNode = !!config.perNode
this.deserialize = config.deserialize || (() => {
throw new Error("This node type doesn't define a deserialize function")
})
this.combine = config.combine || null
}
/// This is meant to be used with
/// [`NodeSet.extend`](#common.NodeSet.extend) or
/// [`LRParser.configure`](#lr.ParserConfig.props) to compute
/// prop values for each node type in the set. Takes a [match
/// object](#common.NodeType^match) or function that returns undefined
/// if the node type doesn't get this prop, and the prop's value if
/// it does.
add(match: {[selector: string]: T} | ((type: NodeType) => T | undefined)): NodePropSource {
if (this.perNode) throw new RangeError("Can't add per-node props to node types")
if (typeof match != "function") match = NodeType.match(match)
return (type) => {
let result = (match as (type: NodeType) => T | undefined)(type)
return result === undefined ? null : [this, result]
}
}
/// Prop that is used to describe matching delimiters. For opening
/// delimiters, this holds an array of node names (written as a
/// space-separated string when declaring this prop in a grammar)
/// for the node types of closing delimiters that match it.
static closedBy = new NodeProp<readonly string[]>({deserialize: str => str.split(" ")})
/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
/// attached to closing delimiters, holding an array of node names
/// of types of matching opening delimiters.
static openedBy = new NodeProp<readonly string[]>({deserialize: str => str.split(" ")})
/// Used to assign node types to groups (for example, all node
/// types that represent an expression could be tagged with an
/// `"Expression"` group).
static group = new NodeProp<readonly string[]>({deserialize: str => str.split(" ")})
/// Attached to nodes to indicate these should be
/// [displayed](https://codemirror.net/docs/ref/#language.syntaxTree)
/// in a bidirectional text isolate, so that direction-neutral
/// characters on their sides don't incorrectly get associated with
/// surrounding text. You'll generally want to set this for nodes
/// that contain arbitrary text, like strings and comments, and for
/// nodes that appear _inside_ arbitrary text, like HTML tags. When
/// not given a value, in a grammar declaration, defaults to
/// `"auto"`.
static isolate = new NodeProp<"rtl" | "ltr" | "auto">({deserialize: value => {
if (value && value != "rtl" && value != "ltr" && value != "auto")
throw new RangeError("Invalid value for isolate: " + value)
return (value as any) || "auto"
}})
/// The hash of the [context](#lr.ContextTracker.constructor)
/// that the node was parsed in, if any. Used to limit reuse of
/// contextual nodes.
static contextHash = new NodeProp<number>({perNode: true})
/// The distance beyond the end of the node that the tokenizer
/// looked ahead for any of the tokens inside the node. (The LR
/// parser only stores this when it is larger than 25, for
/// efficiency reasons.)
static lookAhead = new NodeProp<number>({perNode: true})
/// This per-node prop is used to replace a given node, or part of a
/// node, with another tree. This is useful to include trees from
/// different languages in mixed-language parsers.
static mounted = new NodeProp<MountedTree>({perNode: true})
}
/// A mounted tree, which can be [stored](#common.NodeProp^mounted) on
/// a tree node to indicate that parts of its content are
/// represented by another tree.
export class MountedTree {
constructor(
/// The inner tree.
readonly tree: Tree,
/// If this is null, this tree replaces the entire node (it will
/// be included in the regular iteration instead of its host
/// node). If not, only the given ranges are considered to be
/// covered by this tree. This is used for trees that are mixed in
/// a way that isn't strictly hierarchical. Such mounted trees are
/// only entered by [`resolveInner`](#common.Tree.resolveInner)
/// and [`enter`](#common.SyntaxNode.enter).
readonly overlay: readonly {from: number, to: number}[] | null,
/// The parser used to create this subtree.
readonly parser: Parser,
/// [Indicates](#common.IterMode.EnterBracketed) that the nested
/// content is delineated with some kind
/// of bracket token.
readonly bracketed = false
) {}
/// @internal
static get(tree: Tree | null): MountedTree | null {
return tree && tree.props && tree.props[NodeProp.mounted.id]
}
}
/// Type returned by [`NodeProp.add`](#common.NodeProp.add). Describes
/// whether a prop should be added to a given node type in a node set,
/// and what value it should have.
export type NodePropSource = (type: NodeType) => null | [NodeProp<any>, any]
// Note: this is duplicated in lr/src/constants.ts
const enum NodeFlag {
Top = 1,
Skipped = 2,
Error = 4,
Anonymous = 8
}
const noProps: {[propID: number]: any} = Object.create(null)
/// Each node in a syntax tree has a node type associated with it.
export class NodeType {
/// @internal
constructor(
/// The name of the node type. Not necessarily unique, but if the
/// grammar was written properly, different node types with the
/// same name within a node set should play the same semantic
/// role.
readonly name: string,
/// @internal
readonly props: {readonly [prop: number]: any},
/// The id of this node in its set. Corresponds to the term ids
/// used in the parser.
readonly id: number,
/// @internal
readonly flags: number = 0) {}
/// Define a node type.
static define(spec: {
/// The ID of the node type. When this type is used in a
/// [set](#common.NodeSet), the ID must correspond to its index in
/// the type array.
id: number,
/// The name of the node type. Leave empty to define an anonymous
/// node.
name?: string,
/// [Node props](#common.NodeProp) to assign to the type. The value
/// given for any given prop should correspond to the prop's type.
props?: readonly ([NodeProp<any>, any] | NodePropSource)[],
/// Whether this is a [top node](#common.NodeType.isTop).
top?: boolean,
/// Whether this node counts as an [error
/// node](#common.NodeType.isError).
error?: boolean,
/// Whether this node is a [skipped](#common.NodeType.isSkipped)
/// node.
skipped?: boolean
}) {
let props = spec.props && spec.props.length ? Object.create(null) : noProps
let flags = (spec.top ? NodeFlag.Top : 0) | (spec.skipped ? NodeFlag.Skipped : 0) |
(spec.error ? NodeFlag.Error : 0) | (spec.name == null ? NodeFlag.Anonymous : 0)
let type = new NodeType(spec.name || "", props, spec.id, flags)
if (spec.props) for (let src of spec.props) {
if (!Array.isArray(src)) src = src(type)!
if (src) {
if (src[0].perNode) throw new RangeError("Can't store a per-node prop on a node type")
props[src[0].id] = src[1]
}
}
return type
}
/// Retrieves a node prop for this type. Will return `undefined` if
/// the prop isn't present on this node.
prop<T>(prop: NodeProp<T>): T | undefined { return this.props[prop.id] }
/// True when this is the top node of a grammar.
get isTop() { return (this.flags & NodeFlag.Top) > 0 }
/// True when this node is produced by a skip rule.
get isSkipped() { return (this.flags & NodeFlag.Skipped) > 0 }
/// Indicates whether this is an error node.
get isError() { return (this.flags & NodeFlag.Error) > 0 }
/// When true, this node type doesn't correspond to a user-declared
/// named node, for example because it is used to cache repetition.
get isAnonymous() { return (this.flags & NodeFlag.Anonymous) > 0 }
/// Returns true when this node's name or one of its
/// [groups](#common.NodeProp^group) matches the given string.
is(name: string | number) {
if (typeof name == 'string') {
if (this.name == name) return true
let group = this.prop(NodeProp.group)
return group ? group.indexOf(name) > -1 : false
}
return this.id == name
}
/// An empty dummy node type to use when no actual type is available.
static none: NodeType = new NodeType("", Object.create(null), 0, NodeFlag.Anonymous)
/// Create a function from node types to arbitrary values by
/// specifying an object whose property names are node or
/// [group](#common.NodeProp^group) names. Often useful with
/// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
/// names, separated by spaces, in a single property name to map
/// multiple node names to a single value.
static match<T>(map: {[selector: string]: T}): (node: NodeType) => T | undefined {
let direct = Object.create(null)
for (let prop in map)
for (let name of prop.split(" ")) direct[name] = map[prop]
return (node: NodeType) => {
for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
let found = direct[i < 0 ? node.name : groups![i]]
if (found) return found
}
}
}
}
/// A node set holds a collection of node types. It is used to
/// compactly represent trees by storing their type ids, rather than a
/// full pointer to the type object, in a numeric array. Each parser
/// [has](#lr.LRParser.nodeSet) a node set, and [tree
/// buffers](#common.TreeBuffer) can only store collections of nodes
/// from the same set. A set can have a maximum of 2**16 (65536) node
/// types in it, so that the ids fit into 16-bit typed array slots.
export class NodeSet {
/// Create a set with the given types. The `id` property of each
/// type should correspond to its position within the array.
constructor(
/// The node types in this set, by id.
readonly types: readonly NodeType[]
) {
for (let i = 0; i < types.length; i++) if (types[i].id != i)
throw new RangeError("Node type ids should correspond to array positions when creating a node set")
}
/// Create a copy of this set with some node properties added. The
/// arguments to this method can be created with
/// [`NodeProp.add`](#common.NodeProp.add).
extend(...props: NodePropSource[]): NodeSet {
let newTypes: NodeType[] = []
for (let type of this.types) {
let newProps: null | {[id: number]: any} = null
for (let source of props) {
let add = source(type)
if (add) {
if (!newProps) newProps = Object.assign({}, type.props)
let value = add[1], prop = add[0]
if (prop.combine && prop.id in newProps) value = prop.combine(newProps[prop.id], value)
newProps[prop.id] = value
}
}
newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type)
}
return new NodeSet(newTypes)
}
}
const CachedNode = new WeakMap<Tree, SyntaxNode>(), CachedInnerNode = new WeakMap<Tree, SyntaxNode>()
/// Options that control iteration. Can be combined with the `|`
/// operator to enable multiple ones.
export enum IterMode {
/// When enabled, iteration will only visit [`Tree`](#common.Tree)
/// objects, not nodes packed into
/// [`TreeBuffer`](#common.TreeBuffer)s.
ExcludeBuffers = 1,
/// Enable this to make iteration include anonymous nodes (such as
/// the nodes that wrap repeated grammar constructs into a balanced
/// tree).
IncludeAnonymous = 2,
/// By default, regular [mounted](#common.NodeProp^mounted) nodes
/// replace their base node in iteration. Enable this to ignore them
/// instead.
IgnoreMounts = 4,
/// This option only applies in
/// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
/// library to not enter mounted overlays if one covers the given
/// position.
IgnoreOverlays = 8,
/// When set, positions on the boundary of a mounted overlay tree
/// that has its [`bracketed`](#common.NestedParse.bracketed) flag
/// set will enter that tree regardless of side. Only supported in
/// [`enter`](#common.SyntaxNode.enter), not in cursors.
EnterBracketed = 16,
}
/// A piece of syntax tree. There are two ways to approach these
/// trees: the way they are actually stored in memory, and the
/// convenient way.
///
/// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
/// objects. By packing detail information into `TreeBuffer` leaf
/// nodes, the representation is made a lot more memory-efficient.
///
/// However, when you want to actually work with tree nodes, this
/// representation is very awkward, so most client code will want to
/// use the [`TreeCursor`](#common.TreeCursor) or
/// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
/// a view on some part of this data structure, and can be used to
/// move around to adjacent nodes.
export class Tree {
/// @internal
props: null | {[id: number]: any} = null
/// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
constructor(
/// The type of the top node.
readonly type: NodeType,
/// This node's child nodes.
readonly children: readonly (Tree | TreeBuffer)[],
/// The positions (offsets relative to the start of this tree) of
/// the children.
readonly positions: readonly number[],
/// The total length of this tree
readonly length: number,
/// Per-node [node props](#common.NodeProp) to associate with this node.
props?: readonly [NodeProp<any> | number, any][]
) {
if (props && props.length) {
this.props = Object.create(null)
for (let [prop, value] of props) this.props![typeof prop == "number" ? prop : prop.id] = value
}
}
/// @internal
toString(): string {
let mounted = MountedTree.get(this)
if (mounted && !mounted.overlay) return mounted.tree.toString()
let children = ""
for (let ch of this.children) {
let str = ch.toString()
if (str) {
if (children) children += ","
children += str
}
}
return !this.type.name ? children :
(/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
(children.length ? "(" + children + ")" : "")
}
/// The empty tree
static empty = new Tree(NodeType.none, [], [], 0)
/// Get a [tree cursor](#common.TreeCursor) positioned at the top of
/// the tree. Mode can be used to [control](#common.IterMode) which
/// nodes the cursor visits.
cursor(mode: IterMode = 0 as IterMode) {
return new TreeCursor(this.topNode as TreeNode, mode)
}
/// Get a [tree cursor](#common.TreeCursor) pointing into this tree
/// at the given position and side (see
/// [`moveTo`](#common.TreeCursor.moveTo).
cursorAt(pos: number, side: -1 | 0 | 1 = 0, mode: IterMode = 0 as IterMode): TreeCursor {
let scope = CachedNode.get(this) || this.topNode
let cursor = new TreeCursor(scope as TreeNode | BufferNode)
cursor.moveTo(pos, side)
CachedNode.set(this, cursor._tree)
return cursor
}
/// Get a [syntax node](#common.SyntaxNode) object for the top of the
/// tree.
get topNode(): SyntaxNode {
return new TreeNode(this, 0, 0, null)
}
/// Get the [syntax node](#common.SyntaxNode) at the given position.
/// If `side` is -1, this will move into nodes that end at the
/// position. If 1, it'll move into nodes that start at the
/// position. With 0, it'll only enter nodes that cover the position
/// from both sides.
///
/// Note that this will not enter
/// [overlays](#common.MountedTree.overlay), and you often want
/// [`resolveInner`](#common.Tree.resolveInner) instead.
resolve(pos: number, side: -1 | 0 | 1 = 0) {
let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false)
CachedNode.set(this, node)
return node
}
/// Like [`resolve`](#common.Tree.resolve), but will enter
/// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
/// pointing into the innermost overlaid tree at the given position
/// (with parent links going through all parent structure, including
/// the host trees).
resolveInner(pos: number, side: -1 | 0 | 1 = 0) {
let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true)
CachedInnerNode.set(this, node)
return node
}
/// In some situations, it can be useful to iterate through all
/// nodes around a position, including those in overlays that don't
/// directly cover the position. This method gives you an iterator
/// that will produce all nodes, from small to big, around the given
/// position.
resolveStack(pos: number, side: -1 | 0 | 1 = 0): NodeIterator {
return stackIterator(this, pos, side)
}
/// Iterate over the tree and its children, calling `enter` for any
/// node that touches the `from`/`to` region (if given) before
/// running over such a node's children, and `leave` (if given) when
/// leaving the node. When `enter` returns `false`, that node will
/// not have its children iterated over (or `leave` called).
iterate(spec: {
enter(node: SyntaxNodeRef): boolean | void,
leave?(node: SyntaxNodeRef): void,
from?: number,
to?: number,
mode?: IterMode
}) {
let {enter, leave, from = 0, to = this.length} = spec
let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0
for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {
let entered = false
if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
if (c.firstChild()) continue
entered = true
}
for (;;) {
if (entered && leave && (anon || !c.type.isAnonymous)) leave(c)
if (c.nextSibling()) break
if (!c.parent()) return
entered = true
}
}
}
/// Get the value of the given [node prop](#common.NodeProp) for this
/// node. Works with both per-node and per-type props.
prop<T>(prop: NodeProp<T>): T | undefined {
return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined
}
/// Returns the node's [per-node props](#common.NodeProp.perNode) in a
/// format that can be passed to the [`Tree`](#common.Tree)
/// constructor.
get propValues(): readonly [NodeProp<any> | number, any][] {
let result: [NodeProp<any> | number, any][] = []
if (this.props) for (let id in this.props) result.push([+id, this.props[id]])
return result
}
/// Balance the direct children of this tree, producing a copy of
/// which may have children grouped into subtrees with type
/// [`NodeType.none`](#common.NodeType^none).
balance(config: {
/// Function to create the newly balanced subtrees.
makeTree?: (children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number) => Tree
} = {}) {
return this.children.length <= Balance.BranchFactor ? this :
balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length,
(children, positions, length) => new Tree(this.type, children, positions, length, this.propValues),
config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)))
}
/// Build a tree from a postfix-ordered buffer of node information,
/// or a cursor over such a buffer.
static build(data: BuildData) { return buildTree(data) }
}
/// Represents a sequence of nodes.
export type NodeIterator = {node: SyntaxNode, next: NodeIterator | null}
type BuildData = {
/// The buffer or buffer cursor to read the node data from.
///
/// When this is an array, it should contain four values for every
/// node in the tree.
///
/// - The first holds the node's type, as a node ID pointing into
/// the given `NodeSet`.
/// - The second holds the node's start offset.
/// - The third the end offset.
/// - The fourth the amount of space taken up in the array by this
/// node and its children. Since there's four values per node,
/// this is the total number of nodes inside this node (children
/// and transitive children) plus one for the node itself, times
/// four.
///
/// Parent nodes should appear _after_ child nodes in the array. As
/// an example, a node of type 10 spanning positions 0 to 4, with
/// two children, of type 11 and 12, might look like this:
///
/// [11, 0, 1, 4, 12, 2, 4, 4, 10, 0, 4, 12]
buffer: BufferCursor | readonly number[],
/// The node types to use.
nodeSet: NodeSet,
/// The id of the top node type.
topID: number,
/// The position the tree should start at. Defaults to 0.
start?: number,
/// The position in the buffer where the function should stop
/// reading. Defaults to 0.
bufferStart?: number,
/// The length of the wrapping node. The end offset of the last
/// child is used when not provided.
length?: number,
/// The maximum buffer length to use. Defaults to
/// [`DefaultBufferLength`](#common.DefaultBufferLength).
maxBufferLength?: number,
/// An optional array holding reused nodes that the buffer can refer
/// to.
reused?: readonly Tree[],
/// The first node type that indicates repeat constructs in this
/// grammar.
minRepeatType?: number
}
/// This is used by `Tree.build` as an abstraction for iterating over
/// a tree buffer. A cursor initially points at the very last element
/// in the buffer. Every time `next()` is called it moves on to the
/// previous one.
export interface BufferCursor {
/// The current buffer position (four times the number of nodes
/// remaining).
pos: number
/// The node ID of the next node in the buffer.
id: number
/// The start position of the next node in the buffer.
start: number
/// The end position of the next node.
end: number
/// The size of the next node (the number of nodes inside, counting
/// the node itself, times 4).
size: number
/// Moves `this.pos` down by 4.
next(): void
/// Create a copy of this cursor.
fork(): BufferCursor
}
class FlatBufferCursor implements BufferCursor {
constructor(readonly buffer: readonly number[], public index: number) {}
get id() { return this.buffer[this.index - 4] }
get start() { return this.buffer[this.index - 3] }
get end() { return this.buffer[this.index - 2] }
get size() { return this.buffer[this.index - 1] }
get pos() { return this.index }
next() { this.index -= 4 }
fork() { return new FlatBufferCursor(this.buffer, this.index) }
}
/// Tree buffers contain (type, start, end, endIndex) quads for each
/// node. In such a buffer, nodes are stored in prefix order (parents
/// before children, with the endIndex of the parent indicating which
/// children belong to it).
export class TreeBuffer {
/// Create a tree buffer.
constructor(
/// The buffer's content.
readonly buffer: Uint16Array,
/// The total length of the group of nodes in the buffer.
readonly length: number,
/// The node set used in this buffer.
readonly set: NodeSet
) {}
/// @internal
get type() { return NodeType.none }
/// @internal
toString() {
let result: string[] = []
for (let index = 0; index < this.buffer.length;) {
result.push(this.childString(index))
index = this.buffer[index + 3]
}
return result.join(",")
}
/// @internal
childString(index: number): string {
let id = this.buffer[index], endIndex = this.buffer[index + 3]
let type = this.set.types[id], result = type.name
if (/\W/.test(result) && !type.isError) result = JSON.stringify(result)
index += 4
if (endIndex == index) return result
let children: string[] = []
while (index < endIndex) {
children.push(this.childString(index))
index = this.buffer[index + 3]
}
return result + "(" + children.join(",") + ")"
}
/// @internal
findChild(startIndex: number, endIndex: number, dir: 1 | -1, pos: number, side: Side) {
let {buffer} = this, pick = -1
for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
pick = i
if (dir > 0) break
}
}
return pick
}
/// @internal
slice(startI: number, endI: number, from: number) {
let b = this.buffer
let copy = new Uint16Array(endI - startI), len = 0
for (let i = startI, j = 0; i < endI;) {
copy[j++] = b[i++]
copy[j++] = b[i++] - from
let to = copy[j++] = b[i++] - from
copy[j++] = b[i++] - startI
len = Math.max(len, to)
}
return new TreeBuffer(copy, len, this.set)
}
}
/// The set of properties provided by both [`SyntaxNode`](#common.SyntaxNode)
/// and [`TreeCursor`](#common.TreeCursor). Note that, if you need
/// an object that is guaranteed to stay stable in the future, you
/// need to use the [`node`](#common.SyntaxNodeRef.node) accessor.
export interface SyntaxNodeRef {
/// The start position of the node.
readonly from: number
/// The end position of the node.
readonly to: number
/// The type of the node.
readonly type: NodeType
/// The name of the node (`.type.name`).
readonly name: string
/// Get the [tree](#common.Tree) that represents the current node,
/// if any. Will return null when the node is in a [tree
/// buffer](#common.TreeBuffer).
readonly tree: Tree | null
/// Retrieve a stable [syntax node](#common.SyntaxNode) at this
/// position.
readonly node: SyntaxNode
/// Test whether the node matches a given context—a sequence of
/// direct parent nodes. Empty strings in the context array act as
/// wildcards, other strings must match the ancestor node's name.
matchContext(context: readonly string[]): boolean
}
/// A syntax node provides an immutable pointer to a given node in a
/// tree. When iterating over large amounts of nodes, you may want to
/// use a mutable [cursor](#common.TreeCursor) instead, which is more
/// efficient.
export interface SyntaxNode extends SyntaxNodeRef {
/// The node's parent node, if any.
parent: SyntaxNode | null
/// The first child, if the node has children.
firstChild: SyntaxNode | null
/// The node's last child, if available.
lastChild: SyntaxNode | null
/// The first child that ends after `pos`.
childAfter(pos: number): SyntaxNode | null
/// The last child that starts before `pos`.
childBefore(pos: number): SyntaxNode | null
/// Enter the child at the given position. If side is -1 the child
/// may end at that position, when 1 it may start there.
///
/// This will by default enter
/// [overlaid](#common.MountedTree.overlay)
/// [mounted](#common.NodeProp^mounted) trees. You can set
/// `overlays` to false to disable that.
///
/// Similarly, when `buffers` is false this will not enter
/// [buffers](#common.TreeBuffer), only [nodes](#common.Tree) (which
/// is mostly useful when looking for props, which cannot exist on
/// buffer-allocated nodes).
enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null
/// This node's next sibling, if any.
nextSibling: SyntaxNode | null
/// This node's previous sibling.
prevSibling: SyntaxNode | null
/// Read the given node prop from this node.
prop<T>(prop: NodeProp<T>): T | undefined
/// A [tree cursor](#common.TreeCursor) starting at this node.
cursor(mode?: IterMode): TreeCursor
/// Find the node around, before (if `side` is -1), or after (`side`
/// is 1) the given position. Will look in parent nodes if the
/// position is outside this node.
resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode
/// Similar to `resolve`, but enter
/// [overlaid](#common.MountedTree.overlay) nodes.
resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode
/// Move the position to the innermost node before `pos` that looks
/// like it is unfinished (meaning it ends in an error node or has a
/// child ending in an error node right at its end).
enterUnfinishedNodesBefore(pos: number): SyntaxNode
/// Get a [tree](#common.Tree) for this node. Will allocate one if it
/// points into a buffer.
toTree(): Tree
/// Get the first child of the given type (which may be a [node
/// name](#common.NodeType.name) or a [group
/// name](#common.NodeProp^group)). If `before` is non-null, only
/// return children that occur somewhere after a node with that name
/// or group. If `after` is non-null, only return children that
/// occur somewhere before a node with that name or group.
getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode | null
/// Like [`getChild`](#common.SyntaxNode.getChild), but return all
/// matching children, not just the first.
getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[]
}
const enum Side {
Before = -2,
AtOrBefore = -1,
Around = 0,
AtOrAfter = 1,
After = 2,
DontCare = 4
}
function checkSide(side: Side, pos: number, from: number, to: number) {
switch (side) {
case Side.Before: return from < pos
case Side.AtOrBefore: return to >= pos && from < pos
case Side.Around: return from < pos && to > pos
case Side.AtOrAfter: return from <= pos && to > pos
case Side.After: return to > pos
case Side.DontCare: return true
}
}
function resolveNode(node: SyntaxNode, pos: number, side: -1 | 0 | 1, overlays: boolean): SyntaxNode {
// Move up to a node that actually holds the position, if possible
while (node.from == node.to ||
(side < 1 ? node.from >= pos : node.from > pos) ||
(side > -1 ? node.to <= pos : node.to < pos)) {
let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent
if (!parent) return node
node = parent
}
let mode = overlays ? 0 : IterMode.IgnoreOverlays
// Must go up out of overlays when those do not overlap with pos
if (overlays) for (let scan: SyntaxNode | null = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
if (scan instanceof TreeNode && scan.index < 0 && parent.enter(pos, side, mode)?.from != scan.from)
node = parent
}
for (;;) {
let inner = node.enter(pos, side, mode)
if (!inner) return node
node = inner
}
}
abstract class BaseNode implements SyntaxNode {
abstract from: number
abstract to: number
abstract type: NodeType
abstract name: string
abstract tree: Tree | null
abstract parent: SyntaxNode | null
abstract firstChild: SyntaxNode | null
abstract lastChild: SyntaxNode | null
abstract childAfter(pos: number): SyntaxNode | null
abstract childBefore(pos: number): SyntaxNode | null
abstract enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null
abstract nextSibling: SyntaxNode | null
abstract prevSibling: SyntaxNode | null
abstract toTree(): Tree
abstract prop<T>(prop: NodeProp<T>): T | undefined
cursor(mode: IterMode = 0 as IterMode) { return new TreeCursor(this as any, mode) }
getChild(type: string | number, before: string | number | null = null, after: string | number | null = null) {
let r = getChildren(this, type, before, after)
return r.length ? r[0] : null
}
getChildren(type: string | number, before: string | number | null = null, after: string | number | null = null): SyntaxNode[] {
return getChildren(this, type, before, after)
}
resolve(pos: number, side: -1 | 0 | 1 = 0): SyntaxNode {
return resolveNode(this, pos, side, false)
}
resolveInner(pos: number, side: -1 | 0 | 1 = 0): SyntaxNode {
return resolveNode(this, pos, side, true)
}
matchContext(context: readonly string[]): boolean {
return matchNodeContext(this.parent, context)
}
enterUnfinishedNodesBefore(pos: number) {
let scan = this.childBefore(pos), node: SyntaxNode = this
while (scan) {
let last = scan.lastChild
if (!last || last.to != scan.to) break
if (last.type.isError && last.from == last.to) {
node = scan
scan = last.prevSibling
} else {
scan = last
}
}
return node
}
get node() { return this }
get next() { return this.parent }
}
export class TreeNode extends BaseNode implements SyntaxNode {
constructor(readonly _tree: Tree,
readonly from: number,
// Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
readonly index: number,
readonly _parent: TreeNode | null) { super() }
get type() { return this._tree.type }
get name() { return this._tree.type.name }
get to() { return this.from + this._tree.length }
nextChild(i: number, dir: 1 | -1, pos: number, side: Side, mode: IterMode = 0 as IterMode): TreeNode | BufferNode | null {
for (let parent: TreeNode = this;;) {
for (let {children, positions} = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
let next = children[i], start = positions[i] + parent.from, mounted
if (!((mode & IterMode.EnterBracketed) && next instanceof Tree &&
(mounted = MountedTree.get(next)) && !mounted.overlay && mounted.bracketed &&
pos >= start && pos <= start + next.length) &&
!checkSide(side, pos, start, start + next.length))
continue
if (next instanceof TreeBuffer) {
if (mode & IterMode.ExcludeBuffers) continue
let index = next.findChild(0, next.buffer.length, dir, pos - start, side)
if (index > -1) return new BufferNode(new BufferContext(parent, next, i, start), null, index)
} else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
let mounted
if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
return new TreeNode(mounted.tree, start, i, parent)
let inner = new TreeNode(next, start, i, parent)
return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
: inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side, mode)
}
}
if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous) return null
if (parent.index >= 0) i = parent.index + dir
else i = dir < 0 ? -1 : parent._parent!._tree.children.length
parent = parent._parent!
if (!parent) return null
}
}
get firstChild() { return this.nextChild(0, 1, 0, Side.DontCare) }
get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, Side.DontCare) }
childAfter(pos: number) { return this.nextChild(0, 1, pos, Side.After) }
childBefore(pos: number) { return this.nextChild(this._tree.children.length - 1, -1, pos, Side.Before) }
prop<T>(prop: NodeProp<T>): T | undefined { return this._tree.prop(prop) }
enter(pos: number, side: -1 | 0 | 1, mode = 0) {
let mounted
if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
let rPos = pos - this.from, enterBracketed = (mode & IterMode.EnterBracketed) && mounted.bracketed
for (let {from, to} of mounted.overlay) {
if ((side > 0 || enterBracketed ? from <= rPos : from < rPos) &&
(side < 0 || enterBracketed ? to >= rPos : to > rPos))
return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this)
}
}
return this.nextChild(0, 1, pos, side, mode)
}
nextSignificantParent() {
let val: TreeNode = this
while (val.type.isAnonymous && val._parent) val = val._parent
return val
}
get parent(): TreeNode | null {
return this._parent ? this._parent.nextSignificantParent() : null
}
get nextSibling(): SyntaxNode | null {
return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, Side.DontCare) : null
}
get prevSibling(): SyntaxNode | null {
return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, Side.DontCare) : null
}
get tree() { return this._tree }
toTree() { return this._tree }
/// @internal
toString() { return this._tree.toString() }
}
function getChildren(node: SyntaxNode, type: string | number, before: string | number | null, after: string | number | null): SyntaxNode[] {
let cur = node.cursor(), result: SyntaxNode[] = []
if (!cur.firstChild()) return result
if (before != null) for (let found = false; !found;) {
found = cur.type.is(before)
if (!cur.nextSibling()) return result
}
for (;;) {
if (after != null && cur.type.is(after)) return result
if (cur.type.is(type)) result.push(cur.node)
if (!cur.nextSibling()) return after == null ? result : []
}
}
function matchNodeContext(node: SyntaxNode | null, context: readonly string[], i = context.length - 1): boolean {
for (let p = node; i >= 0; p = p.parent) {
if (!p) return false
if (!p.type.isAnonymous) {
if (context[i] && context[i] != p.name) return false
i--
}
}
return true
}
class BufferContext {
constructor(readonly parent: TreeNode,
readonly buffer: TreeBuffer,
readonly index: number,
readonly start: number) {}
}
export class BufferNode extends BaseNode {
type: NodeType
get name() { return this.type.name }
get from() { return this.context.start + this.context.buffer.buffer[this.index + 1] }
get to() { return this.context.start + this.context.buffer.buffer[this.index + 2] }
constructor(readonly context: BufferContext,
readonly _parent: BufferNode | null,
readonly index: number) {
super()
this.type = context.buffer.set.types[context.buffer.buffer[index]]
}