@lezer/common 0.15.11 → 0.15.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tree.cjs DELETED
@@ -1,1156 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- // FIXME profile adding a per-Tree TreeNode cache, validating it by
6
- // parent pointer
7
- /// The default maximum length of a `TreeBuffer` node (1024).
8
- const DefaultBufferLength = 1024;
9
- let nextPropID = 0;
10
- class Range {
11
- constructor(from, to) {
12
- this.from = from;
13
- this.to = to;
14
- }
15
- }
16
- /// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
17
- /// can have metadata associated with it in props. Instances of this
18
- /// class represent prop names.
19
- class NodeProp {
20
- /// Create a new node prop type.
21
- constructor(config = {}) {
22
- this.id = nextPropID++;
23
- this.perNode = !!config.perNode;
24
- this.deserialize = config.deserialize || (() => {
25
- throw new Error("This node type doesn't define a deserialize function");
26
- });
27
- }
28
- /// This is meant to be used with
29
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
30
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
31
- /// prop values for each node type in the set. Takes a [match
32
- /// object](#common.NodeType^match) or function that returns undefined
33
- /// if the node type doesn't get this prop, and the prop's value if
34
- /// it does.
35
- add(match) {
36
- if (this.perNode)
37
- throw new RangeError("Can't add per-node props to node types");
38
- if (typeof match != "function")
39
- match = NodeType.match(match);
40
- return (type) => {
41
- let result = match(type);
42
- return result === undefined ? null : [this, result];
43
- };
44
- }
45
- }
46
- /// Prop that is used to describe matching delimiters. For opening
47
- /// delimiters, this holds an array of node names (written as a
48
- /// space-separated string when declaring this prop in a grammar)
49
- /// for the node types of closing delimiters that match it.
50
- NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
51
- /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
52
- /// attached to closing delimiters, holding an array of node names
53
- /// of types of matching opening delimiters.
54
- NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
55
- /// Used to assign node types to groups (for example, all node
56
- /// types that represent an expression could be tagged with an
57
- /// `"Expression"` group).
58
- NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
59
- /// The hash of the [context](#lr.ContextTracker.constructor)
60
- /// that the node was parsed in, if any. Used to limit reuse of
61
- /// contextual nodes.
62
- NodeProp.contextHash = new NodeProp({ perNode: true });
63
- /// The distance beyond the end of the node that the tokenizer
64
- /// looked ahead for any of the tokens inside the node. (The LR
65
- /// parser only stores this when it is larger than 25, for
66
- /// efficiency reasons.)
67
- NodeProp.lookAhead = new NodeProp({ perNode: true });
68
- /// This per-node prop is used to replace a given node, or part of a
69
- /// node, with another tree. This is useful to include trees from
70
- /// different languages.
71
- NodeProp.mounted = new NodeProp({ perNode: true });
72
- /// A mounted tree, which can be [stored](#common.NodeProp^mounted) on
73
- /// a tree node to indicate that parts of its content are
74
- /// represented by another tree.
75
- class MountedTree {
76
- constructor(
77
- /// The inner tree.
78
- tree,
79
- /// If this is null, this tree replaces the entire node (it will
80
- /// be included in the regular iteration instead of its host
81
- /// node). If not, only the given ranges are considered to be
82
- /// covered by this tree. This is used for trees that are mixed in
83
- /// a way that isn't strictly hierarchical. Such mounted trees are
84
- /// only entered by [`resolveInner`](#common.Tree.resolveInner)
85
- /// and [`enter`](#common.SyntaxNode.enter).
86
- overlay,
87
- /// The parser used to create this subtree.
88
- parser) {
89
- this.tree = tree;
90
- this.overlay = overlay;
91
- this.parser = parser;
92
- }
93
- }
94
- const noProps = Object.create(null);
95
- /// Each node in a syntax tree has a node type associated with it.
96
- class NodeType {
97
- /// @internal
98
- constructor(
99
- /// The name of the node type. Not necessarily unique, but if the
100
- /// grammar was written properly, different node types with the
101
- /// same name within a node set should play the same semantic
102
- /// role.
103
- name,
104
- /// @internal
105
- props,
106
- /// The id of this node in its set. Corresponds to the term ids
107
- /// used in the parser.
108
- id,
109
- /// @internal
110
- flags = 0) {
111
- this.name = name;
112
- this.props = props;
113
- this.id = id;
114
- this.flags = flags;
115
- }
116
- static define(spec) {
117
- let props = spec.props && spec.props.length ? Object.create(null) : noProps;
118
- let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) |
119
- (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0);
120
- let type = new NodeType(spec.name || "", props, spec.id, flags);
121
- if (spec.props)
122
- for (let src of spec.props) {
123
- if (!Array.isArray(src))
124
- src = src(type);
125
- if (src) {
126
- if (src[0].perNode)
127
- throw new RangeError("Can't store a per-node prop on a node type");
128
- props[src[0].id] = src[1];
129
- }
130
- }
131
- return type;
132
- }
133
- /// Retrieves a node prop for this type. Will return `undefined` if
134
- /// the prop isn't present on this node.
135
- prop(prop) { return this.props[prop.id]; }
136
- /// True when this is the top node of a grammar.
137
- get isTop() { return (this.flags & 1 /* Top */) > 0; }
138
- /// True when this node is produced by a skip rule.
139
- get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; }
140
- /// Indicates whether this is an error node.
141
- get isError() { return (this.flags & 4 /* Error */) > 0; }
142
- /// When true, this node type doesn't correspond to a user-declared
143
- /// named node, for example because it is used to cache repetition.
144
- get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; }
145
- /// Returns true when this node's name or one of its
146
- /// [groups](#common.NodeProp^group) matches the given string.
147
- is(name) {
148
- if (typeof name == 'string') {
149
- if (this.name == name)
150
- return true;
151
- let group = this.prop(NodeProp.group);
152
- return group ? group.indexOf(name) > -1 : false;
153
- }
154
- return this.id == name;
155
- }
156
- /// Create a function from node types to arbitrary values by
157
- /// specifying an object whose property names are node or
158
- /// [group](#common.NodeProp^group) names. Often useful with
159
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
160
- /// names, separated by spaces, in a single property name to map
161
- /// multiple node names to a single value.
162
- static match(map) {
163
- let direct = Object.create(null);
164
- for (let prop in map)
165
- for (let name of prop.split(" "))
166
- direct[name] = map[prop];
167
- return (node) => {
168
- for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
169
- let found = direct[i < 0 ? node.name : groups[i]];
170
- if (found)
171
- return found;
172
- }
173
- };
174
- }
175
- }
176
- /// An empty dummy node type to use when no actual type is available.
177
- NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */);
178
- /// A node set holds a collection of node types. It is used to
179
- /// compactly represent trees by storing their type ids, rather than a
180
- /// full pointer to the type object, in a numeric array. Each parser
181
- /// [has](#lr.LRParser.nodeSet) a node set, and [tree
182
- /// buffers](#common.TreeBuffer) can only store collections of nodes
183
- /// from the same set. A set can have a maximum of 2**16 (65536) node
184
- /// types in it, so that the ids fit into 16-bit typed array slots.
185
- class NodeSet {
186
- /// Create a set with the given types. The `id` property of each
187
- /// type should correspond to its position within the array.
188
- constructor(
189
- /// The node types in this set, by id.
190
- types) {
191
- this.types = types;
192
- for (let i = 0; i < types.length; i++)
193
- if (types[i].id != i)
194
- throw new RangeError("Node type ids should correspond to array positions when creating a node set");
195
- }
196
- /// Create a copy of this set with some node properties added. The
197
- /// arguments to this method should be created with
198
- /// [`NodeProp.add`](#common.NodeProp.add).
199
- extend(...props) {
200
- let newTypes = [];
201
- for (let type of this.types) {
202
- let newProps = null;
203
- for (let source of props) {
204
- let add = source(type);
205
- if (add) {
206
- if (!newProps)
207
- newProps = Object.assign({}, type.props);
208
- newProps[add[0].id] = add[1];
209
- }
210
- }
211
- newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
212
- }
213
- return new NodeSet(newTypes);
214
- }
215
- }
216
- const CachedNode = new WeakMap();
217
- /// A piece of syntax tree. There are two ways to approach these
218
- /// trees: the way they are actually stored in memory, and the
219
- /// convenient way.
220
- ///
221
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
222
- /// objects. By packing detail information into `TreeBuffer` leaf
223
- /// nodes, the representation is made a lot more memory-efficient.
224
- ///
225
- /// However, when you want to actually work with tree nodes, this
226
- /// representation is very awkward, so most client code will want to
227
- /// use the [`TreeCursor`](#common.TreeCursor) or
228
- /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
229
- /// a view on some part of this data structure, and can be used to
230
- /// move around to adjacent nodes.
231
- class Tree {
232
- /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
233
- constructor(
234
- /// The type of the top node.
235
- type,
236
- /// This node's child nodes.
237
- children,
238
- /// The positions (offsets relative to the start of this tree) of
239
- /// the children.
240
- positions,
241
- /// The total length of this tree
242
- length,
243
- /// Per-node [node props](#common.NodeProp) to associate with this node.
244
- props) {
245
- this.type = type;
246
- this.children = children;
247
- this.positions = positions;
248
- this.length = length;
249
- /// @internal
250
- this.props = null;
251
- if (props && props.length) {
252
- this.props = Object.create(null);
253
- for (let [prop, value] of props)
254
- this.props[typeof prop == "number" ? prop : prop.id] = value;
255
- }
256
- }
257
- /// @internal
258
- toString() {
259
- let mounted = this.prop(NodeProp.mounted);
260
- if (mounted && !mounted.overlay)
261
- return mounted.tree.toString();
262
- let children = "";
263
- for (let ch of this.children) {
264
- let str = ch.toString();
265
- if (str) {
266
- if (children)
267
- children += ",";
268
- children += str;
269
- }
270
- }
271
- return !this.type.name ? children :
272
- (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
273
- (children.length ? "(" + children + ")" : "");
274
- }
275
- /// Get a [tree cursor](#common.TreeCursor) rooted at this tree. When
276
- /// `pos` is given, the cursor is [moved](#common.TreeCursor.moveTo)
277
- /// to the given position and side.
278
- cursor(pos, side = 0) {
279
- let scope = (pos != null && CachedNode.get(this)) || this.topNode;
280
- let cursor = new TreeCursor(scope);
281
- if (pos != null) {
282
- cursor.moveTo(pos, side);
283
- CachedNode.set(this, cursor._tree);
284
- }
285
- return cursor;
286
- }
287
- /// Get a [tree cursor](#common.TreeCursor) that, unlike regular
288
- /// cursors, doesn't skip through
289
- /// [anonymous](#common.NodeType.isAnonymous) nodes and doesn't
290
- /// automatically enter mounted nodes.
291
- fullCursor() {
292
- return new TreeCursor(this.topNode, 1 /* Full */);
293
- }
294
- /// Get a [syntax node](#common.SyntaxNode) object for the top of the
295
- /// tree.
296
- get topNode() {
297
- return new TreeNode(this, 0, 0, null);
298
- }
299
- /// Get the [syntax node](#common.SyntaxNode) at the given position.
300
- /// If `side` is -1, this will move into nodes that end at the
301
- /// position. If 1, it'll move into nodes that start at the
302
- /// position. With 0, it'll only enter nodes that cover the position
303
- /// from both sides.
304
- resolve(pos, side = 0) {
305
- return this.cursor(pos, side).node;
306
- }
307
- /// Like [`resolve`](#common.Tree.resolve), but will enter
308
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
309
- /// pointing into the innermost overlaid tree at the given position
310
- /// (with parent links going through all parent structure, including
311
- /// the host trees).
312
- resolveInner(pos, side = 0) {
313
- let result = this.topNode;
314
- for (;;) {
315
- let inner = result.enter(pos, side);
316
- if (!inner)
317
- return result;
318
- result = inner;
319
- }
320
- }
321
- /// Iterate over the tree and its children, calling `enter` for any
322
- /// node that touches the `from`/`to` region (if given) before
323
- /// running over such a node's children, and `leave` (if given) when
324
- /// leaving the node. When `enter` returns `false`, that node will
325
- /// not have its children iterated over (or `leave` called).
326
- iterate(spec) {
327
- let { enter, leave, from = 0, to = this.length } = spec;
328
- for (let c = this.cursor(), get = () => c.node;;) {
329
- let mustLeave = false;
330
- if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c.type, c.from, c.to, get) !== false)) {
331
- if (c.firstChild())
332
- continue;
333
- if (!c.type.isAnonymous)
334
- mustLeave = true;
335
- }
336
- for (;;) {
337
- if (mustLeave && leave)
338
- leave(c.type, c.from, c.to, get);
339
- mustLeave = c.type.isAnonymous;
340
- if (c.nextSibling())
341
- break;
342
- if (!c.parent())
343
- return;
344
- mustLeave = true;
345
- }
346
- }
347
- }
348
- /// Get the value of the given [node prop](#common.NodeProp) for this
349
- /// node. Works with both per-node and per-type props.
350
- prop(prop) {
351
- return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
352
- }
353
- /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
354
- /// format that can be passed to the [`Tree`](#common.Tree)
355
- /// constructor.
356
- get propValues() {
357
- let result = [];
358
- if (this.props)
359
- for (let id in this.props)
360
- result.push([+id, this.props[id]]);
361
- return result;
362
- }
363
- /// Balance the direct children of this tree, producing a copy of
364
- /// which may have children grouped into subtrees with type
365
- /// [`NodeType.none`](#common.NodeType^none).
366
- balance(config = {}) {
367
- return this.children.length <= 8 /* BranchFactor */ ? this :
368
- 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)));
369
- }
370
- /// Build a tree from a postfix-ordered buffer of node information,
371
- /// or a cursor over such a buffer.
372
- static build(data) { return buildTree(data); }
373
- }
374
- /// The empty tree
375
- Tree.empty = new Tree(NodeType.none, [], [], 0);
376
- class FlatBufferCursor {
377
- constructor(buffer, index) {
378
- this.buffer = buffer;
379
- this.index = index;
380
- }
381
- get id() { return this.buffer[this.index - 4]; }
382
- get start() { return this.buffer[this.index - 3]; }
383
- get end() { return this.buffer[this.index - 2]; }
384
- get size() { return this.buffer[this.index - 1]; }
385
- get pos() { return this.index; }
386
- next() { this.index -= 4; }
387
- fork() { return new FlatBufferCursor(this.buffer, this.index); }
388
- }
389
- /// Tree buffers contain (type, start, end, endIndex) quads for each
390
- /// node. In such a buffer, nodes are stored in prefix order (parents
391
- /// before children, with the endIndex of the parent indicating which
392
- /// children belong to it)
393
- class TreeBuffer {
394
- /// Create a tree buffer.
395
- constructor(
396
- /// The buffer's content.
397
- buffer,
398
- /// The total length of the group of nodes in the buffer.
399
- length,
400
- /// The node set used in this buffer.
401
- set) {
402
- this.buffer = buffer;
403
- this.length = length;
404
- this.set = set;
405
- }
406
- /// @internal
407
- get type() { return NodeType.none; }
408
- /// @internal
409
- toString() {
410
- let result = [];
411
- for (let index = 0; index < this.buffer.length;) {
412
- result.push(this.childString(index));
413
- index = this.buffer[index + 3];
414
- }
415
- return result.join(",");
416
- }
417
- /// @internal
418
- childString(index) {
419
- let id = this.buffer[index], endIndex = this.buffer[index + 3];
420
- let type = this.set.types[id], result = type.name;
421
- if (/\W/.test(result) && !type.isError)
422
- result = JSON.stringify(result);
423
- index += 4;
424
- if (endIndex == index)
425
- return result;
426
- let children = [];
427
- while (index < endIndex) {
428
- children.push(this.childString(index));
429
- index = this.buffer[index + 3];
430
- }
431
- return result + "(" + children.join(",") + ")";
432
- }
433
- /// @internal
434
- findChild(startIndex, endIndex, dir, pos, side) {
435
- let { buffer } = this, pick = -1;
436
- for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
437
- if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
438
- pick = i;
439
- if (dir > 0)
440
- break;
441
- }
442
- }
443
- return pick;
444
- }
445
- /// @internal
446
- slice(startI, endI, from, to) {
447
- let b = this.buffer;
448
- let copy = new Uint16Array(endI - startI);
449
- for (let i = startI, j = 0; i < endI;) {
450
- copy[j++] = b[i++];
451
- copy[j++] = b[i++] - from;
452
- copy[j++] = b[i++] - from;
453
- copy[j++] = b[i++] - startI;
454
- }
455
- return new TreeBuffer(copy, to - from, this.set);
456
- }
457
- }
458
- function checkSide(side, pos, from, to) {
459
- switch (side) {
460
- case -2 /* Before */: return from < pos;
461
- case -1 /* AtOrBefore */: return to >= pos && from < pos;
462
- case 0 /* Around */: return from < pos && to > pos;
463
- case 1 /* AtOrAfter */: return from <= pos && to > pos;
464
- case 2 /* After */: return to > pos;
465
- case 4 /* DontCare */: return true;
466
- }
467
- }
468
- function enterUnfinishedNodesBefore(node, pos) {
469
- let scan = node.childBefore(pos);
470
- while (scan) {
471
- let last = scan.lastChild;
472
- if (!last || last.to != scan.to)
473
- break;
474
- if (last.type.isError && last.from == last.to) {
475
- node = scan;
476
- scan = last.prevSibling;
477
- }
478
- else {
479
- scan = last;
480
- }
481
- }
482
- return node;
483
- }
484
- class TreeNode {
485
- constructor(node, _from,
486
- // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
487
- index, _parent) {
488
- this.node = node;
489
- this._from = _from;
490
- this.index = index;
491
- this._parent = _parent;
492
- }
493
- get type() { return this.node.type; }
494
- get name() { return this.node.type.name; }
495
- get from() { return this._from; }
496
- get to() { return this._from + this.node.length; }
497
- nextChild(i, dir, pos, side, mode = 0) {
498
- for (let parent = this;;) {
499
- for (let { children, positions } = parent.node, e = dir > 0 ? children.length : -1; i != e; i += dir) {
500
- let next = children[i], start = positions[i] + parent._from;
501
- if (!checkSide(side, pos, start, start + next.length))
502
- continue;
503
- if (next instanceof TreeBuffer) {
504
- if (mode & 2 /* NoEnterBuffer */)
505
- continue;
506
- let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
507
- if (index > -1)
508
- return new BufferNode(new BufferContext(parent, next, i, start), null, index);
509
- }
510
- else if ((mode & 1 /* Full */) || (!next.type.isAnonymous || hasChild(next))) {
511
- let mounted;
512
- if (!(mode & 1 /* Full */) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
513
- return new TreeNode(mounted.tree, start, i, parent);
514
- let inner = new TreeNode(next, start, i, parent);
515
- return (mode & 1 /* Full */) || !inner.type.isAnonymous ? inner
516
- : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
517
- }
518
- }
519
- if ((mode & 1 /* Full */) || !parent.type.isAnonymous)
520
- return null;
521
- if (parent.index >= 0)
522
- i = parent.index + dir;
523
- else
524
- i = dir < 0 ? -1 : parent._parent.node.children.length;
525
- parent = parent._parent;
526
- if (!parent)
527
- return null;
528
- }
529
- }
530
- get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); }
531
- get lastChild() { return this.nextChild(this.node.children.length - 1, -1, 0, 4 /* DontCare */); }
532
- childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); }
533
- childBefore(pos) { return this.nextChild(this.node.children.length - 1, -1, pos, -2 /* Before */); }
534
- enter(pos, side, overlays = true, buffers = true) {
535
- let mounted;
536
- if (overlays && (mounted = this.node.prop(NodeProp.mounted)) && mounted.overlay) {
537
- let rPos = pos - this.from;
538
- for (let { from, to } of mounted.overlay) {
539
- if ((side > 0 ? from <= rPos : from < rPos) &&
540
- (side < 0 ? to >= rPos : to > rPos))
541
- return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
542
- }
543
- }
544
- return this.nextChild(0, 1, pos, side, buffers ? 0 : 2 /* NoEnterBuffer */);
545
- }
546
- nextSignificantParent() {
547
- let val = this;
548
- while (val.type.isAnonymous && val._parent)
549
- val = val._parent;
550
- return val;
551
- }
552
- get parent() {
553
- return this._parent ? this._parent.nextSignificantParent() : null;
554
- }
555
- get nextSibling() {
556
- return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* DontCare */) : null;
557
- }
558
- get prevSibling() {
559
- return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null;
560
- }
561
- get cursor() { return new TreeCursor(this); }
562
- get tree() { return this.node; }
563
- toTree() { return this.node; }
564
- resolve(pos, side = 0) {
565
- return this.cursor.moveTo(pos, side).node;
566
- }
567
- enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }
568
- getChild(type, before = null, after = null) {
569
- let r = getChildren(this, type, before, after);
570
- return r.length ? r[0] : null;
571
- }
572
- getChildren(type, before = null, after = null) {
573
- return getChildren(this, type, before, after);
574
- }
575
- /// @internal
576
- toString() { return this.node.toString(); }
577
- }
578
- function getChildren(node, type, before, after) {
579
- let cur = node.cursor, result = [];
580
- if (!cur.firstChild())
581
- return result;
582
- if (before != null)
583
- while (!cur.type.is(before))
584
- if (!cur.nextSibling())
585
- return result;
586
- for (;;) {
587
- if (after != null && cur.type.is(after))
588
- return result;
589
- if (cur.type.is(type))
590
- result.push(cur.node);
591
- if (!cur.nextSibling())
592
- return after == null ? result : [];
593
- }
594
- }
595
- class BufferContext {
596
- constructor(parent, buffer, index, start) {
597
- this.parent = parent;
598
- this.buffer = buffer;
599
- this.index = index;
600
- this.start = start;
601
- }
602
- }
603
- class BufferNode {
604
- constructor(context, _parent, index) {
605
- this.context = context;
606
- this._parent = _parent;
607
- this.index = index;
608
- this.type = context.buffer.set.types[context.buffer.buffer[index]];
609
- }
610
- get name() { return this.type.name; }
611
- get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
612
- get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
613
- child(dir, pos, side) {
614
- let { buffer } = this.context;
615
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
616
- return index < 0 ? null : new BufferNode(this.context, this, index);
617
- }
618
- get firstChild() { return this.child(1, 0, 4 /* DontCare */); }
619
- get lastChild() { return this.child(-1, 0, 4 /* DontCare */); }
620
- childAfter(pos) { return this.child(1, pos, 2 /* After */); }
621
- childBefore(pos) { return this.child(-1, pos, -2 /* Before */); }
622
- enter(pos, side, overlays, buffers = true) {
623
- if (!buffers)
624
- return null;
625
- let { buffer } = this.context;
626
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
627
- return index < 0 ? null : new BufferNode(this.context, this, index);
628
- }
629
- get parent() {
630
- return this._parent || this.context.parent.nextSignificantParent();
631
- }
632
- externalSibling(dir) {
633
- return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */);
634
- }
635
- get nextSibling() {
636
- let { buffer } = this.context;
637
- let after = buffer.buffer[this.index + 3];
638
- if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
639
- return new BufferNode(this.context, this._parent, after);
640
- return this.externalSibling(1);
641
- }
642
- get prevSibling() {
643
- let { buffer } = this.context;
644
- let parentStart = this._parent ? this._parent.index + 4 : 0;
645
- if (this.index == parentStart)
646
- return this.externalSibling(-1);
647
- return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */));
648
- }
649
- get cursor() { return new TreeCursor(this); }
650
- get tree() { return null; }
651
- toTree() {
652
- let children = [], positions = [];
653
- let { buffer } = this.context;
654
- let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
655
- if (endI > startI) {
656
- let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2];
657
- children.push(buffer.slice(startI, endI, from, to));
658
- positions.push(0);
659
- }
660
- return new Tree(this.type, children, positions, this.to - this.from);
661
- }
662
- resolve(pos, side = 0) {
663
- return this.cursor.moveTo(pos, side).node;
664
- }
665
- enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }
666
- /// @internal
667
- toString() { return this.context.buffer.childString(this.index); }
668
- getChild(type, before = null, after = null) {
669
- let r = getChildren(this, type, before, after);
670
- return r.length ? r[0] : null;
671
- }
672
- getChildren(type, before = null, after = null) {
673
- return getChildren(this, type, before, after);
674
- }
675
- }
676
- /// A tree cursor object focuses on a given node in a syntax tree, and
677
- /// allows you to move to adjacent nodes.
678
- class TreeCursor {
679
- /// @internal
680
- constructor(node,
681
- /// @internal
682
- mode = 0) {
683
- this.mode = mode;
684
- this.buffer = null;
685
- this.stack = [];
686
- this.index = 0;
687
- this.bufferNode = null;
688
- if (node instanceof TreeNode) {
689
- this.yieldNode(node);
690
- }
691
- else {
692
- this._tree = node.context.parent;
693
- this.buffer = node.context;
694
- for (let n = node._parent; n; n = n._parent)
695
- this.stack.unshift(n.index);
696
- this.bufferNode = node;
697
- this.yieldBuf(node.index);
698
- }
699
- }
700
- /// Shorthand for `.type.name`.
701
- get name() { return this.type.name; }
702
- yieldNode(node) {
703
- if (!node)
704
- return false;
705
- this._tree = node;
706
- this.type = node.type;
707
- this.from = node.from;
708
- this.to = node.to;
709
- return true;
710
- }
711
- yieldBuf(index, type) {
712
- this.index = index;
713
- let { start, buffer } = this.buffer;
714
- this.type = type || buffer.set.types[buffer.buffer[index]];
715
- this.from = start + buffer.buffer[index + 1];
716
- this.to = start + buffer.buffer[index + 2];
717
- return true;
718
- }
719
- yield(node) {
720
- if (!node)
721
- return false;
722
- if (node instanceof TreeNode) {
723
- this.buffer = null;
724
- return this.yieldNode(node);
725
- }
726
- this.buffer = node.context;
727
- return this.yieldBuf(node.index, node.type);
728
- }
729
- /// @internal
730
- toString() {
731
- return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
732
- }
733
- /// @internal
734
- enterChild(dir, pos, side) {
735
- if (!this.buffer)
736
- return this.yield(this._tree.nextChild(dir < 0 ? this._tree.node.children.length - 1 : 0, dir, pos, side, this.mode));
737
- let { buffer } = this.buffer;
738
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
739
- if (index < 0)
740
- return false;
741
- this.stack.push(this.index);
742
- return this.yieldBuf(index);
743
- }
744
- /// Move the cursor to this node's first child. When this returns
745
- /// false, the node has no child, and the cursor has not been moved.
746
- firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); }
747
- /// Move the cursor to this node's last child.
748
- lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); }
749
- /// Move the cursor to the first child that ends after `pos`.
750
- childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); }
751
- /// Move to the last child that starts before `pos`.
752
- childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); }
753
- /// Move the cursor to the child around `pos`. If side is -1 the
754
- /// child may end at that position, when 1 it may start there. This
755
- /// will also enter [overlaid](#common.MountedTree.overlay)
756
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
757
- /// set to false.
758
- enter(pos, side, overlays = true, buffers = true) {
759
- if (!this.buffer)
760
- return this.yield(this._tree.enter(pos, side, overlays && !(this.mode & 1 /* Full */), buffers));
761
- return buffers ? this.enterChild(1, pos, side) : false;
762
- }
763
- /// Move to the node's parent node, if this isn't the top node.
764
- parent() {
765
- if (!this.buffer)
766
- return this.yieldNode((this.mode & 1 /* Full */) ? this._tree._parent : this._tree.parent);
767
- if (this.stack.length)
768
- return this.yieldBuf(this.stack.pop());
769
- let parent = (this.mode & 1 /* Full */) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
770
- this.buffer = null;
771
- return this.yieldNode(parent);
772
- }
773
- /// @internal
774
- sibling(dir) {
775
- if (!this.buffer)
776
- return !this._tree._parent ? false
777
- : this.yield(this._tree.index < 0 ? null
778
- : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode));
779
- let { buffer } = this.buffer, d = this.stack.length - 1;
780
- if (dir < 0) {
781
- let parentStart = d < 0 ? 0 : this.stack[d] + 4;
782
- if (this.index != parentStart)
783
- return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */));
784
- }
785
- else {
786
- let after = buffer.buffer[this.index + 3];
787
- if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
788
- return this.yieldBuf(after);
789
- }
790
- return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false;
791
- }
792
- /// Move to this node's next sibling, if any.
793
- nextSibling() { return this.sibling(1); }
794
- /// Move to this node's previous sibling, if any.
795
- prevSibling() { return this.sibling(-1); }
796
- atLastNode(dir) {
797
- let index, parent, { buffer } = this;
798
- if (buffer) {
799
- if (dir > 0) {
800
- if (this.index < buffer.buffer.buffer.length)
801
- return false;
802
- }
803
- else {
804
- for (let i = 0; i < this.index; i++)
805
- if (buffer.buffer.buffer[i + 3] < this.index)
806
- return false;
807
- }
808
- ({ index, parent } = buffer);
809
- }
810
- else {
811
- ({ index, _parent: parent } = this._tree);
812
- }
813
- for (; parent; { index, _parent: parent } = parent) {
814
- if (index > -1)
815
- for (let i = index + dir, e = dir < 0 ? -1 : parent.node.children.length; i != e; i += dir) {
816
- let child = parent.node.children[i];
817
- if ((this.mode & 1 /* Full */) || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
818
- return false;
819
- }
820
- }
821
- return true;
822
- }
823
- move(dir, enter) {
824
- if (enter && this.enterChild(dir, 0, 4 /* DontCare */))
825
- return true;
826
- for (;;) {
827
- if (this.sibling(dir))
828
- return true;
829
- if (this.atLastNode(dir) || !this.parent())
830
- return false;
831
- }
832
- }
833
- /// Move to the next node in a
834
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
835
- /// traversal, going from a node to its first child or, if the
836
- /// current node is empty or `enter` is false, its next sibling or
837
- /// the next sibling of the first parent node that has one.
838
- next(enter = true) { return this.move(1, enter); }
839
- /// Move to the next node in a last-to-first pre-order traveral. A
840
- /// node is followed by its last child or, if it has none, its
841
- /// previous sibling or the previous sibling of the first parent
842
- /// node that has one.
843
- prev(enter = true) { return this.move(-1, enter); }
844
- /// Move the cursor to the innermost node that covers `pos`. If
845
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
846
- /// it will enter nodes that start at `pos`.
847
- moveTo(pos, side = 0) {
848
- // Move up to a node that actually holds the position, if possible
849
- while (this.from == this.to ||
850
- (side < 1 ? this.from >= pos : this.from > pos) ||
851
- (side > -1 ? this.to <= pos : this.to < pos))
852
- if (!this.parent())
853
- break;
854
- // Then scan down into child nodes as far as possible
855
- while (this.enterChild(1, pos, side)) { }
856
- return this;
857
- }
858
- /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
859
- /// position.
860
- get node() {
861
- if (!this.buffer)
862
- return this._tree;
863
- let cache = this.bufferNode, result = null, depth = 0;
864
- if (cache && cache.context == this.buffer) {
865
- scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
866
- for (let c = cache; c; c = c._parent)
867
- if (c.index == index) {
868
- if (index == this.index)
869
- return c;
870
- result = c;
871
- depth = d + 1;
872
- break scan;
873
- }
874
- index = this.stack[--d];
875
- }
876
- }
877
- for (let i = depth; i < this.stack.length; i++)
878
- result = new BufferNode(this.buffer, result, this.stack[i]);
879
- return this.bufferNode = new BufferNode(this.buffer, result, this.index);
880
- }
881
- /// Get the [tree](#common.Tree) that represents the current node, if
882
- /// any. Will return null when the node is in a [tree
883
- /// buffer](#common.TreeBuffer).
884
- get tree() {
885
- return this.buffer ? null : this._tree.node;
886
- }
887
- }
888
- function hasChild(tree) {
889
- return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
890
- }
891
- function buildTree(data) {
892
- var _a;
893
- let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
894
- let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
895
- let types = nodeSet.types;
896
- let contextHash = 0, lookAhead = 0;
897
- function takeNode(parentStart, minPos, children, positions, inRepeat) {
898
- let { id, start, end, size } = cursor;
899
- let lookAheadAtStart = lookAhead;
900
- while (size < 0) {
901
- cursor.next();
902
- if (size == -1 /* Reuse */) {
903
- let node = reused[id];
904
- children.push(node);
905
- positions.push(start - parentStart);
906
- return;
907
- }
908
- else if (size == -3 /* ContextChange */) { // Context change
909
- contextHash = id;
910
- return;
911
- }
912
- else if (size == -4 /* LookAhead */) {
913
- lookAhead = id;
914
- return;
915
- }
916
- else {
917
- throw new RangeError(`Unrecognized record size: ${size}`);
918
- }
919
- }
920
- let type = types[id], node, buffer;
921
- let startPos = start - parentStart;
922
- if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
923
- // Small enough for a buffer, and no reused nodes inside
924
- let data = new Uint16Array(buffer.size - buffer.skip);
925
- let endPos = cursor.pos - buffer.size, index = data.length;
926
- while (cursor.pos > endPos)
927
- index = copyToBuffer(buffer.start, data, index);
928
- node = new TreeBuffer(data, end - buffer.start, nodeSet);
929
- startPos = buffer.start - parentStart;
930
- }
931
- else { // Make it a node
932
- let endPos = cursor.pos - size;
933
- cursor.next();
934
- let localChildren = [], localPositions = [];
935
- let localInRepeat = id >= minRepeatType ? id : -1;
936
- let lastGroup = 0, lastEnd = end;
937
- while (cursor.pos > endPos) {
938
- if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
939
- if (cursor.end <= lastEnd - maxBufferLength) {
940
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
941
- lastGroup = localChildren.length;
942
- lastEnd = cursor.end;
943
- }
944
- cursor.next();
945
- }
946
- else {
947
- takeNode(start, endPos, localChildren, localPositions, localInRepeat);
948
- }
949
- }
950
- if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
951
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
952
- localChildren.reverse();
953
- localPositions.reverse();
954
- if (localInRepeat > -1 && lastGroup > 0) {
955
- let make = makeBalanced(type);
956
- node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
957
- }
958
- else {
959
- node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
960
- }
961
- }
962
- children.push(node);
963
- positions.push(startPos);
964
- }
965
- function makeBalanced(type) {
966
- return (children, positions, length) => {
967
- let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
968
- if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
969
- if (!lastI && last.type == type && last.length == length)
970
- return last;
971
- if (lookAheadProp = last.prop(NodeProp.lookAhead))
972
- lookAhead = positions[lastI] + last.length + lookAheadProp;
973
- }
974
- return makeTree(type, children, positions, length, lookAhead);
975
- };
976
- }
977
- function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {
978
- let localChildren = [], localPositions = [];
979
- while (children.length > i) {
980
- localChildren.push(children.pop());
981
- localPositions.push(positions.pop() + base - from);
982
- }
983
- children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));
984
- positions.push(from - base);
985
- }
986
- function makeTree(type, children, positions, length, lookAhead = 0, props) {
987
- if (contextHash) {
988
- let pair = [NodeProp.contextHash, contextHash];
989
- props = props ? [pair].concat(props) : [pair];
990
- }
991
- if (lookAhead > 25) {
992
- let pair = [NodeProp.lookAhead, lookAhead];
993
- props = props ? [pair].concat(props) : [pair];
994
- }
995
- return new Tree(type, children, positions, length, props);
996
- }
997
- function findBufferSize(maxSize, inRepeat) {
998
- // Scan through the buffer to find previous siblings that fit
999
- // together in a TreeBuffer, and don't contain any reused nodes
1000
- // (which can't be stored in a buffer).
1001
- // If `inRepeat` is > -1, ignore node boundaries of that type for
1002
- // nesting, but make sure the end falls either at the start
1003
- // (`maxSize`) or before such a node.
1004
- let fork = cursor.fork();
1005
- let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1006
- let result = { size: 0, start: 0, skip: 0 };
1007
- scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
1008
- let nodeSize = fork.size;
1009
- // Pretend nested repeat nodes of the same type don't exist
1010
- if (fork.id == inRepeat && nodeSize >= 0) {
1011
- // Except that we store the current state as a valid return
1012
- // value.
1013
- result.size = size;
1014
- result.start = start;
1015
- result.skip = skip;
1016
- skip += 4;
1017
- size += 4;
1018
- fork.next();
1019
- continue;
1020
- }
1021
- let startPos = fork.pos - nodeSize;
1022
- if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
1023
- break;
1024
- let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1025
- let nodeStart = fork.start;
1026
- fork.next();
1027
- while (fork.pos > startPos) {
1028
- if (fork.size < 0) {
1029
- if (fork.size == -3 /* ContextChange */)
1030
- localSkipped += 4;
1031
- else
1032
- break scan;
1033
- }
1034
- else if (fork.id >= minRepeatType) {
1035
- localSkipped += 4;
1036
- }
1037
- fork.next();
1038
- }
1039
- start = nodeStart;
1040
- size += nodeSize;
1041
- skip += localSkipped;
1042
- }
1043
- if (inRepeat < 0 || size == maxSize) {
1044
- result.size = size;
1045
- result.start = start;
1046
- result.skip = skip;
1047
- }
1048
- return result.size > 4 ? result : undefined;
1049
- }
1050
- function copyToBuffer(bufferStart, buffer, index) {
1051
- let { id, start, end, size } = cursor;
1052
- cursor.next();
1053
- if (size >= 0 && id < minRepeatType) {
1054
- let startIndex = index;
1055
- if (size > 4) {
1056
- let endPos = cursor.pos - (size - 4);
1057
- while (cursor.pos > endPos)
1058
- index = copyToBuffer(bufferStart, buffer, index);
1059
- }
1060
- buffer[--index] = startIndex;
1061
- buffer[--index] = end - bufferStart;
1062
- buffer[--index] = start - bufferStart;
1063
- buffer[--index] = id;
1064
- }
1065
- else if (size == -3 /* ContextChange */) {
1066
- contextHash = id;
1067
- }
1068
- else if (size == -4 /* LookAhead */) {
1069
- lookAhead = id;
1070
- }
1071
- return index;
1072
- }
1073
- let children = [], positions = [];
1074
- while (cursor.pos > 0)
1075
- takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1076
- let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
1077
- return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1078
- }
1079
- const nodeSizeCache = new WeakMap;
1080
- function nodeSize(balanceType, node) {
1081
- if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1082
- return 1;
1083
- let size = nodeSizeCache.get(node);
1084
- if (size == null) {
1085
- size = 1;
1086
- for (let child of node.children) {
1087
- if (child.type != balanceType || !(child instanceof Tree)) {
1088
- size = 1;
1089
- break;
1090
- }
1091
- size += nodeSize(balanceType, child);
1092
- }
1093
- nodeSizeCache.set(node, size);
1094
- }
1095
- return size;
1096
- }
1097
- function balanceRange(
1098
- // The type the balanced tree's inner nodes.
1099
- balanceType,
1100
- // The direct children and their positions
1101
- children, positions,
1102
- // The index range in children/positions to use
1103
- from, to,
1104
- // The start position of the nodes, relative to their parent.
1105
- start,
1106
- // Length of the outer node
1107
- length,
1108
- // Function to build the top node of the balanced tree
1109
- mkTop,
1110
- // Function to build internal nodes for the balanced tree
1111
- mkTree) {
1112
- let total = 0;
1113
- for (let i = from; i < to; i++)
1114
- total += nodeSize(balanceType, children[i]);
1115
- let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */);
1116
- let localChildren = [], localPositions = [];
1117
- function divide(children, positions, from, to, offset) {
1118
- for (let i = from; i < to;) {
1119
- let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
1120
- i++;
1121
- for (; i < to; i++) {
1122
- let nextSize = nodeSize(balanceType, children[i]);
1123
- if (groupSize + nextSize >= maxChild)
1124
- break;
1125
- groupSize += nextSize;
1126
- }
1127
- if (i == groupFrom + 1) {
1128
- if (groupSize > maxChild) {
1129
- let only = children[groupFrom]; // Only trees can have a size > 1
1130
- divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
1131
- continue;
1132
- }
1133
- localChildren.push(children[groupFrom]);
1134
- }
1135
- else {
1136
- let length = positions[i - 1] + children[i - 1].length - groupStart;
1137
- localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
1138
- }
1139
- localPositions.push(groupStart + offset - start);
1140
- }
1141
- }
1142
- divide(children, positions, from, to, 0);
1143
- return (mkTop || mkTree)(localChildren, localPositions, length);
1144
- }
1145
-
1146
- exports.DefaultBufferLength = DefaultBufferLength;
1147
- exports.MountedTree = MountedTree;
1148
- exports.NodeProp = NodeProp;
1149
- exports.NodeSet = NodeSet;
1150
- exports.NodeType = NodeType;
1151
- exports.Range = Range;
1152
- exports.Tree = Tree;
1153
- exports.TreeBuffer = TreeBuffer;
1154
- exports.TreeCursor = TreeCursor;
1155
- exports.TreeNode = TreeNode;
1156
- //# sourceMappingURL=tree.cjs.map