@lezer/common 0.15.9 → 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,1019 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- /// The default maximum length of a `TreeBuffer` node.
6
- const DefaultBufferLength = 1024;
7
- let nextPropID = 0;
8
- const CachedNode = new WeakMap();
9
- /// Each [node type](#tree.NodeType) can have metadata associated with
10
- /// it in props. Instances of this class represent prop names.
11
- class NodeProp {
12
- /// Create a new node prop type. You can optionally pass a
13
- /// `deserialize` function.
14
- constructor({ deserialize } = {}) {
15
- this.id = nextPropID++;
16
- this.deserialize = deserialize || (() => {
17
- throw new Error("This node type doesn't define a deserialize function");
18
- });
19
- }
20
- /// Create a string-valued node prop whose deserialize function is
21
- /// the identity function.
22
- static string() { return new NodeProp({ deserialize: str => str }); }
23
- /// Create a number-valued node prop whose deserialize function is
24
- /// just `Number`.
25
- static number() { return new NodeProp({ deserialize: Number }); }
26
- /// Creates a boolean-valued node prop whose deserialize function
27
- /// returns true for any input.
28
- static flag() { return new NodeProp({ deserialize: () => true }); }
29
- /// Store a value for this prop in the given object. This can be
30
- /// useful when building up a prop object to pass to the
31
- /// [`NodeType`](#tree.NodeType) constructor. Returns its first
32
- /// argument.
33
- set(propObj, value) {
34
- propObj[this.id] = value;
35
- return propObj;
36
- }
37
- /// This is meant to be used with
38
- /// [`NodeSet.extend`](#tree.NodeSet.extend) or
39
- /// [`Parser.withProps`](#lezer.Parser.withProps) to compute prop
40
- /// values for each node type in the set. Takes a [match
41
- /// object](#tree.NodeType^match) or function that returns undefined
42
- /// if the node type doesn't get this prop, and the prop's value if
43
- /// it does.
44
- add(match) {
45
- if (typeof match != "function")
46
- match = NodeType.match(match);
47
- return (type) => {
48
- let result = match(type);
49
- return result === undefined ? null : [this, result];
50
- };
51
- }
52
- }
53
- /// Prop that is used to describe matching delimiters. For opening
54
- /// delimiters, this holds an array of node names (written as a
55
- /// space-separated string when declaring this prop in a grammar)
56
- /// for the node types of closing delimiters that match it.
57
- NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
58
- /// The inverse of [`closedBy`](#tree.NodeProp^closedBy). This is
59
- /// attached to closing delimiters, holding an array of node names
60
- /// of types of matching opening delimiters.
61
- NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
62
- /// Used to assign node types to groups (for example, all node
63
- /// types that represent an expression could be tagged with an
64
- /// `"Expression"` group).
65
- NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
66
- const noProps = Object.create(null);
67
- /// Each node in a syntax tree has a node type associated with it.
68
- class NodeType {
69
- /// @internal
70
- constructor(
71
- /// The name of the node type. Not necessarily unique, but if the
72
- /// grammar was written properly, different node types with the
73
- /// same name within a node set should play the same semantic
74
- /// role.
75
- name,
76
- /// @internal
77
- props,
78
- /// The id of this node in its set. Corresponds to the term ids
79
- /// used in the parser.
80
- id,
81
- /// @internal
82
- flags = 0) {
83
- this.name = name;
84
- this.props = props;
85
- this.id = id;
86
- this.flags = flags;
87
- }
88
- static define(spec) {
89
- let props = spec.props && spec.props.length ? Object.create(null) : noProps;
90
- let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) |
91
- (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0);
92
- let type = new NodeType(spec.name || "", props, spec.id, flags);
93
- if (spec.props)
94
- for (let src of spec.props) {
95
- if (!Array.isArray(src))
96
- src = src(type);
97
- if (src)
98
- src[0].set(props, src[1]);
99
- }
100
- return type;
101
- }
102
- /// Retrieves a node prop for this type. Will return `undefined` if
103
- /// the prop isn't present on this node.
104
- prop(prop) { return this.props[prop.id]; }
105
- /// True when this is the top node of a grammar.
106
- get isTop() { return (this.flags & 1 /* Top */) > 0; }
107
- /// True when this node is produced by a skip rule.
108
- get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; }
109
- /// Indicates whether this is an error node.
110
- get isError() { return (this.flags & 4 /* Error */) > 0; }
111
- /// When true, this node type doesn't correspond to a user-declared
112
- /// named node, for example because it is used to cache repetition.
113
- get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; }
114
- /// Returns true when this node's name or one of its
115
- /// [groups](#tree.NodeProp^group) matches the given string.
116
- is(name) {
117
- if (typeof name == 'string') {
118
- if (this.name == name)
119
- return true;
120
- let group = this.prop(NodeProp.group);
121
- return group ? group.indexOf(name) > -1 : false;
122
- }
123
- return this.id == name;
124
- }
125
- /// Create a function from node types to arbitrary values by
126
- /// specifying an object whose property names are node or
127
- /// [group](#tree.NodeProp^group) names. Often useful with
128
- /// [`NodeProp.add`](#tree.NodeProp.add). You can put multiple
129
- /// names, separated by spaces, in a single property name to map
130
- /// multiple node names to a single value.
131
- static match(map) {
132
- let direct = Object.create(null);
133
- for (let prop in map)
134
- for (let name of prop.split(" "))
135
- direct[name] = map[prop];
136
- return (node) => {
137
- for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
138
- let found = direct[i < 0 ? node.name : groups[i]];
139
- if (found)
140
- return found;
141
- }
142
- };
143
- }
144
- }
145
- /// An empty dummy node type to use when no actual type is available.
146
- NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */);
147
- /// A node set holds a collection of node types. It is used to
148
- /// compactly represent trees by storing their type ids, rather than a
149
- /// full pointer to the type object, in a number array. Each parser
150
- /// [has](#lezer.Parser.nodeSet) a node set, and [tree
151
- /// buffers](#tree.TreeBuffer) can only store collections of nodes
152
- /// from the same set. A set can have a maximum of 2**16 (65536)
153
- /// node types in it, so that the ids fit into 16-bit typed array
154
- /// slots.
155
- class NodeSet {
156
- /// Create a set with the given types. The `id` property of each
157
- /// type should correspond to its position within the array.
158
- constructor(
159
- /// The node types in this set, by id.
160
- types) {
161
- this.types = types;
162
- for (let i = 0; i < types.length; i++)
163
- if (types[i].id != i)
164
- throw new RangeError("Node type ids should correspond to array positions when creating a node set");
165
- }
166
- /// Create a copy of this set with some node properties added. The
167
- /// arguments to this method should be created with
168
- /// [`NodeProp.add`](#tree.NodeProp.add).
169
- extend(...props) {
170
- let newTypes = [];
171
- for (let type of this.types) {
172
- let newProps = null;
173
- for (let source of props) {
174
- let add = source(type);
175
- if (add) {
176
- if (!newProps)
177
- newProps = Object.assign({}, type.props);
178
- add[0].set(newProps, add[1]);
179
- }
180
- }
181
- newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
182
- }
183
- return new NodeSet(newTypes);
184
- }
185
- }
186
- /// A piece of syntax tree. There are two ways to approach these
187
- /// trees: the way they are actually stored in memory, and the
188
- /// convenient way.
189
- ///
190
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
191
- /// objects. By packing detail information into `TreeBuffer` leaf
192
- /// nodes, the representation is made a lot more memory-efficient.
193
- ///
194
- /// However, when you want to actually work with tree nodes, this
195
- /// representation is very awkward, so most client code will want to
196
- /// use the `TreeCursor` interface instead, which provides a view on
197
- /// some part of this data structure, and can be used to move around
198
- /// to adjacent nodes.
199
- class Tree {
200
- /// Construct a new tree. You usually want to go through
201
- /// [`Tree.build`](#tree.Tree^build) instead.
202
- constructor(type,
203
- /// The tree's child nodes. Children small enough to fit in a
204
- /// `TreeBuffer will be represented as such, other children can be
205
- /// further `Tree` instances with their own internal structure.
206
- children,
207
- /// The positions (offsets relative to the start of this tree) of
208
- /// the children.
209
- positions,
210
- /// The total length of this tree
211
- length) {
212
- this.type = type;
213
- this.children = children;
214
- this.positions = positions;
215
- this.length = length;
216
- }
217
- /// @internal
218
- toString() {
219
- let children = this.children.map(c => c.toString()).join();
220
- return !this.type.name ? children :
221
- (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
222
- (children.length ? "(" + children + ")" : "");
223
- }
224
- /// Get a [tree cursor](#tree.TreeCursor) rooted at this tree. When
225
- /// `pos` is given, the cursor is [moved](#tree.TreeCursor.moveTo)
226
- /// to the given position and side.
227
- cursor(pos, side = 0) {
228
- let scope = (pos != null && CachedNode.get(this)) || this.topNode;
229
- let cursor = new TreeCursor(scope);
230
- if (pos != null) {
231
- cursor.moveTo(pos, side);
232
- CachedNode.set(this, cursor._tree);
233
- }
234
- return cursor;
235
- }
236
- /// Get a [tree cursor](#tree.TreeCursor) that, unlike regular
237
- /// cursors, doesn't skip [anonymous](#tree.NodeType.isAnonymous)
238
- /// nodes.
239
- fullCursor() {
240
- return new TreeCursor(this.topNode, true);
241
- }
242
- /// Get a [syntax node](#tree.SyntaxNode) object for the top of the
243
- /// tree.
244
- get topNode() {
245
- return new TreeNode(this, 0, 0, null);
246
- }
247
- /// Get the [syntax node](#tree.SyntaxNode) at the given position.
248
- /// If `side` is -1, this will move into nodes that end at the
249
- /// position. If 1, it'll move into nodes that start at the
250
- /// position. With 0, it'll only enter nodes that cover the position
251
- /// from both sides.
252
- resolve(pos, side = 0) {
253
- return this.cursor(pos, side).node;
254
- }
255
- /// Iterate over the tree and its children, calling `enter` for any
256
- /// node that touches the `from`/`to` region (if given) before
257
- /// running over such a node's children, and `leave` (if given) when
258
- /// leaving the node. When `enter` returns `false`, the given node
259
- /// will not have its children iterated over (or `leave` called).
260
- iterate(spec) {
261
- let { enter, leave, from = 0, to = this.length } = spec;
262
- for (let c = this.cursor();;) {
263
- let mustLeave = false;
264
- if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c.type, c.from, c.to) !== false)) {
265
- if (c.firstChild())
266
- continue;
267
- if (!c.type.isAnonymous)
268
- mustLeave = true;
269
- }
270
- for (;;) {
271
- if (mustLeave && leave)
272
- leave(c.type, c.from, c.to);
273
- mustLeave = c.type.isAnonymous;
274
- if (c.nextSibling())
275
- break;
276
- if (!c.parent())
277
- return;
278
- mustLeave = true;
279
- }
280
- }
281
- }
282
- /// Balance the direct children of this tree.
283
- balance(maxBufferLength = DefaultBufferLength) {
284
- return this.children.length <= BalanceBranchFactor ? this
285
- : balanceRange(this.type, NodeType.none, this.children, this.positions, 0, this.children.length, 0, maxBufferLength, this.length, 0);
286
- }
287
- /// Build a tree from a postfix-ordered buffer of node information,
288
- /// or a cursor over such a buffer.
289
- static build(data) { return buildTree(data); }
290
- }
291
- /// The empty tree
292
- Tree.empty = new Tree(NodeType.none, [], [], 0);
293
- // For trees that need a context hash attached, we're using this
294
- // kludge which assigns an extra property directly after
295
- // initialization (creating a single new object shape).
296
- function withHash(tree, hash) {
297
- if (hash)
298
- tree.contextHash = hash;
299
- return tree;
300
- }
301
- /// Tree buffers contain (type, start, end, endIndex) quads for each
302
- /// node. In such a buffer, nodes are stored in prefix order (parents
303
- /// before children, with the endIndex of the parent indicating which
304
- /// children belong to it)
305
- class TreeBuffer {
306
- /// Create a tree buffer @internal
307
- constructor(
308
- /// @internal
309
- buffer,
310
- /// The total length of the group of nodes in the buffer.
311
- length,
312
- /// @internal
313
- set,
314
- /// An optional repeat node type associated with the buffer.
315
- type = NodeType.none) {
316
- this.buffer = buffer;
317
- this.length = length;
318
- this.set = set;
319
- this.type = type;
320
- }
321
- /// @internal
322
- toString() {
323
- let result = [];
324
- for (let index = 0; index < this.buffer.length;) {
325
- result.push(this.childString(index));
326
- index = this.buffer[index + 3];
327
- }
328
- return result.join(",");
329
- }
330
- /// @internal
331
- childString(index) {
332
- let id = this.buffer[index], endIndex = this.buffer[index + 3];
333
- let type = this.set.types[id], result = type.name;
334
- if (/\W/.test(result) && !type.isError)
335
- result = JSON.stringify(result);
336
- index += 4;
337
- if (endIndex == index)
338
- return result;
339
- let children = [];
340
- while (index < endIndex) {
341
- children.push(this.childString(index));
342
- index = this.buffer[index + 3];
343
- }
344
- return result + "(" + children.join(",") + ")";
345
- }
346
- /// @internal
347
- findChild(startIndex, endIndex, dir, after) {
348
- let { buffer } = this, pick = -1;
349
- for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
350
- if (after != -100000000 /* None */) {
351
- let start = buffer[i + 1], end = buffer[i + 2];
352
- if (dir > 0) {
353
- if (end > after)
354
- pick = i;
355
- if (end > after)
356
- break;
357
- }
358
- else {
359
- if (start < after)
360
- pick = i;
361
- if (end >= after)
362
- break;
363
- }
364
- }
365
- else {
366
- pick = i;
367
- if (dir > 0)
368
- break;
369
- }
370
- }
371
- return pick;
372
- }
373
- }
374
- class TreeNode {
375
- constructor(node, from, index, _parent) {
376
- this.node = node;
377
- this.from = from;
378
- this.index = index;
379
- this._parent = _parent;
380
- }
381
- get type() { return this.node.type; }
382
- get name() { return this.node.type.name; }
383
- get to() { return this.from + this.node.length; }
384
- nextChild(i, dir, after, full = false) {
385
- for (let parent = this;;) {
386
- for (let { children, positions } = parent.node, e = dir > 0 ? children.length : -1; i != e; i += dir) {
387
- let next = children[i], start = positions[i] + parent.from;
388
- if (after != -100000000 /* None */ && (dir < 0 ? start >= after : start + next.length <= after))
389
- continue;
390
- if (next instanceof TreeBuffer) {
391
- let index = next.findChild(0, next.buffer.length, dir, after == -100000000 /* None */ ? -100000000 /* None */ : after - start);
392
- if (index > -1)
393
- return new BufferNode(new BufferContext(parent, next, i, start), null, index);
394
- }
395
- else if (full || (!next.type.isAnonymous || hasChild(next))) {
396
- let inner = new TreeNode(next, start, i, parent);
397
- return full || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, after);
398
- }
399
- }
400
- if (full || !parent.type.isAnonymous)
401
- return null;
402
- i = parent.index + dir;
403
- parent = parent._parent;
404
- if (!parent)
405
- return null;
406
- }
407
- }
408
- get firstChild() { return this.nextChild(0, 1, -100000000 /* None */); }
409
- get lastChild() { return this.nextChild(this.node.children.length - 1, -1, -100000000 /* None */); }
410
- childAfter(pos) { return this.nextChild(0, 1, pos); }
411
- childBefore(pos) { return this.nextChild(this.node.children.length - 1, -1, pos); }
412
- nextSignificantParent() {
413
- let val = this;
414
- while (val.type.isAnonymous && val._parent)
415
- val = val._parent;
416
- return val;
417
- }
418
- get parent() {
419
- return this._parent ? this._parent.nextSignificantParent() : null;
420
- }
421
- get nextSibling() {
422
- return this._parent ? this._parent.nextChild(this.index + 1, 1, -1) : null;
423
- }
424
- get prevSibling() {
425
- return this._parent ? this._parent.nextChild(this.index - 1, -1, -1) : null;
426
- }
427
- get cursor() { return new TreeCursor(this); }
428
- resolve(pos, side = 0) {
429
- return this.cursor.moveTo(pos, side).node;
430
- }
431
- getChild(type, before = null, after = null) {
432
- let r = getChildren(this, type, before, after);
433
- return r.length ? r[0] : null;
434
- }
435
- getChildren(type, before = null, after = null) {
436
- return getChildren(this, type, before, after);
437
- }
438
- /// @internal
439
- toString() { return this.node.toString(); }
440
- }
441
- function getChildren(node, type, before, after) {
442
- let cur = node.cursor, result = [];
443
- if (!cur.firstChild())
444
- return result;
445
- if (before != null)
446
- while (!cur.type.is(before))
447
- if (!cur.nextSibling())
448
- return result;
449
- for (;;) {
450
- if (after != null && cur.type.is(after))
451
- return result;
452
- if (cur.type.is(type))
453
- result.push(cur.node);
454
- if (!cur.nextSibling())
455
- return after == null ? result : [];
456
- }
457
- }
458
- class BufferContext {
459
- constructor(parent, buffer, index, start) {
460
- this.parent = parent;
461
- this.buffer = buffer;
462
- this.index = index;
463
- this.start = start;
464
- }
465
- }
466
- class BufferNode {
467
- constructor(context, _parent, index) {
468
- this.context = context;
469
- this._parent = _parent;
470
- this.index = index;
471
- this.type = context.buffer.set.types[context.buffer.buffer[index]];
472
- }
473
- get name() { return this.type.name; }
474
- get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
475
- get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
476
- child(dir, after) {
477
- let { buffer } = this.context;
478
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, after == -100000000 /* None */ ? -100000000 /* None */ : after - this.context.start);
479
- return index < 0 ? null : new BufferNode(this.context, this, index);
480
- }
481
- get firstChild() { return this.child(1, -100000000 /* None */); }
482
- get lastChild() { return this.child(-1, -100000000 /* None */); }
483
- childAfter(pos) { return this.child(1, pos); }
484
- childBefore(pos) { return this.child(-1, pos); }
485
- get parent() {
486
- return this._parent || this.context.parent.nextSignificantParent();
487
- }
488
- externalSibling(dir) {
489
- return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, -1);
490
- }
491
- get nextSibling() {
492
- let { buffer } = this.context;
493
- let after = buffer.buffer[this.index + 3];
494
- if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
495
- return new BufferNode(this.context, this._parent, after);
496
- return this.externalSibling(1);
497
- }
498
- get prevSibling() {
499
- let { buffer } = this.context;
500
- let parentStart = this._parent ? this._parent.index + 4 : 0;
501
- if (this.index == parentStart)
502
- return this.externalSibling(-1);
503
- return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, -100000000 /* None */));
504
- }
505
- get cursor() { return new TreeCursor(this); }
506
- resolve(pos, side = 0) {
507
- return this.cursor.moveTo(pos, side).node;
508
- }
509
- /// @internal
510
- toString() { return this.context.buffer.childString(this.index); }
511
- getChild(type, before = null, after = null) {
512
- let r = getChildren(this, type, before, after);
513
- return r.length ? r[0] : null;
514
- }
515
- getChildren(type, before = null, after = null) {
516
- return getChildren(this, type, before, after);
517
- }
518
- }
519
- /// A tree cursor object focuses on a given node in a syntax tree, and
520
- /// allows you to move to adjacent nodes.
521
- class TreeCursor {
522
- /// @internal
523
- constructor(node, full = false) {
524
- this.full = full;
525
- this.buffer = null;
526
- this.stack = [];
527
- this.index = 0;
528
- this.bufferNode = null;
529
- if (node instanceof TreeNode) {
530
- this.yieldNode(node);
531
- }
532
- else {
533
- this._tree = node.context.parent;
534
- this.buffer = node.context;
535
- for (let n = node._parent; n; n = n._parent)
536
- this.stack.unshift(n.index);
537
- this.bufferNode = node;
538
- this.yieldBuf(node.index);
539
- }
540
- }
541
- /// Shorthand for `.type.name`.
542
- get name() { return this.type.name; }
543
- yieldNode(node) {
544
- if (!node)
545
- return false;
546
- this._tree = node;
547
- this.type = node.type;
548
- this.from = node.from;
549
- this.to = node.to;
550
- return true;
551
- }
552
- yieldBuf(index, type) {
553
- this.index = index;
554
- let { start, buffer } = this.buffer;
555
- this.type = type || buffer.set.types[buffer.buffer[index]];
556
- this.from = start + buffer.buffer[index + 1];
557
- this.to = start + buffer.buffer[index + 2];
558
- return true;
559
- }
560
- yield(node) {
561
- if (!node)
562
- return false;
563
- if (node instanceof TreeNode) {
564
- this.buffer = null;
565
- return this.yieldNode(node);
566
- }
567
- this.buffer = node.context;
568
- return this.yieldBuf(node.index, node.type);
569
- }
570
- /// @internal
571
- toString() {
572
- return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
573
- }
574
- /// @internal
575
- enter(dir, after) {
576
- if (!this.buffer)
577
- return this.yield(this._tree.nextChild(dir < 0 ? this._tree.node.children.length - 1 : 0, dir, after, this.full));
578
- let { buffer } = this.buffer;
579
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, after == -100000000 /* None */ ? -100000000 /* None */ : after - this.buffer.start);
580
- if (index < 0)
581
- return false;
582
- this.stack.push(this.index);
583
- return this.yieldBuf(index);
584
- }
585
- /// Move the cursor to this node's first child. When this returns
586
- /// false, the node has no child, and the cursor has not been moved.
587
- firstChild() { return this.enter(1, -100000000 /* None */); }
588
- /// Move the cursor to this node's last child.
589
- lastChild() { return this.enter(-1, -100000000 /* None */); }
590
- /// Move the cursor to the first child that starts at or after `pos`.
591
- childAfter(pos) { return this.enter(1, pos); }
592
- /// Move to the last child that ends at or before `pos`.
593
- childBefore(pos) { return this.enter(-1, pos); }
594
- /// Move the node's parent node, if this isn't the top node.
595
- parent() {
596
- if (!this.buffer)
597
- return this.yieldNode(this.full ? this._tree._parent : this._tree.parent);
598
- if (this.stack.length)
599
- return this.yieldBuf(this.stack.pop());
600
- let parent = this.full ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
601
- this.buffer = null;
602
- return this.yieldNode(parent);
603
- }
604
- /// @internal
605
- sibling(dir) {
606
- if (!this.buffer)
607
- return !this._tree._parent ? false
608
- : this.yield(this._tree._parent.nextChild(this._tree.index + dir, dir, -100000000 /* None */, this.full));
609
- let { buffer } = this.buffer, d = this.stack.length - 1;
610
- if (dir < 0) {
611
- let parentStart = d < 0 ? 0 : this.stack[d] + 4;
612
- if (this.index != parentStart)
613
- return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, -100000000 /* None */));
614
- }
615
- else {
616
- let after = buffer.buffer[this.index + 3];
617
- if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
618
- return this.yieldBuf(after);
619
- }
620
- return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, -100000000 /* None */, this.full)) : false;
621
- }
622
- /// Move to this node's next sibling, if any.
623
- nextSibling() { return this.sibling(1); }
624
- /// Move to this node's previous sibling, if any.
625
- prevSibling() { return this.sibling(-1); }
626
- atLastNode(dir) {
627
- let index, parent, { buffer } = this;
628
- if (buffer) {
629
- if (dir > 0) {
630
- if (this.index < buffer.buffer.buffer.length)
631
- return false;
632
- }
633
- else {
634
- for (let i = 0; i < this.index; i++)
635
- if (buffer.buffer.buffer[i + 3] < this.index)
636
- return false;
637
- }
638
- ({ index, parent } = buffer);
639
- }
640
- else {
641
- ({ index, _parent: parent } = this._tree);
642
- }
643
- for (; parent; { index, _parent: parent } = parent) {
644
- for (let i = index + dir, e = dir < 0 ? -1 : parent.node.children.length; i != e; i += dir) {
645
- let child = parent.node.children[i];
646
- if (this.full || !child.type.isAnonymous || child instanceof TreeBuffer || hasChild(child))
647
- return false;
648
- }
649
- }
650
- return true;
651
- }
652
- move(dir) {
653
- if (this.enter(dir, -100000000 /* None */))
654
- return true;
655
- for (;;) {
656
- if (this.sibling(dir))
657
- return true;
658
- if (this.atLastNode(dir) || !this.parent())
659
- return false;
660
- }
661
- }
662
- /// Move to the next node in a
663
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
664
- /// traversal, going from a node to its first child or, if the
665
- /// current node is empty, its next sibling or the next sibling of
666
- /// the first parent node that has one.
667
- next() { return this.move(1); }
668
- /// Move to the next node in a last-to-first pre-order traveral. A
669
- /// node is followed by ist last child or, if it has none, its
670
- /// previous sibling or the previous sibling of the first parent
671
- /// node that has one.
672
- prev() { return this.move(-1); }
673
- /// Move the cursor to the innermost node that covers `pos`. If
674
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
675
- /// it will enter nodes that start at `pos`.
676
- moveTo(pos, side = 0) {
677
- // Move up to a node that actually holds the position, if possible
678
- while (this.from == this.to ||
679
- (side < 1 ? this.from >= pos : this.from > pos) ||
680
- (side > -1 ? this.to <= pos : this.to < pos))
681
- if (!this.parent())
682
- break;
683
- // Then scan down into child nodes as far as possible
684
- for (;;) {
685
- if (side < 0 ? !this.childBefore(pos) : !this.childAfter(pos))
686
- break;
687
- if (this.from == this.to ||
688
- (side < 1 ? this.from >= pos : this.from > pos) ||
689
- (side > -1 ? this.to <= pos : this.to < pos)) {
690
- this.parent();
691
- break;
692
- }
693
- }
694
- return this;
695
- }
696
- /// Get a [syntax node](#tree.SyntaxNode) at the cursor's current
697
- /// position.
698
- get node() {
699
- if (!this.buffer)
700
- return this._tree;
701
- let cache = this.bufferNode, result = null, depth = 0;
702
- if (cache && cache.context == this.buffer) {
703
- scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
704
- for (let c = cache; c; c = c._parent)
705
- if (c.index == index) {
706
- if (index == this.index)
707
- return c;
708
- result = c;
709
- depth = d + 1;
710
- break scan;
711
- }
712
- index = this.stack[--d];
713
- }
714
- }
715
- for (let i = depth; i < this.stack.length; i++)
716
- result = new BufferNode(this.buffer, result, this.stack[i]);
717
- return this.bufferNode = new BufferNode(this.buffer, result, this.index);
718
- }
719
- /// Get the [tree](#tree.Tree) that represents the current node, if
720
- /// any. Will return null when the node is in a [tree
721
- /// buffer](#tree.TreeBuffer).
722
- get tree() {
723
- return this.buffer ? null : this._tree.node;
724
- }
725
- }
726
- function hasChild(tree) {
727
- return tree.children.some(ch => !ch.type.isAnonymous || ch instanceof TreeBuffer || hasChild(ch));
728
- }
729
- class FlatBufferCursor {
730
- constructor(buffer, index) {
731
- this.buffer = buffer;
732
- this.index = index;
733
- }
734
- get id() { return this.buffer[this.index - 4]; }
735
- get start() { return this.buffer[this.index - 3]; }
736
- get end() { return this.buffer[this.index - 2]; }
737
- get size() { return this.buffer[this.index - 1]; }
738
- get pos() { return this.index; }
739
- next() { this.index -= 4; }
740
- fork() { return new FlatBufferCursor(this.buffer, this.index); }
741
- }
742
- const BalanceBranchFactor = 8;
743
- function buildTree(data) {
744
- var _a;
745
- let { buffer, nodeSet, topID = 0, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
746
- let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
747
- let types = nodeSet.types;
748
- let contextHash = 0;
749
- function takeNode(parentStart, minPos, children, positions, inRepeat) {
750
- let { id, start, end, size } = cursor;
751
- let startPos = start - parentStart;
752
- if (size < 0) {
753
- if (size == -1) { // Reused node
754
- children.push(reused[id]);
755
- positions.push(startPos);
756
- }
757
- else { // Context change
758
- contextHash = id;
759
- }
760
- cursor.next();
761
- return;
762
- }
763
- let type = types[id], node, buffer;
764
- if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
765
- // Small enough for a buffer, and no reused nodes inside
766
- let data = new Uint16Array(buffer.size - buffer.skip);
767
- let endPos = cursor.pos - buffer.size, index = data.length;
768
- while (cursor.pos > endPos)
769
- index = copyToBuffer(buffer.start, data, index, inRepeat);
770
- node = new TreeBuffer(data, end - buffer.start, nodeSet, inRepeat < 0 ? NodeType.none : types[inRepeat]);
771
- startPos = buffer.start - parentStart;
772
- }
773
- else { // Make it a node
774
- let endPos = cursor.pos - size;
775
- cursor.next();
776
- let localChildren = [], localPositions = [];
777
- let localInRepeat = id >= minRepeatType ? id : -1;
778
- while (cursor.pos > endPos) {
779
- if (cursor.id == localInRepeat)
780
- cursor.next();
781
- else
782
- takeNode(start, endPos, localChildren, localPositions, localInRepeat);
783
- }
784
- localChildren.reverse();
785
- localPositions.reverse();
786
- if (localInRepeat > -1 && localChildren.length > BalanceBranchFactor)
787
- node = balanceRange(type, type, localChildren, localPositions, 0, localChildren.length, 0, maxBufferLength, end - start, contextHash);
788
- else
789
- node = withHash(new Tree(type, localChildren, localPositions, end - start), contextHash);
790
- }
791
- children.push(node);
792
- positions.push(startPos);
793
- }
794
- function findBufferSize(maxSize, inRepeat) {
795
- // Scan through the buffer to find previous siblings that fit
796
- // together in a TreeBuffer, and don't contain any reused nodes
797
- // (which can't be stored in a buffer).
798
- // If `inRepeat` is > -1, ignore node boundaries of that type for
799
- // nesting, but make sure the end falls either at the start
800
- // (`maxSize`) or before such a node.
801
- let fork = cursor.fork();
802
- let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
803
- let result = { size: 0, start: 0, skip: 0 };
804
- scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
805
- // Pretend nested repeat nodes of the same type don't exist
806
- if (fork.id == inRepeat) {
807
- // Except that we store the current state as a valid return
808
- // value.
809
- result.size = size;
810
- result.start = start;
811
- result.skip = skip;
812
- skip += 4;
813
- size += 4;
814
- fork.next();
815
- continue;
816
- }
817
- let nodeSize = fork.size, startPos = fork.pos - nodeSize;
818
- if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
819
- break;
820
- let localSkipped = fork.id >= minRepeatType ? 4 : 0;
821
- let nodeStart = fork.start;
822
- fork.next();
823
- while (fork.pos > startPos) {
824
- if (fork.size < 0)
825
- break scan;
826
- if (fork.id >= minRepeatType)
827
- localSkipped += 4;
828
- fork.next();
829
- }
830
- start = nodeStart;
831
- size += nodeSize;
832
- skip += localSkipped;
833
- }
834
- if (inRepeat < 0 || size == maxSize) {
835
- result.size = size;
836
- result.start = start;
837
- result.skip = skip;
838
- }
839
- return result.size > 4 ? result : undefined;
840
- }
841
- function copyToBuffer(bufferStart, buffer, index, inRepeat) {
842
- let { id, start, end, size } = cursor;
843
- cursor.next();
844
- if (id == inRepeat)
845
- return index;
846
- let startIndex = index;
847
- if (size > 4) {
848
- let endPos = cursor.pos - (size - 4);
849
- while (cursor.pos > endPos)
850
- index = copyToBuffer(bufferStart, buffer, index, inRepeat);
851
- }
852
- if (id < minRepeatType) { // Don't copy repeat nodes into buffers
853
- buffer[--index] = startIndex;
854
- buffer[--index] = end - bufferStart;
855
- buffer[--index] = start - bufferStart;
856
- buffer[--index] = id;
857
- }
858
- return index;
859
- }
860
- let children = [], positions = [];
861
- while (cursor.pos > 0)
862
- takeNode(data.start || 0, 0, children, positions, -1);
863
- let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
864
- return new Tree(types[topID], children.reverse(), positions.reverse(), length);
865
- }
866
- function balanceRange(outerType, innerType, children, positions, from, to, start, maxBufferLength, length, contextHash) {
867
- let localChildren = [], localPositions = [];
868
- if (length <= maxBufferLength) {
869
- for (let i = from; i < to; i++) {
870
- localChildren.push(children[i]);
871
- localPositions.push(positions[i] - start);
872
- }
873
- }
874
- else {
875
- let maxChild = Math.max(maxBufferLength, Math.ceil(length * 1.5 / BalanceBranchFactor));
876
- for (let i = from; i < to;) {
877
- let groupFrom = i, groupStart = positions[i];
878
- i++;
879
- for (; i < to; i++) {
880
- let nextEnd = positions[i] + children[i].length;
881
- if (nextEnd - groupStart > maxChild)
882
- break;
883
- }
884
- if (i == groupFrom + 1) {
885
- let only = children[groupFrom];
886
- if (only instanceof Tree && only.type == innerType && only.length > maxChild << 1) { // Too big, collapse
887
- for (let j = 0; j < only.children.length; j++) {
888
- localChildren.push(only.children[j]);
889
- localPositions.push(only.positions[j] + groupStart - start);
890
- }
891
- continue;
892
- }
893
- localChildren.push(only);
894
- }
895
- else if (i == groupFrom + 1) {
896
- localChildren.push(children[groupFrom]);
897
- }
898
- else {
899
- let inner = balanceRange(innerType, innerType, children, positions, groupFrom, i, groupStart, maxBufferLength, positions[i - 1] + children[i - 1].length - groupStart, contextHash);
900
- if (innerType != NodeType.none && !containsType(inner.children, innerType))
901
- inner = withHash(new Tree(NodeType.none, inner.children, inner.positions, inner.length), contextHash);
902
- localChildren.push(inner);
903
- }
904
- localPositions.push(groupStart - start);
905
- }
906
- }
907
- return withHash(new Tree(outerType, localChildren, localPositions, length), contextHash);
908
- }
909
- function containsType(nodes, type) {
910
- for (let elt of nodes)
911
- if (elt.type == type)
912
- return true;
913
- return false;
914
- }
915
- /// Tree fragments are used during [incremental
916
- /// parsing](#lezer.ParseOptions.fragments) to track parts of old
917
- /// trees that can be reused in a new parse. An array of fragments is
918
- /// used to track regions of an old tree whose nodes might be reused
919
- /// in new parses. Use the static
920
- /// [`applyChanges`](#tree.TreeFragment^applyChanges) method to update
921
- /// fragments for document changes.
922
- class TreeFragment {
923
- constructor(
924
- /// The start of the unchanged range pointed to by this fragment.
925
- /// This refers to an offset in the _updated_ document (as opposed
926
- /// to the original tree).
927
- from,
928
- /// The end of the unchanged range.
929
- to,
930
- /// The tree that this fragment is based on.
931
- tree,
932
- /// The offset between the fragment's tree and the document that
933
- /// this fragment can be used against. Add this when going from
934
- /// document to tree positions, subtract it to go from tree to
935
- /// document positions.
936
- offset, open) {
937
- this.from = from;
938
- this.to = to;
939
- this.tree = tree;
940
- this.offset = offset;
941
- this.open = open;
942
- }
943
- get openStart() { return (this.open & 1 /* Start */) > 0; }
944
- get openEnd() { return (this.open & 2 /* End */) > 0; }
945
- /// Apply a set of edits to an array of fragments, removing or
946
- /// splitting fragments as necessary to remove edited ranges, and
947
- /// adjusting offsets for fragments that moved.
948
- static applyChanges(fragments, changes, minGap = 128) {
949
- if (!changes.length)
950
- return fragments;
951
- let result = [];
952
- let fI = 1, nextF = fragments.length ? fragments[0] : null;
953
- for (let cI = 0, pos = 0, off = 0;; cI++) {
954
- let nextC = cI < changes.length ? changes[cI] : null;
955
- let nextPos = nextC ? nextC.fromA : 1e9;
956
- if (nextPos - pos >= minGap)
957
- while (nextF && nextF.from < nextPos) {
958
- let cut = nextF;
959
- if (pos >= cut.from || nextPos <= cut.to || off) {
960
- let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
961
- cut = fFrom >= fTo ? null :
962
- new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, (cI > 0 ? 1 /* Start */ : 0) | (nextC ? 2 /* End */ : 0));
963
- }
964
- if (cut)
965
- result.push(cut);
966
- if (nextF.to > nextPos)
967
- break;
968
- nextF = fI < fragments.length ? fragments[fI++] : null;
969
- }
970
- if (!nextC)
971
- break;
972
- pos = nextC.toA;
973
- off = nextC.toA - nextC.toB;
974
- }
975
- return result;
976
- }
977
- /// Create a set of fragments from a freshly parsed tree, or update
978
- /// an existing set of fragments by replacing the ones that overlap
979
- /// with a tree with content from the new tree. When `partial` is
980
- /// true, the parse is treated as incomplete, and the token at its
981
- /// end is not included in [`safeTo`](#tree.TreeFragment.safeTo).
982
- static addTree(tree, fragments = [], partial = false) {
983
- let result = [new TreeFragment(0, tree.length, tree, 0, partial ? 2 /* End */ : 0)];
984
- for (let f of fragments)
985
- if (f.to > tree.length)
986
- result.push(f);
987
- return result;
988
- }
989
- }
990
- // Creates an `Input` that is backed by a single, flat string.
991
- function stringInput(input) { return new StringInput(input); }
992
- class StringInput {
993
- constructor(string, length = string.length) {
994
- this.string = string;
995
- this.length = length;
996
- }
997
- get(pos) {
998
- return pos < 0 || pos >= this.length ? -1 : this.string.charCodeAt(pos);
999
- }
1000
- lineAfter(pos) {
1001
- if (pos < 0)
1002
- return "";
1003
- let end = this.string.indexOf("\n", pos);
1004
- return this.string.slice(pos, end < 0 ? this.length : Math.min(end, this.length));
1005
- }
1006
- read(from, to) { return this.string.slice(from, Math.min(this.length, to)); }
1007
- clip(at) { return new StringInput(this.string, at); }
1008
- }
1009
-
1010
- exports.DefaultBufferLength = DefaultBufferLength;
1011
- exports.NodeProp = NodeProp;
1012
- exports.NodeSet = NodeSet;
1013
- exports.NodeType = NodeType;
1014
- exports.Tree = Tree;
1015
- exports.TreeBuffer = TreeBuffer;
1016
- exports.TreeCursor = TreeCursor;
1017
- exports.TreeFragment = TreeFragment;
1018
- exports.stringInput = stringInput;
1019
- //# sourceMappingURL=tree.cjs.map