@lezer/common 0.16.0 → 0.16.1

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.
@@ -0,0 +1,1816 @@
1
+ // FIXME profile adding a per-Tree TreeNode cache, validating it by
2
+ // parent pointer
3
+ /// The default maximum length of a `TreeBuffer` node (1024).
4
+ const DefaultBufferLength = 1024;
5
+ let nextPropID = 0;
6
+ class Range {
7
+ constructor(from, to) {
8
+ this.from = from;
9
+ this.to = to;
10
+ }
11
+ }
12
+ /// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
13
+ /// can have metadata associated with it in props. Instances of this
14
+ /// class represent prop names.
15
+ class NodeProp {
16
+ /// Create a new node prop type.
17
+ constructor(config = {}) {
18
+ this.id = nextPropID++;
19
+ this.perNode = !!config.perNode;
20
+ this.deserialize = config.deserialize || (() => {
21
+ throw new Error("This node type doesn't define a deserialize function");
22
+ });
23
+ }
24
+ /// This is meant to be used with
25
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
26
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
27
+ /// prop values for each node type in the set. Takes a [match
28
+ /// object](#common.NodeType^match) or function that returns undefined
29
+ /// if the node type doesn't get this prop, and the prop's value if
30
+ /// it does.
31
+ add(match) {
32
+ if (this.perNode)
33
+ throw new RangeError("Can't add per-node props to node types");
34
+ if (typeof match != "function")
35
+ match = NodeType.match(match);
36
+ return (type) => {
37
+ let result = match(type);
38
+ return result === undefined ? null : [this, result];
39
+ };
40
+ }
41
+ }
42
+ /// Prop that is used to describe matching delimiters. For opening
43
+ /// delimiters, this holds an array of node names (written as a
44
+ /// space-separated string when declaring this prop in a grammar)
45
+ /// for the node types of closing delimiters that match it.
46
+ NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
47
+ /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
48
+ /// attached to closing delimiters, holding an array of node names
49
+ /// of types of matching opening delimiters.
50
+ NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
51
+ /// Used to assign node types to groups (for example, all node
52
+ /// types that represent an expression could be tagged with an
53
+ /// `"Expression"` group).
54
+ NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
55
+ /// The hash of the [context](#lr.ContextTracker.constructor)
56
+ /// that the node was parsed in, if any. Used to limit reuse of
57
+ /// contextual nodes.
58
+ NodeProp.contextHash = new NodeProp({ perNode: true });
59
+ /// The distance beyond the end of the node that the tokenizer
60
+ /// looked ahead for any of the tokens inside the node. (The LR
61
+ /// parser only stores this when it is larger than 25, for
62
+ /// efficiency reasons.)
63
+ NodeProp.lookAhead = new NodeProp({ perNode: true });
64
+ /// This per-node prop is used to replace a given node, or part of a
65
+ /// node, with another tree. This is useful to include trees from
66
+ /// different languages.
67
+ NodeProp.mounted = new NodeProp({ perNode: true });
68
+ /// A mounted tree, which can be [stored](#common.NodeProp^mounted) on
69
+ /// a tree node to indicate that parts of its content are
70
+ /// represented by another tree.
71
+ class MountedTree {
72
+ constructor(
73
+ /// The inner tree.
74
+ tree,
75
+ /// If this is null, this tree replaces the entire node (it will
76
+ /// be included in the regular iteration instead of its host
77
+ /// node). If not, only the given ranges are considered to be
78
+ /// covered by this tree. This is used for trees that are mixed in
79
+ /// a way that isn't strictly hierarchical. Such mounted trees are
80
+ /// only entered by [`resolveInner`](#common.Tree.resolveInner)
81
+ /// and [`enter`](#common.SyntaxNode.enter).
82
+ overlay,
83
+ /// The parser used to create this subtree.
84
+ parser) {
85
+ this.tree = tree;
86
+ this.overlay = overlay;
87
+ this.parser = parser;
88
+ }
89
+ }
90
+ const noProps = Object.create(null);
91
+ /// Each node in a syntax tree has a node type associated with it.
92
+ class NodeType {
93
+ /// @internal
94
+ constructor(
95
+ /// The name of the node type. Not necessarily unique, but if the
96
+ /// grammar was written properly, different node types with the
97
+ /// same name within a node set should play the same semantic
98
+ /// role.
99
+ name,
100
+ /// @internal
101
+ props,
102
+ /// The id of this node in its set. Corresponds to the term ids
103
+ /// used in the parser.
104
+ id,
105
+ /// @internal
106
+ flags = 0) {
107
+ this.name = name;
108
+ this.props = props;
109
+ this.id = id;
110
+ this.flags = flags;
111
+ }
112
+ static define(spec) {
113
+ let props = spec.props && spec.props.length ? Object.create(null) : noProps;
114
+ let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) |
115
+ (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0);
116
+ let type = new NodeType(spec.name || "", props, spec.id, flags);
117
+ if (spec.props)
118
+ for (let src of spec.props) {
119
+ if (!Array.isArray(src))
120
+ src = src(type);
121
+ if (src) {
122
+ if (src[0].perNode)
123
+ throw new RangeError("Can't store a per-node prop on a node type");
124
+ props[src[0].id] = src[1];
125
+ }
126
+ }
127
+ return type;
128
+ }
129
+ /// Retrieves a node prop for this type. Will return `undefined` if
130
+ /// the prop isn't present on this node.
131
+ prop(prop) { return this.props[prop.id]; }
132
+ /// True when this is the top node of a grammar.
133
+ get isTop() { return (this.flags & 1 /* Top */) > 0; }
134
+ /// True when this node is produced by a skip rule.
135
+ get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; }
136
+ /// Indicates whether this is an error node.
137
+ get isError() { return (this.flags & 4 /* Error */) > 0; }
138
+ /// When true, this node type doesn't correspond to a user-declared
139
+ /// named node, for example because it is used to cache repetition.
140
+ get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; }
141
+ /// Returns true when this node's name or one of its
142
+ /// [groups](#common.NodeProp^group) matches the given string.
143
+ is(name) {
144
+ if (typeof name == 'string') {
145
+ if (this.name == name)
146
+ return true;
147
+ let group = this.prop(NodeProp.group);
148
+ return group ? group.indexOf(name) > -1 : false;
149
+ }
150
+ return this.id == name;
151
+ }
152
+ /// Create a function from node types to arbitrary values by
153
+ /// specifying an object whose property names are node or
154
+ /// [group](#common.NodeProp^group) names. Often useful with
155
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
156
+ /// names, separated by spaces, in a single property name to map
157
+ /// multiple node names to a single value.
158
+ static match(map) {
159
+ let direct = Object.create(null);
160
+ for (let prop in map)
161
+ for (let name of prop.split(" "))
162
+ direct[name] = map[prop];
163
+ return (node) => {
164
+ for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
165
+ let found = direct[i < 0 ? node.name : groups[i]];
166
+ if (found)
167
+ return found;
168
+ }
169
+ };
170
+ }
171
+ }
172
+ /// An empty dummy node type to use when no actual type is available.
173
+ NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */);
174
+ /// A node set holds a collection of node types. It is used to
175
+ /// compactly represent trees by storing their type ids, rather than a
176
+ /// full pointer to the type object, in a numeric array. Each parser
177
+ /// [has](#lr.LRParser.nodeSet) a node set, and [tree
178
+ /// buffers](#common.TreeBuffer) can only store collections of nodes
179
+ /// from the same set. A set can have a maximum of 2**16 (65536) node
180
+ /// types in it, so that the ids fit into 16-bit typed array slots.
181
+ class NodeSet {
182
+ /// Create a set with the given types. The `id` property of each
183
+ /// type should correspond to its position within the array.
184
+ constructor(
185
+ /// The node types in this set, by id.
186
+ types) {
187
+ this.types = types;
188
+ for (let i = 0; i < types.length; i++)
189
+ if (types[i].id != i)
190
+ throw new RangeError("Node type ids should correspond to array positions when creating a node set");
191
+ }
192
+ /// Create a copy of this set with some node properties added. The
193
+ /// arguments to this method should be created with
194
+ /// [`NodeProp.add`](#common.NodeProp.add).
195
+ extend(...props) {
196
+ let newTypes = [];
197
+ for (let type of this.types) {
198
+ let newProps = null;
199
+ for (let source of props) {
200
+ let add = source(type);
201
+ if (add) {
202
+ if (!newProps)
203
+ newProps = Object.assign({}, type.props);
204
+ newProps[add[0].id] = add[1];
205
+ }
206
+ }
207
+ newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
208
+ }
209
+ return new NodeSet(newTypes);
210
+ }
211
+ }
212
+ const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();
213
+ /// Options that control iteration. Can be combined with the `|`
214
+ /// operator to enable multiple ones.
215
+ var IterMode;
216
+ (function (IterMode) {
217
+ /// When enabled, iteration will only visit [`Tree`](#common.Tree)
218
+ /// objects, not nodes packed into
219
+ /// [`TreeBuffer`](#common.TreeBuffer)s.
220
+ IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
221
+ /// Enable this to make iteration include anonymous nodes (such as
222
+ /// the nodes that wrap repeated grammar constructs into a balanced
223
+ /// tree).
224
+ IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
225
+ /// By default, regular [mounted](#common.NodeProp^mounted) nodes
226
+ /// replace their base node in iteration. Enable this to ignore them
227
+ /// instead.
228
+ IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
229
+ /// This option only applies in
230
+ /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
231
+ /// library to not enter mounted overlays if one covers the given
232
+ /// position.
233
+ IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
234
+ })(IterMode || (IterMode = {}));
235
+ /// A piece of syntax tree. There are two ways to approach these
236
+ /// trees: the way they are actually stored in memory, and the
237
+ /// convenient way.
238
+ ///
239
+ /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
240
+ /// objects. By packing detail information into `TreeBuffer` leaf
241
+ /// nodes, the representation is made a lot more memory-efficient.
242
+ ///
243
+ /// However, when you want to actually work with tree nodes, this
244
+ /// representation is very awkward, so most client code will want to
245
+ /// use the [`TreeCursor`](#common.TreeCursor) or
246
+ /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
247
+ /// a view on some part of this data structure, and can be used to
248
+ /// move around to adjacent nodes.
249
+ class Tree {
250
+ /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
251
+ constructor(
252
+ /// The type of the top node.
253
+ type,
254
+ /// This node's child nodes.
255
+ children,
256
+ /// The positions (offsets relative to the start of this tree) of
257
+ /// the children.
258
+ positions,
259
+ /// The total length of this tree
260
+ length,
261
+ /// Per-node [node props](#common.NodeProp) to associate with this node.
262
+ props) {
263
+ this.type = type;
264
+ this.children = children;
265
+ this.positions = positions;
266
+ this.length = length;
267
+ /// @internal
268
+ this.props = null;
269
+ if (props && props.length) {
270
+ this.props = Object.create(null);
271
+ for (let [prop, value] of props)
272
+ this.props[typeof prop == "number" ? prop : prop.id] = value;
273
+ }
274
+ }
275
+ /// @internal
276
+ toString() {
277
+ let mounted = this.prop(NodeProp.mounted);
278
+ if (mounted && !mounted.overlay)
279
+ return mounted.tree.toString();
280
+ let children = "";
281
+ for (let ch of this.children) {
282
+ let str = ch.toString();
283
+ if (str) {
284
+ if (children)
285
+ children += ",";
286
+ children += str;
287
+ }
288
+ }
289
+ return !this.type.name ? children :
290
+ (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
291
+ (children.length ? "(" + children + ")" : "");
292
+ }
293
+ /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
294
+ /// the tree. Mode can be used to [control](#common.IterMode) which
295
+ /// nodes the cursor visits.
296
+ cursor(mode = 0) {
297
+ return new TreeCursor(this.topNode, mode);
298
+ }
299
+ /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
300
+ /// at the given position and side (see
301
+ /// [`moveTo`](#common.TreeCursor.moveTo).
302
+ cursorAt(pos, side = 0, mode = 0) {
303
+ let scope = CachedNode.get(this) || this.topNode;
304
+ let cursor = new TreeCursor(scope);
305
+ cursor.moveTo(pos, side);
306
+ CachedNode.set(this, cursor._tree);
307
+ return cursor;
308
+ }
309
+ /// Get a [syntax node](#common.SyntaxNode) object for the top of the
310
+ /// tree.
311
+ get topNode() {
312
+ return new TreeNode(this, 0, 0, null);
313
+ }
314
+ /// Get the [syntax node](#common.SyntaxNode) at the given position.
315
+ /// If `side` is -1, this will move into nodes that end at the
316
+ /// position. If 1, it'll move into nodes that start at the
317
+ /// position. With 0, it'll only enter nodes that cover the position
318
+ /// from both sides.
319
+ resolve(pos, side = 0) {
320
+ let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
321
+ CachedNode.set(this, node);
322
+ return node;
323
+ }
324
+ /// Like [`resolve`](#common.Tree.resolve), but will enter
325
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
326
+ /// pointing into the innermost overlaid tree at the given position
327
+ /// (with parent links going through all parent structure, including
328
+ /// the host trees).
329
+ resolveInner(pos, side = 0) {
330
+ let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
331
+ CachedInnerNode.set(this, node);
332
+ return node;
333
+ }
334
+ /// Iterate over the tree and its children, calling `enter` for any
335
+ /// node that touches the `from`/`to` region (if given) before
336
+ /// running over such a node's children, and `leave` (if given) when
337
+ /// leaving the node. When `enter` returns `false`, that node will
338
+ /// not have its children iterated over (or `leave` called).
339
+ iterate(spec) {
340
+ let { enter, leave, from = 0, to = this.length } = spec;
341
+ for (let c = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous);;) {
342
+ let entered = false;
343
+ if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) {
344
+ if (c.firstChild())
345
+ continue;
346
+ entered = true;
347
+ }
348
+ for (;;) {
349
+ if (entered && leave && !c.type.isAnonymous)
350
+ leave(c);
351
+ if (c.nextSibling())
352
+ break;
353
+ if (!c.parent())
354
+ return;
355
+ entered = true;
356
+ }
357
+ }
358
+ }
359
+ /// Get the value of the given [node prop](#common.NodeProp) for this
360
+ /// node. Works with both per-node and per-type props.
361
+ prop(prop) {
362
+ return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
363
+ }
364
+ /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
365
+ /// format that can be passed to the [`Tree`](#common.Tree)
366
+ /// constructor.
367
+ get propValues() {
368
+ let result = [];
369
+ if (this.props)
370
+ for (let id in this.props)
371
+ result.push([+id, this.props[id]]);
372
+ return result;
373
+ }
374
+ /// Balance the direct children of this tree, producing a copy of
375
+ /// which may have children grouped into subtrees with type
376
+ /// [`NodeType.none`](#common.NodeType^none).
377
+ balance(config = {}) {
378
+ return this.children.length <= 8 /* BranchFactor */ ? this :
379
+ 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)));
380
+ }
381
+ /// Build a tree from a postfix-ordered buffer of node information,
382
+ /// or a cursor over such a buffer.
383
+ static build(data) { return buildTree(data); }
384
+ }
385
+ /// The empty tree
386
+ Tree.empty = new Tree(NodeType.none, [], [], 0);
387
+ class FlatBufferCursor {
388
+ constructor(buffer, index) {
389
+ this.buffer = buffer;
390
+ this.index = index;
391
+ }
392
+ get id() { return this.buffer[this.index - 4]; }
393
+ get start() { return this.buffer[this.index - 3]; }
394
+ get end() { return this.buffer[this.index - 2]; }
395
+ get size() { return this.buffer[this.index - 1]; }
396
+ get pos() { return this.index; }
397
+ next() { this.index -= 4; }
398
+ fork() { return new FlatBufferCursor(this.buffer, this.index); }
399
+ }
400
+ /// Tree buffers contain (type, start, end, endIndex) quads for each
401
+ /// node. In such a buffer, nodes are stored in prefix order (parents
402
+ /// before children, with the endIndex of the parent indicating which
403
+ /// children belong to it)
404
+ class TreeBuffer {
405
+ /// Create a tree buffer.
406
+ constructor(
407
+ /// The buffer's content.
408
+ buffer,
409
+ /// The total length of the group of nodes in the buffer.
410
+ length,
411
+ /// The node set used in this buffer.
412
+ set) {
413
+ this.buffer = buffer;
414
+ this.length = length;
415
+ this.set = set;
416
+ }
417
+ /// @internal
418
+ get type() { return NodeType.none; }
419
+ /// @internal
420
+ toString() {
421
+ let result = [];
422
+ for (let index = 0; index < this.buffer.length;) {
423
+ result.push(this.childString(index));
424
+ index = this.buffer[index + 3];
425
+ }
426
+ return result.join(",");
427
+ }
428
+ /// @internal
429
+ childString(index) {
430
+ let id = this.buffer[index], endIndex = this.buffer[index + 3];
431
+ let type = this.set.types[id], result = type.name;
432
+ if (/\W/.test(result) && !type.isError)
433
+ result = JSON.stringify(result);
434
+ index += 4;
435
+ if (endIndex == index)
436
+ return result;
437
+ let children = [];
438
+ while (index < endIndex) {
439
+ children.push(this.childString(index));
440
+ index = this.buffer[index + 3];
441
+ }
442
+ return result + "(" + children.join(",") + ")";
443
+ }
444
+ /// @internal
445
+ findChild(startIndex, endIndex, dir, pos, side) {
446
+ let { buffer } = this, pick = -1;
447
+ for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
448
+ if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
449
+ pick = i;
450
+ if (dir > 0)
451
+ break;
452
+ }
453
+ }
454
+ return pick;
455
+ }
456
+ /// @internal
457
+ slice(startI, endI, from, to) {
458
+ let b = this.buffer;
459
+ let copy = new Uint16Array(endI - startI);
460
+ for (let i = startI, j = 0; i < endI;) {
461
+ copy[j++] = b[i++];
462
+ copy[j++] = b[i++] - from;
463
+ copy[j++] = b[i++] - from;
464
+ copy[j++] = b[i++] - startI;
465
+ }
466
+ return new TreeBuffer(copy, to - from, this.set);
467
+ }
468
+ }
469
+ function checkSide(side, pos, from, to) {
470
+ switch (side) {
471
+ case -2 /* Before */: return from < pos;
472
+ case -1 /* AtOrBefore */: return to >= pos && from < pos;
473
+ case 0 /* Around */: return from < pos && to > pos;
474
+ case 1 /* AtOrAfter */: return from <= pos && to > pos;
475
+ case 2 /* After */: return to > pos;
476
+ case 4 /* DontCare */: return true;
477
+ }
478
+ }
479
+ function enterUnfinishedNodesBefore(node, pos) {
480
+ let scan = node.childBefore(pos);
481
+ while (scan) {
482
+ let last = scan.lastChild;
483
+ if (!last || last.to != scan.to)
484
+ break;
485
+ if (last.type.isError && last.from == last.to) {
486
+ node = scan;
487
+ scan = last.prevSibling;
488
+ }
489
+ else {
490
+ scan = last;
491
+ }
492
+ }
493
+ return node;
494
+ }
495
+ function resolveNode(node, pos, side, overlays) {
496
+ var _a;
497
+ // Move up to a node that actually holds the position, if possible
498
+ while (node.from == node.to ||
499
+ (side < 1 ? node.from >= pos : node.from > pos) ||
500
+ (side > -1 ? node.to <= pos : node.to < pos)) {
501
+ let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
502
+ if (!parent)
503
+ return node;
504
+ node = parent;
505
+ }
506
+ let mode = overlays ? 0 : IterMode.IgnoreOverlays;
507
+ // Must go up out of overlays when those do not overlap with pos
508
+ if (overlays)
509
+ for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
510
+ if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
511
+ node = parent;
512
+ }
513
+ for (;;) {
514
+ let inner = node.enter(pos, side, mode);
515
+ if (!inner)
516
+ return node;
517
+ node = inner;
518
+ }
519
+ }
520
+ class TreeNode {
521
+ constructor(_tree, from,
522
+ // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
523
+ index, _parent) {
524
+ this._tree = _tree;
525
+ this.from = from;
526
+ this.index = index;
527
+ this._parent = _parent;
528
+ }
529
+ get type() { return this._tree.type; }
530
+ get name() { return this._tree.type.name; }
531
+ get to() { return this.from + this._tree.length; }
532
+ nextChild(i, dir, pos, side, mode = 0) {
533
+ for (let parent = this;;) {
534
+ for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
535
+ let next = children[i], start = positions[i] + parent.from;
536
+ if (!checkSide(side, pos, start, start + next.length))
537
+ continue;
538
+ if (next instanceof TreeBuffer) {
539
+ if (mode & IterMode.ExcludeBuffers)
540
+ continue;
541
+ let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
542
+ if (index > -1)
543
+ return new BufferNode(new BufferContext(parent, next, i, start), null, index);
544
+ }
545
+ else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
546
+ let mounted;
547
+ if (!(mode & IterMode.IgnoreMounts) &&
548
+ next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
549
+ return new TreeNode(mounted.tree, start, i, parent);
550
+ let inner = new TreeNode(next, start, i, parent);
551
+ return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
552
+ : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
553
+ }
554
+ }
555
+ if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)
556
+ return null;
557
+ if (parent.index >= 0)
558
+ i = parent.index + dir;
559
+ else
560
+ i = dir < 0 ? -1 : parent._parent._tree.children.length;
561
+ parent = parent._parent;
562
+ if (!parent)
563
+ return null;
564
+ }
565
+ }
566
+ get firstChild() { return this.nextChild(0, 1, 0, 4 /* DontCare */); }
567
+ get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* DontCare */); }
568
+ childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* After */); }
569
+ childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Before */); }
570
+ enter(pos, side, mode = 0) {
571
+ let mounted;
572
+ if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
573
+ let rPos = pos - this.from;
574
+ for (let { from, to } of mounted.overlay) {
575
+ if ((side > 0 ? from <= rPos : from < rPos) &&
576
+ (side < 0 ? to >= rPos : to > rPos))
577
+ return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
578
+ }
579
+ }
580
+ return this.nextChild(0, 1, pos, side, mode);
581
+ }
582
+ nextSignificantParent() {
583
+ let val = this;
584
+ while (val.type.isAnonymous && val._parent)
585
+ val = val._parent;
586
+ return val;
587
+ }
588
+ get parent() {
589
+ return this._parent ? this._parent.nextSignificantParent() : null;
590
+ }
591
+ get nextSibling() {
592
+ return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* DontCare */) : null;
593
+ }
594
+ get prevSibling() {
595
+ return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* DontCare */) : null;
596
+ }
597
+ cursor(mode = 0) { return new TreeCursor(this, mode); }
598
+ get tree() { return this._tree; }
599
+ toTree() { return this._tree; }
600
+ resolve(pos, side = 0) {
601
+ return resolveNode(this, pos, side, false);
602
+ }
603
+ resolveInner(pos, side = 0) {
604
+ return resolveNode(this, pos, side, true);
605
+ }
606
+ enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }
607
+ getChild(type, before = null, after = null) {
608
+ let r = getChildren(this, type, before, after);
609
+ return r.length ? r[0] : null;
610
+ }
611
+ getChildren(type, before = null, after = null) {
612
+ return getChildren(this, type, before, after);
613
+ }
614
+ /// @internal
615
+ toString() { return this._tree.toString(); }
616
+ get node() { return this; }
617
+ matchContext(context) { return matchNodeContext(this, context); }
618
+ }
619
+ function getChildren(node, type, before, after) {
620
+ let cur = node.cursor(), result = [];
621
+ if (!cur.firstChild())
622
+ return result;
623
+ if (before != null)
624
+ while (!cur.type.is(before))
625
+ if (!cur.nextSibling())
626
+ return result;
627
+ for (;;) {
628
+ if (after != null && cur.type.is(after))
629
+ return result;
630
+ if (cur.type.is(type))
631
+ result.push(cur.node);
632
+ if (!cur.nextSibling())
633
+ return after == null ? result : [];
634
+ }
635
+ }
636
+ function matchNodeContext(node, context, i = context.length - 1) {
637
+ for (let p = node.parent; i >= 0; p = p.parent) {
638
+ if (!p)
639
+ return false;
640
+ if (!p.type.isAnonymous) {
641
+ if (context[i] && context[i] != p.name)
642
+ return false;
643
+ i--;
644
+ }
645
+ }
646
+ return true;
647
+ }
648
+ class BufferContext {
649
+ constructor(parent, buffer, index, start) {
650
+ this.parent = parent;
651
+ this.buffer = buffer;
652
+ this.index = index;
653
+ this.start = start;
654
+ }
655
+ }
656
+ class BufferNode {
657
+ constructor(context, _parent, index) {
658
+ this.context = context;
659
+ this._parent = _parent;
660
+ this.index = index;
661
+ this.type = context.buffer.set.types[context.buffer.buffer[index]];
662
+ }
663
+ get name() { return this.type.name; }
664
+ get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
665
+ get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
666
+ child(dir, pos, side) {
667
+ let { buffer } = this.context;
668
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
669
+ return index < 0 ? null : new BufferNode(this.context, this, index);
670
+ }
671
+ get firstChild() { return this.child(1, 0, 4 /* DontCare */); }
672
+ get lastChild() { return this.child(-1, 0, 4 /* DontCare */); }
673
+ childAfter(pos) { return this.child(1, pos, 2 /* After */); }
674
+ childBefore(pos) { return this.child(-1, pos, -2 /* Before */); }
675
+ enter(pos, side, mode = 0) {
676
+ if (mode & IterMode.ExcludeBuffers)
677
+ return null;
678
+ let { buffer } = this.context;
679
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
680
+ return index < 0 ? null : new BufferNode(this.context, this, index);
681
+ }
682
+ get parent() {
683
+ return this._parent || this.context.parent.nextSignificantParent();
684
+ }
685
+ externalSibling(dir) {
686
+ return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* DontCare */);
687
+ }
688
+ get nextSibling() {
689
+ let { buffer } = this.context;
690
+ let after = buffer.buffer[this.index + 3];
691
+ if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
692
+ return new BufferNode(this.context, this._parent, after);
693
+ return this.externalSibling(1);
694
+ }
695
+ get prevSibling() {
696
+ let { buffer } = this.context;
697
+ let parentStart = this._parent ? this._parent.index + 4 : 0;
698
+ if (this.index == parentStart)
699
+ return this.externalSibling(-1);
700
+ return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */));
701
+ }
702
+ cursor(mode = 0) { return new TreeCursor(this, mode); }
703
+ get tree() { return null; }
704
+ toTree() {
705
+ let children = [], positions = [];
706
+ let { buffer } = this.context;
707
+ let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
708
+ if (endI > startI) {
709
+ let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2];
710
+ children.push(buffer.slice(startI, endI, from, to));
711
+ positions.push(0);
712
+ }
713
+ return new Tree(this.type, children, positions, this.to - this.from);
714
+ }
715
+ resolve(pos, side = 0) {
716
+ return resolveNode(this, pos, side, false);
717
+ }
718
+ resolveInner(pos, side = 0) {
719
+ return resolveNode(this, pos, side, true);
720
+ }
721
+ enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }
722
+ /// @internal
723
+ toString() { return this.context.buffer.childString(this.index); }
724
+ getChild(type, before = null, after = null) {
725
+ let r = getChildren(this, type, before, after);
726
+ return r.length ? r[0] : null;
727
+ }
728
+ getChildren(type, before = null, after = null) {
729
+ return getChildren(this, type, before, after);
730
+ }
731
+ get node() { return this; }
732
+ matchContext(context) { return matchNodeContext(this, context); }
733
+ }
734
+ /// A tree cursor object focuses on a given node in a syntax tree, and
735
+ /// allows you to move to adjacent nodes.
736
+ class TreeCursor {
737
+ /// @internal
738
+ constructor(node,
739
+ /// @internal
740
+ mode = 0) {
741
+ this.mode = mode;
742
+ /// @internal
743
+ this.buffer = null;
744
+ this.stack = [];
745
+ /// @internal
746
+ this.index = 0;
747
+ this.bufferNode = null;
748
+ if (node instanceof TreeNode) {
749
+ this.yieldNode(node);
750
+ }
751
+ else {
752
+ this._tree = node.context.parent;
753
+ this.buffer = node.context;
754
+ for (let n = node._parent; n; n = n._parent)
755
+ this.stack.unshift(n.index);
756
+ this.bufferNode = node;
757
+ this.yieldBuf(node.index);
758
+ }
759
+ }
760
+ /// Shorthand for `.type.name`.
761
+ get name() { return this.type.name; }
762
+ yieldNode(node) {
763
+ if (!node)
764
+ return false;
765
+ this._tree = node;
766
+ this.type = node.type;
767
+ this.from = node.from;
768
+ this.to = node.to;
769
+ return true;
770
+ }
771
+ yieldBuf(index, type) {
772
+ this.index = index;
773
+ let { start, buffer } = this.buffer;
774
+ this.type = type || buffer.set.types[buffer.buffer[index]];
775
+ this.from = start + buffer.buffer[index + 1];
776
+ this.to = start + buffer.buffer[index + 2];
777
+ return true;
778
+ }
779
+ yield(node) {
780
+ if (!node)
781
+ return false;
782
+ if (node instanceof TreeNode) {
783
+ this.buffer = null;
784
+ return this.yieldNode(node);
785
+ }
786
+ this.buffer = node.context;
787
+ return this.yieldBuf(node.index, node.type);
788
+ }
789
+ /// @internal
790
+ toString() {
791
+ return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
792
+ }
793
+ /// @internal
794
+ enterChild(dir, pos, side) {
795
+ if (!this.buffer)
796
+ return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
797
+ let { buffer } = this.buffer;
798
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
799
+ if (index < 0)
800
+ return false;
801
+ this.stack.push(this.index);
802
+ return this.yieldBuf(index);
803
+ }
804
+ /// Move the cursor to this node's first child. When this returns
805
+ /// false, the node has no child, and the cursor has not been moved.
806
+ firstChild() { return this.enterChild(1, 0, 4 /* DontCare */); }
807
+ /// Move the cursor to this node's last child.
808
+ lastChild() { return this.enterChild(-1, 0, 4 /* DontCare */); }
809
+ /// Move the cursor to the first child that ends after `pos`.
810
+ childAfter(pos) { return this.enterChild(1, pos, 2 /* After */); }
811
+ /// Move to the last child that starts before `pos`.
812
+ childBefore(pos) { return this.enterChild(-1, pos, -2 /* Before */); }
813
+ /// Move the cursor to the child around `pos`. If side is -1 the
814
+ /// child may end at that position, when 1 it may start there. This
815
+ /// will also enter [overlaid](#common.MountedTree.overlay)
816
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
817
+ /// set to false.
818
+ enter(pos, side, mode = this.mode) {
819
+ if (!this.buffer)
820
+ return this.yield(this._tree.enter(pos, side, mode));
821
+ return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
822
+ }
823
+ /// Move to the node's parent node, if this isn't the top node.
824
+ parent() {
825
+ if (!this.buffer)
826
+ return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);
827
+ if (this.stack.length)
828
+ return this.yieldBuf(this.stack.pop());
829
+ let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
830
+ this.buffer = null;
831
+ return this.yieldNode(parent);
832
+ }
833
+ /// @internal
834
+ sibling(dir) {
835
+ if (!this.buffer)
836
+ return !this._tree._parent ? false
837
+ : this.yield(this._tree.index < 0 ? null
838
+ : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* DontCare */, this.mode));
839
+ let { buffer } = this.buffer, d = this.stack.length - 1;
840
+ if (dir < 0) {
841
+ let parentStart = d < 0 ? 0 : this.stack[d] + 4;
842
+ if (this.index != parentStart)
843
+ return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* DontCare */));
844
+ }
845
+ else {
846
+ let after = buffer.buffer[this.index + 3];
847
+ if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
848
+ return this.yieldBuf(after);
849
+ }
850
+ return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* DontCare */, this.mode)) : false;
851
+ }
852
+ /// Move to this node's next sibling, if any.
853
+ nextSibling() { return this.sibling(1); }
854
+ /// Move to this node's previous sibling, if any.
855
+ prevSibling() { return this.sibling(-1); }
856
+ atLastNode(dir) {
857
+ let index, parent, { buffer } = this;
858
+ if (buffer) {
859
+ if (dir > 0) {
860
+ if (this.index < buffer.buffer.buffer.length)
861
+ return false;
862
+ }
863
+ else {
864
+ for (let i = 0; i < this.index; i++)
865
+ if (buffer.buffer.buffer[i + 3] < this.index)
866
+ return false;
867
+ }
868
+ ({ index, parent } = buffer);
869
+ }
870
+ else {
871
+ ({ index, _parent: parent } = this._tree);
872
+ }
873
+ for (; parent; { index, _parent: parent } = parent) {
874
+ if (index > -1)
875
+ for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
876
+ let child = parent._tree.children[i];
877
+ if ((this.mode & IterMode.IncludeAnonymous) ||
878
+ child instanceof TreeBuffer ||
879
+ !child.type.isAnonymous ||
880
+ hasChild(child))
881
+ return false;
882
+ }
883
+ }
884
+ return true;
885
+ }
886
+ move(dir, enter) {
887
+ if (enter && this.enterChild(dir, 0, 4 /* DontCare */))
888
+ return true;
889
+ for (;;) {
890
+ if (this.sibling(dir))
891
+ return true;
892
+ if (this.atLastNode(dir) || !this.parent())
893
+ return false;
894
+ }
895
+ }
896
+ /// Move to the next node in a
897
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
898
+ /// traversal, going from a node to its first child or, if the
899
+ /// current node is empty or `enter` is false, its next sibling or
900
+ /// the next sibling of the first parent node that has one.
901
+ next(enter = true) { return this.move(1, enter); }
902
+ /// Move to the next node in a last-to-first pre-order traveral. A
903
+ /// node is followed by its last child or, if it has none, its
904
+ /// previous sibling or the previous sibling of the first parent
905
+ /// node that has one.
906
+ prev(enter = true) { return this.move(-1, enter); }
907
+ /// Move the cursor to the innermost node that covers `pos`. If
908
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
909
+ /// it will enter nodes that start at `pos`.
910
+ moveTo(pos, side = 0) {
911
+ // Move up to a node that actually holds the position, if possible
912
+ while (this.from == this.to ||
913
+ (side < 1 ? this.from >= pos : this.from > pos) ||
914
+ (side > -1 ? this.to <= pos : this.to < pos))
915
+ if (!this.parent())
916
+ break;
917
+ // Then scan down into child nodes as far as possible
918
+ while (this.enterChild(1, pos, side)) { }
919
+ return this;
920
+ }
921
+ /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
922
+ /// position.
923
+ get node() {
924
+ if (!this.buffer)
925
+ return this._tree;
926
+ let cache = this.bufferNode, result = null, depth = 0;
927
+ if (cache && cache.context == this.buffer) {
928
+ scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
929
+ for (let c = cache; c; c = c._parent)
930
+ if (c.index == index) {
931
+ if (index == this.index)
932
+ return c;
933
+ result = c;
934
+ depth = d + 1;
935
+ break scan;
936
+ }
937
+ index = this.stack[--d];
938
+ }
939
+ }
940
+ for (let i = depth; i < this.stack.length; i++)
941
+ result = new BufferNode(this.buffer, result, this.stack[i]);
942
+ return this.bufferNode = new BufferNode(this.buffer, result, this.index);
943
+ }
944
+ /// Get the [tree](#common.Tree) that represents the current node, if
945
+ /// any. Will return null when the node is in a [tree
946
+ /// buffer](#common.TreeBuffer).
947
+ get tree() {
948
+ return this.buffer ? null : this._tree._tree;
949
+ }
950
+ /// Iterate over the current node and all its descendants, calling
951
+ /// `enter` when entering a node and `leave`, if given, when leaving
952
+ /// one. When `enter` returns `false`, any children of that node are
953
+ /// skipped, and `leave` isn't called for it.
954
+ iterate(enter, leave) {
955
+ for (let depth = 0;;) {
956
+ let mustLeave = false;
957
+ if (this.type.isAnonymous || enter(this) !== false) {
958
+ if (this.firstChild()) {
959
+ depth++;
960
+ continue;
961
+ }
962
+ if (!this.type.isAnonymous)
963
+ mustLeave = true;
964
+ }
965
+ for (;;) {
966
+ if (mustLeave && leave)
967
+ leave(this);
968
+ mustLeave = this.type.isAnonymous;
969
+ if (this.nextSibling())
970
+ break;
971
+ if (!depth)
972
+ return;
973
+ this.parent();
974
+ depth--;
975
+ mustLeave = true;
976
+ }
977
+ }
978
+ }
979
+ /// Test whether the current node matches a given context—a sequence
980
+ /// of direct parent node names. Empty strings in the context array
981
+ /// are treated as wildcards.
982
+ matchContext(context) {
983
+ if (!this.buffer)
984
+ return matchNodeContext(this.node, context);
985
+ let { buffer } = this.buffer, { types } = buffer.set;
986
+ for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
987
+ if (d < 0)
988
+ return matchNodeContext(this.node, context, i);
989
+ let type = types[buffer.buffer[this.stack[d]]];
990
+ if (!type.isAnonymous) {
991
+ if (context[i] && context[i] != type.name)
992
+ return false;
993
+ i--;
994
+ }
995
+ }
996
+ return true;
997
+ }
998
+ }
999
+ function hasChild(tree) {
1000
+ return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1001
+ }
1002
+ function buildTree(data) {
1003
+ var _a;
1004
+ let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1005
+ let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1006
+ let types = nodeSet.types;
1007
+ let contextHash = 0, lookAhead = 0;
1008
+ function takeNode(parentStart, minPos, children, positions, inRepeat) {
1009
+ let { id, start, end, size } = cursor;
1010
+ let lookAheadAtStart = lookAhead;
1011
+ while (size < 0) {
1012
+ cursor.next();
1013
+ if (size == -1 /* Reuse */) {
1014
+ let node = reused[id];
1015
+ children.push(node);
1016
+ positions.push(start - parentStart);
1017
+ return;
1018
+ }
1019
+ else if (size == -3 /* ContextChange */) { // Context change
1020
+ contextHash = id;
1021
+ return;
1022
+ }
1023
+ else if (size == -4 /* LookAhead */) {
1024
+ lookAhead = id;
1025
+ return;
1026
+ }
1027
+ else {
1028
+ throw new RangeError(`Unrecognized record size: ${size}`);
1029
+ }
1030
+ }
1031
+ let type = types[id], node, buffer;
1032
+ let startPos = start - parentStart;
1033
+ if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
1034
+ // Small enough for a buffer, and no reused nodes inside
1035
+ let data = new Uint16Array(buffer.size - buffer.skip);
1036
+ let endPos = cursor.pos - buffer.size, index = data.length;
1037
+ while (cursor.pos > endPos)
1038
+ index = copyToBuffer(buffer.start, data, index);
1039
+ node = new TreeBuffer(data, end - buffer.start, nodeSet);
1040
+ startPos = buffer.start - parentStart;
1041
+ }
1042
+ else { // Make it a node
1043
+ let endPos = cursor.pos - size;
1044
+ cursor.next();
1045
+ let localChildren = [], localPositions = [];
1046
+ let localInRepeat = id >= minRepeatType ? id : -1;
1047
+ let lastGroup = 0, lastEnd = end;
1048
+ while (cursor.pos > endPos) {
1049
+ if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1050
+ if (cursor.end <= lastEnd - maxBufferLength) {
1051
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
1052
+ lastGroup = localChildren.length;
1053
+ lastEnd = cursor.end;
1054
+ }
1055
+ cursor.next();
1056
+ }
1057
+ else {
1058
+ takeNode(start, endPos, localChildren, localPositions, localInRepeat);
1059
+ }
1060
+ }
1061
+ if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1062
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
1063
+ localChildren.reverse();
1064
+ localPositions.reverse();
1065
+ if (localInRepeat > -1 && lastGroup > 0) {
1066
+ let make = makeBalanced(type);
1067
+ node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1068
+ }
1069
+ else {
1070
+ node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
1071
+ }
1072
+ }
1073
+ children.push(node);
1074
+ positions.push(startPos);
1075
+ }
1076
+ function makeBalanced(type) {
1077
+ return (children, positions, length) => {
1078
+ let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
1079
+ if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
1080
+ if (!lastI && last.type == type && last.length == length)
1081
+ return last;
1082
+ if (lookAheadProp = last.prop(NodeProp.lookAhead))
1083
+ lookAhead = positions[lastI] + last.length + lookAheadProp;
1084
+ }
1085
+ return makeTree(type, children, positions, length, lookAhead);
1086
+ };
1087
+ }
1088
+ function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {
1089
+ let localChildren = [], localPositions = [];
1090
+ while (children.length > i) {
1091
+ localChildren.push(children.pop());
1092
+ localPositions.push(positions.pop() + base - from);
1093
+ }
1094
+ children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));
1095
+ positions.push(from - base);
1096
+ }
1097
+ function makeTree(type, children, positions, length, lookAhead = 0, props) {
1098
+ if (contextHash) {
1099
+ let pair = [NodeProp.contextHash, contextHash];
1100
+ props = props ? [pair].concat(props) : [pair];
1101
+ }
1102
+ if (lookAhead > 25) {
1103
+ let pair = [NodeProp.lookAhead, lookAhead];
1104
+ props = props ? [pair].concat(props) : [pair];
1105
+ }
1106
+ return new Tree(type, children, positions, length, props);
1107
+ }
1108
+ function findBufferSize(maxSize, inRepeat) {
1109
+ // Scan through the buffer to find previous siblings that fit
1110
+ // together in a TreeBuffer, and don't contain any reused nodes
1111
+ // (which can't be stored in a buffer).
1112
+ // If `inRepeat` is > -1, ignore node boundaries of that type for
1113
+ // nesting, but make sure the end falls either at the start
1114
+ // (`maxSize`) or before such a node.
1115
+ let fork = cursor.fork();
1116
+ let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1117
+ let result = { size: 0, start: 0, skip: 0 };
1118
+ scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
1119
+ let nodeSize = fork.size;
1120
+ // Pretend nested repeat nodes of the same type don't exist
1121
+ if (fork.id == inRepeat && nodeSize >= 0) {
1122
+ // Except that we store the current state as a valid return
1123
+ // value.
1124
+ result.size = size;
1125
+ result.start = start;
1126
+ result.skip = skip;
1127
+ skip += 4;
1128
+ size += 4;
1129
+ fork.next();
1130
+ continue;
1131
+ }
1132
+ let startPos = fork.pos - nodeSize;
1133
+ if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
1134
+ break;
1135
+ let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1136
+ let nodeStart = fork.start;
1137
+ fork.next();
1138
+ while (fork.pos > startPos) {
1139
+ if (fork.size < 0) {
1140
+ if (fork.size == -3 /* ContextChange */)
1141
+ localSkipped += 4;
1142
+ else
1143
+ break scan;
1144
+ }
1145
+ else if (fork.id >= minRepeatType) {
1146
+ localSkipped += 4;
1147
+ }
1148
+ fork.next();
1149
+ }
1150
+ start = nodeStart;
1151
+ size += nodeSize;
1152
+ skip += localSkipped;
1153
+ }
1154
+ if (inRepeat < 0 || size == maxSize) {
1155
+ result.size = size;
1156
+ result.start = start;
1157
+ result.skip = skip;
1158
+ }
1159
+ return result.size > 4 ? result : undefined;
1160
+ }
1161
+ function copyToBuffer(bufferStart, buffer, index) {
1162
+ let { id, start, end, size } = cursor;
1163
+ cursor.next();
1164
+ if (size >= 0 && id < minRepeatType) {
1165
+ let startIndex = index;
1166
+ if (size > 4) {
1167
+ let endPos = cursor.pos - (size - 4);
1168
+ while (cursor.pos > endPos)
1169
+ index = copyToBuffer(bufferStart, buffer, index);
1170
+ }
1171
+ buffer[--index] = startIndex;
1172
+ buffer[--index] = end - bufferStart;
1173
+ buffer[--index] = start - bufferStart;
1174
+ buffer[--index] = id;
1175
+ }
1176
+ else if (size == -3 /* ContextChange */) {
1177
+ contextHash = id;
1178
+ }
1179
+ else if (size == -4 /* LookAhead */) {
1180
+ lookAhead = id;
1181
+ }
1182
+ return index;
1183
+ }
1184
+ let children = [], positions = [];
1185
+ while (cursor.pos > 0)
1186
+ takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1187
+ let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
1188
+ return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1189
+ }
1190
+ const nodeSizeCache = new WeakMap;
1191
+ function nodeSize(balanceType, node) {
1192
+ if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1193
+ return 1;
1194
+ let size = nodeSizeCache.get(node);
1195
+ if (size == null) {
1196
+ size = 1;
1197
+ for (let child of node.children) {
1198
+ if (child.type != balanceType || !(child instanceof Tree)) {
1199
+ size = 1;
1200
+ break;
1201
+ }
1202
+ size += nodeSize(balanceType, child);
1203
+ }
1204
+ nodeSizeCache.set(node, size);
1205
+ }
1206
+ return size;
1207
+ }
1208
+ function balanceRange(
1209
+ // The type the balanced tree's inner nodes.
1210
+ balanceType,
1211
+ // The direct children and their positions
1212
+ children, positions,
1213
+ // The index range in children/positions to use
1214
+ from, to,
1215
+ // The start position of the nodes, relative to their parent.
1216
+ start,
1217
+ // Length of the outer node
1218
+ length,
1219
+ // Function to build the top node of the balanced tree
1220
+ mkTop,
1221
+ // Function to build internal nodes for the balanced tree
1222
+ mkTree) {
1223
+ let total = 0;
1224
+ for (let i = from; i < to; i++)
1225
+ total += nodeSize(balanceType, children[i]);
1226
+ let maxChild = Math.ceil((total * 1.5) / 8 /* BranchFactor */);
1227
+ let localChildren = [], localPositions = [];
1228
+ function divide(children, positions, from, to, offset) {
1229
+ for (let i = from; i < to;) {
1230
+ let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
1231
+ i++;
1232
+ for (; i < to; i++) {
1233
+ let nextSize = nodeSize(balanceType, children[i]);
1234
+ if (groupSize + nextSize >= maxChild)
1235
+ break;
1236
+ groupSize += nextSize;
1237
+ }
1238
+ if (i == groupFrom + 1) {
1239
+ if (groupSize > maxChild) {
1240
+ let only = children[groupFrom]; // Only trees can have a size > 1
1241
+ divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
1242
+ continue;
1243
+ }
1244
+ localChildren.push(children[groupFrom]);
1245
+ }
1246
+ else {
1247
+ let length = positions[i - 1] + children[i - 1].length - groupStart;
1248
+ localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
1249
+ }
1250
+ localPositions.push(groupStart + offset - start);
1251
+ }
1252
+ }
1253
+ divide(children, positions, from, to, 0);
1254
+ return (mkTop || mkTree)(localChildren, localPositions, length);
1255
+ }
1256
+ /// Provides a way to associate values with pieces of trees. As long
1257
+ /// as that part of the tree is reused, the associated values can be
1258
+ /// retrieved from an updated tree.
1259
+ class NodeWeakMap {
1260
+ constructor() {
1261
+ this.map = new WeakMap();
1262
+ }
1263
+ setBuffer(buffer, index, value) {
1264
+ let inner = this.map.get(buffer);
1265
+ if (!inner)
1266
+ this.map.set(buffer, inner = new Map);
1267
+ inner.set(index, value);
1268
+ }
1269
+ getBuffer(buffer, index) {
1270
+ let inner = this.map.get(buffer);
1271
+ return inner && inner.get(index);
1272
+ }
1273
+ /// Set the value for this syntax node.
1274
+ set(node, value) {
1275
+ if (node instanceof BufferNode)
1276
+ this.setBuffer(node.context.buffer, node.index, value);
1277
+ else if (node instanceof TreeNode)
1278
+ this.map.set(node.tree, value);
1279
+ }
1280
+ /// Retrieve value for this syntax node, if it exists in the map.
1281
+ get(node) {
1282
+ return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)
1283
+ : node instanceof TreeNode ? this.map.get(node.tree) : undefined;
1284
+ }
1285
+ /// Set the value for the node that a cursor currently points to.
1286
+ cursorSet(cursor, value) {
1287
+ if (cursor.buffer)
1288
+ this.setBuffer(cursor.buffer.buffer, cursor.index, value);
1289
+ else
1290
+ this.map.set(cursor.tree, value);
1291
+ }
1292
+ /// Retrieve the value for the node that a cursor currently points
1293
+ /// to.
1294
+ cursorGet(cursor) {
1295
+ return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
1296
+ }
1297
+ }
1298
+
1299
+ /// Tree fragments are used during [incremental
1300
+ /// parsing](#common.Parser.startParse) to track parts of old trees
1301
+ /// that can be reused in a new parse. An array of fragments is used
1302
+ /// to track regions of an old tree whose nodes might be reused in new
1303
+ /// parses. Use the static
1304
+ /// [`applyChanges`](#common.TreeFragment^applyChanges) method to
1305
+ /// update fragments for document changes.
1306
+ class TreeFragment {
1307
+ /// Construct a tree fragment.
1308
+ constructor(
1309
+ /// The start of the unchanged range pointed to by this fragment.
1310
+ /// This refers to an offset in the _updated_ document (as opposed
1311
+ /// to the original tree).
1312
+ from,
1313
+ /// The end of the unchanged range.
1314
+ to,
1315
+ /// The tree that this fragment is based on.
1316
+ tree,
1317
+ /// The offset between the fragment's tree and the document that
1318
+ /// this fragment can be used against. Add this when going from
1319
+ /// document to tree positions, subtract it to go from tree to
1320
+ /// document positions.
1321
+ offset, openStart = false, openEnd = false) {
1322
+ this.from = from;
1323
+ this.to = to;
1324
+ this.tree = tree;
1325
+ this.offset = offset;
1326
+ this.open = (openStart ? 1 /* Start */ : 0) | (openEnd ? 2 /* End */ : 0);
1327
+ }
1328
+ /// Whether the start of the fragment represents the start of a
1329
+ /// parse, or the end of a change. (In the second case, it may not
1330
+ /// be safe to reuse some nodes at the start, depending on the
1331
+ /// parsing algorithm.)
1332
+ get openStart() { return (this.open & 1 /* Start */) > 0; }
1333
+ /// Whether the end of the fragment represents the end of a
1334
+ /// full-document parse, or the start of a change.
1335
+ get openEnd() { return (this.open & 2 /* End */) > 0; }
1336
+ /// Create a set of fragments from a freshly parsed tree, or update
1337
+ /// an existing set of fragments by replacing the ones that overlap
1338
+ /// with a tree with content from the new tree. When `partial` is
1339
+ /// true, the parse is treated as incomplete, and the resulting
1340
+ /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
1341
+ /// true.
1342
+ static addTree(tree, fragments = [], partial = false) {
1343
+ let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
1344
+ for (let f of fragments)
1345
+ if (f.to > tree.length)
1346
+ result.push(f);
1347
+ return result;
1348
+ }
1349
+ /// Apply a set of edits to an array of fragments, removing or
1350
+ /// splitting fragments as necessary to remove edited ranges, and
1351
+ /// adjusting offsets for fragments that moved.
1352
+ static applyChanges(fragments, changes, minGap = 128) {
1353
+ if (!changes.length)
1354
+ return fragments;
1355
+ let result = [];
1356
+ let fI = 1, nextF = fragments.length ? fragments[0] : null;
1357
+ for (let cI = 0, pos = 0, off = 0;; cI++) {
1358
+ let nextC = cI < changes.length ? changes[cI] : null;
1359
+ let nextPos = nextC ? nextC.fromA : 1e9;
1360
+ if (nextPos - pos >= minGap)
1361
+ while (nextF && nextF.from < nextPos) {
1362
+ let cut = nextF;
1363
+ if (pos >= cut.from || nextPos <= cut.to || off) {
1364
+ let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
1365
+ cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
1366
+ }
1367
+ if (cut)
1368
+ result.push(cut);
1369
+ if (nextF.to > nextPos)
1370
+ break;
1371
+ nextF = fI < fragments.length ? fragments[fI++] : null;
1372
+ }
1373
+ if (!nextC)
1374
+ break;
1375
+ pos = nextC.toA;
1376
+ off = nextC.toA - nextC.toB;
1377
+ }
1378
+ return result;
1379
+ }
1380
+ }
1381
+ /// A superclass that parsers should extend.
1382
+ class Parser {
1383
+ /// Start a parse, returning a [partial parse](#common.PartialParse)
1384
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
1385
+ /// make the parse incremental.
1386
+ ///
1387
+ /// By default, the entire input is parsed. You can pass `ranges`,
1388
+ /// which should be a sorted array of non-empty, non-overlapping
1389
+ /// ranges, to parse only those ranges. The tree returned in that
1390
+ /// case will start at `ranges[0].from`.
1391
+ startParse(input, fragments, ranges) {
1392
+ if (typeof input == "string")
1393
+ input = new StringInput(input);
1394
+ ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];
1395
+ return this.createParse(input, fragments || [], ranges);
1396
+ }
1397
+ /// Run a full parse, returning the resulting tree.
1398
+ parse(input, fragments, ranges) {
1399
+ let parse = this.startParse(input, fragments, ranges);
1400
+ for (;;) {
1401
+ let done = parse.advance();
1402
+ if (done)
1403
+ return done;
1404
+ }
1405
+ }
1406
+ }
1407
+ class StringInput {
1408
+ constructor(string) {
1409
+ this.string = string;
1410
+ }
1411
+ get length() { return this.string.length; }
1412
+ chunk(from) { return this.string.slice(from); }
1413
+ get lineChunks() { return false; }
1414
+ read(from, to) { return this.string.slice(from, to); }
1415
+ }
1416
+
1417
+ /// Create a parse wrapper that, after the inner parse completes,
1418
+ /// scans its tree for mixed language regions with the `nest`
1419
+ /// function, runs the resulting [inner parses](#common.NestedParse),
1420
+ /// and then [mounts](#common.NodeProp^mounted) their results onto the
1421
+ /// tree.
1422
+ ///
1423
+ /// The nesting function is passed a cursor to provide context for a
1424
+ /// node, but _should not_ move that cursor, only inspect its
1425
+ /// properties and optionally access its
1426
+ /// [node object](#common.TreeCursor.node).
1427
+ function parseMixed(nest) {
1428
+ return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
1429
+ }
1430
+ class InnerParse {
1431
+ constructor(parser, parse, overlay, target, ranges) {
1432
+ this.parser = parser;
1433
+ this.parse = parse;
1434
+ this.overlay = overlay;
1435
+ this.target = target;
1436
+ this.ranges = ranges;
1437
+ }
1438
+ }
1439
+ class ActiveOverlay {
1440
+ constructor(parser, predicate, mounts, index, start, target, prev) {
1441
+ this.parser = parser;
1442
+ this.predicate = predicate;
1443
+ this.mounts = mounts;
1444
+ this.index = index;
1445
+ this.start = start;
1446
+ this.target = target;
1447
+ this.prev = prev;
1448
+ this.depth = 0;
1449
+ this.ranges = [];
1450
+ }
1451
+ }
1452
+ const stoppedInner = new NodeProp({ perNode: true });
1453
+ class MixedParse {
1454
+ constructor(base, nest, input, fragments, ranges) {
1455
+ this.nest = nest;
1456
+ this.input = input;
1457
+ this.fragments = fragments;
1458
+ this.ranges = ranges;
1459
+ this.inner = [];
1460
+ this.innerDone = 0;
1461
+ this.baseTree = null;
1462
+ this.stoppedAt = null;
1463
+ this.baseParse = base;
1464
+ }
1465
+ advance() {
1466
+ if (this.baseParse) {
1467
+ let done = this.baseParse.advance();
1468
+ if (!done)
1469
+ return null;
1470
+ this.baseParse = null;
1471
+ this.baseTree = done;
1472
+ this.startInner();
1473
+ if (this.stoppedAt != null)
1474
+ for (let inner of this.inner)
1475
+ inner.parse.stopAt(this.stoppedAt);
1476
+ }
1477
+ if (this.innerDone == this.inner.length) {
1478
+ let result = this.baseTree;
1479
+ if (this.stoppedAt != null)
1480
+ result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
1481
+ return result;
1482
+ }
1483
+ let inner = this.inner[this.innerDone], done = inner.parse.advance();
1484
+ if (done) {
1485
+ this.innerDone++;
1486
+ // This is a somewhat dodgy but super helpful hack where we
1487
+ // patch up nodes created by the inner parse (and thus
1488
+ // presumably not aliased anywhere else) to hold the information
1489
+ // about the inner parse.
1490
+ let props = Object.assign(Object.create(null), inner.target.props);
1491
+ props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);
1492
+ inner.target.props = props;
1493
+ }
1494
+ return null;
1495
+ }
1496
+ get parsedPos() {
1497
+ if (this.baseParse)
1498
+ return 0;
1499
+ let pos = this.input.length;
1500
+ for (let i = this.innerDone; i < this.inner.length; i++) {
1501
+ if (this.inner[i].ranges[0].from < pos)
1502
+ pos = Math.min(pos, this.inner[i].parse.parsedPos);
1503
+ }
1504
+ return pos;
1505
+ }
1506
+ stopAt(pos) {
1507
+ this.stoppedAt = pos;
1508
+ if (this.baseParse)
1509
+ this.baseParse.stopAt(pos);
1510
+ else
1511
+ for (let i = this.innerDone; i < this.inner.length; i++)
1512
+ this.inner[i].parse.stopAt(pos);
1513
+ }
1514
+ startInner() {
1515
+ let fragmentCursor = new FragmentCursor(this.fragments);
1516
+ let overlay = null;
1517
+ let covered = null;
1518
+ let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
1519
+ scan: for (let nest, isCovered; this.stoppedAt == null || cursor.from < this.stoppedAt;) {
1520
+ let enter = true, range;
1521
+ if (fragmentCursor.hasNode(cursor)) {
1522
+ if (overlay) {
1523
+ let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
1524
+ if (match)
1525
+ for (let r of match.mount.overlay) {
1526
+ let from = r.from + match.pos, to = r.to + match.pos;
1527
+ if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))
1528
+ overlay.ranges.push({ from, to });
1529
+ }
1530
+ }
1531
+ enter = false;
1532
+ }
1533
+ else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {
1534
+ enter = isCovered != 2 /* Full */;
1535
+ }
1536
+ else if (!cursor.type.isAnonymous && cursor.from < cursor.to && (nest = this.nest(cursor, this.input))) {
1537
+ if (!cursor.tree)
1538
+ materialize(cursor);
1539
+ let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
1540
+ if (typeof nest.overlay == "function") {
1541
+ overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);
1542
+ }
1543
+ else {
1544
+ let ranges = punchRanges(this.ranges, nest.overlay || [new Range(cursor.from, cursor.to)]);
1545
+ if (ranges.length)
1546
+ this.inner.push(new InnerParse(nest.parser, nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges));
1547
+ if (!nest.overlay)
1548
+ enter = false;
1549
+ else if (ranges.length)
1550
+ covered = { ranges, depth: 0, prev: covered };
1551
+ }
1552
+ }
1553
+ else if (overlay && (range = overlay.predicate(cursor))) {
1554
+ if (range === true)
1555
+ range = new Range(cursor.from, cursor.to);
1556
+ if (range.from < range.to)
1557
+ overlay.ranges.push(range);
1558
+ }
1559
+ if (enter && cursor.firstChild()) {
1560
+ if (overlay)
1561
+ overlay.depth++;
1562
+ if (covered)
1563
+ covered.depth++;
1564
+ }
1565
+ else {
1566
+ for (;;) {
1567
+ if (cursor.nextSibling())
1568
+ break;
1569
+ if (!cursor.parent())
1570
+ break scan;
1571
+ if (overlay && !--overlay.depth) {
1572
+ let ranges = punchRanges(this.ranges, overlay.ranges);
1573
+ if (ranges.length)
1574
+ this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges));
1575
+ overlay = overlay.prev;
1576
+ }
1577
+ if (covered && !--covered.depth)
1578
+ covered = covered.prev;
1579
+ }
1580
+ }
1581
+ }
1582
+ }
1583
+ }
1584
+ function checkCover(covered, from, to) {
1585
+ for (let range of covered) {
1586
+ if (range.from >= to)
1587
+ break;
1588
+ if (range.to > from)
1589
+ return range.from <= from && range.to >= to ? 2 /* Full */ : 1 /* Partial */;
1590
+ }
1591
+ return 0 /* None */;
1592
+ }
1593
+ // Take a piece of buffer and convert it into a stand-alone
1594
+ // TreeBuffer.
1595
+ function sliceBuf(buf, startI, endI, nodes, positions, off) {
1596
+ if (startI < endI) {
1597
+ let from = buf.buffer[startI + 1], to = buf.buffer[endI - 2];
1598
+ nodes.push(buf.slice(startI, endI, from, to));
1599
+ positions.push(from - off);
1600
+ }
1601
+ }
1602
+ // This function takes a node that's in a buffer, and converts it, and
1603
+ // its parent buffer nodes, into a Tree. This is again acting on the
1604
+ // assumption that the trees and buffers have been constructed by the
1605
+ // parse that was ran via the mix parser, and thus aren't shared with
1606
+ // any other code, making violations of the immutability safe.
1607
+ function materialize(cursor) {
1608
+ let { node } = cursor, depth = 0;
1609
+ // Scan up to the nearest tree
1610
+ do {
1611
+ cursor.parent();
1612
+ depth++;
1613
+ } while (!cursor.tree);
1614
+ // Find the index of the buffer in that tree
1615
+ let i = 0, base = cursor.tree, off = 0;
1616
+ for (;; i++) {
1617
+ off = base.positions[i] + cursor.from;
1618
+ if (off <= node.from && off + base.children[i].length >= node.to)
1619
+ break;
1620
+ }
1621
+ let buf = base.children[i], b = buf.buffer;
1622
+ // Split a level in the buffer, putting the nodes before and after
1623
+ // the child that contains `node` into new buffers.
1624
+ function split(startI, endI, type, innerOffset, length) {
1625
+ let i = startI;
1626
+ while (b[i + 2] + off <= node.from)
1627
+ i = b[i + 3];
1628
+ let children = [], positions = [];
1629
+ sliceBuf(buf, startI, i, children, positions, innerOffset);
1630
+ let from = b[i + 1], to = b[i + 2];
1631
+ let isTarget = from + off == node.from && to + off == node.to && b[i] == node.type.id;
1632
+ children.push(isTarget ? node.toTree() : split(i + 4, b[i + 3], buf.set.types[b[i]], from, to - from));
1633
+ positions.push(from - innerOffset);
1634
+ sliceBuf(buf, b[i + 3], endI, children, positions, innerOffset);
1635
+ return new Tree(type, children, positions, length);
1636
+ }
1637
+ base.children[i] = split(0, b.length, NodeType.none, 0, buf.length);
1638
+ // Move the cursor back to the target node
1639
+ for (let d = 0; d <= depth; d++)
1640
+ cursor.childAfter(node.from);
1641
+ }
1642
+ class StructureCursor {
1643
+ constructor(root, offset) {
1644
+ this.offset = offset;
1645
+ this.done = false;
1646
+ this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
1647
+ }
1648
+ // Move to the first node (in pre-order) that starts at or after `pos`.
1649
+ moveTo(pos) {
1650
+ let { cursor } = this, p = pos - this.offset;
1651
+ while (!this.done && cursor.from < p) {
1652
+ if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;
1653
+ else if (!cursor.next(false))
1654
+ this.done = true;
1655
+ }
1656
+ }
1657
+ hasNode(cursor) {
1658
+ this.moveTo(cursor.from);
1659
+ if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {
1660
+ for (let tree = this.cursor.tree;;) {
1661
+ if (tree == cursor.tree)
1662
+ return true;
1663
+ if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)
1664
+ tree = tree.children[0];
1665
+ else
1666
+ break;
1667
+ }
1668
+ }
1669
+ return false;
1670
+ }
1671
+ }
1672
+ class FragmentCursor {
1673
+ constructor(fragments) {
1674
+ var _a;
1675
+ this.fragments = fragments;
1676
+ this.curTo = 0;
1677
+ this.fragI = 0;
1678
+ if (fragments.length) {
1679
+ let first = this.curFrag = fragments[0];
1680
+ this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;
1681
+ this.inner = new StructureCursor(first.tree, -first.offset);
1682
+ }
1683
+ else {
1684
+ this.curFrag = this.inner = null;
1685
+ }
1686
+ }
1687
+ hasNode(node) {
1688
+ while (this.curFrag && node.from >= this.curTo)
1689
+ this.nextFrag();
1690
+ return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
1691
+ }
1692
+ nextFrag() {
1693
+ var _a;
1694
+ this.fragI++;
1695
+ if (this.fragI == this.fragments.length) {
1696
+ this.curFrag = this.inner = null;
1697
+ }
1698
+ else {
1699
+ let frag = this.curFrag = this.fragments[this.fragI];
1700
+ this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;
1701
+ this.inner = new StructureCursor(frag.tree, -frag.offset);
1702
+ }
1703
+ }
1704
+ findMounts(pos, parser) {
1705
+ var _a;
1706
+ let result = [];
1707
+ if (this.inner) {
1708
+ this.inner.cursor.moveTo(pos, 1);
1709
+ for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {
1710
+ let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);
1711
+ if (mount && mount.parser == parser) {
1712
+ for (let i = this.fragI; i < this.fragments.length; i++) {
1713
+ let frag = this.fragments[i];
1714
+ if (frag.from >= pos.to)
1715
+ break;
1716
+ if (frag.tree == this.curFrag.tree)
1717
+ result.push({
1718
+ frag,
1719
+ pos: pos.from - frag.offset,
1720
+ mount
1721
+ });
1722
+ }
1723
+ }
1724
+ }
1725
+ }
1726
+ return result;
1727
+ }
1728
+ }
1729
+ function punchRanges(outer, ranges) {
1730
+ let copy = null, current = ranges;
1731
+ for (let i = 1, j = 0; i < outer.length; i++) {
1732
+ let gapFrom = outer[i - 1].to, gapTo = outer[i].from;
1733
+ for (; j < current.length; j++) {
1734
+ let r = current[j];
1735
+ if (r.from >= gapTo)
1736
+ break;
1737
+ if (r.to <= gapFrom)
1738
+ continue;
1739
+ if (!copy)
1740
+ current = copy = ranges.slice();
1741
+ if (r.from < gapFrom) {
1742
+ copy[j] = new Range(r.from, gapFrom);
1743
+ if (r.to > gapTo)
1744
+ copy.splice(j + 1, 0, new Range(gapTo, r.to));
1745
+ }
1746
+ else if (r.to > gapTo) {
1747
+ copy[j--] = new Range(gapTo, r.to);
1748
+ }
1749
+ else {
1750
+ copy.splice(j--, 1);
1751
+ }
1752
+ }
1753
+ }
1754
+ return current;
1755
+ }
1756
+ function findCoverChanges(a, b, from, to) {
1757
+ let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;
1758
+ let result = [];
1759
+ for (;;) {
1760
+ let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
1761
+ let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
1762
+ if (inA != inB) {
1763
+ let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);
1764
+ if (start < end)
1765
+ result.push(new Range(start, end));
1766
+ }
1767
+ pos = Math.min(nextA, nextB);
1768
+ if (pos == 1e9)
1769
+ break;
1770
+ if (nextA == pos) {
1771
+ if (!inA)
1772
+ inA = true;
1773
+ else {
1774
+ inA = false;
1775
+ iA++;
1776
+ }
1777
+ }
1778
+ if (nextB == pos) {
1779
+ if (!inB)
1780
+ inB = true;
1781
+ else {
1782
+ inB = false;
1783
+ iB++;
1784
+ }
1785
+ }
1786
+ }
1787
+ return result;
1788
+ }
1789
+ // Given a number of fragments for the outer tree, and a set of ranges
1790
+ // to parse, find fragments for inner trees mounted around those
1791
+ // ranges, if any.
1792
+ function enterFragments(mounts, ranges) {
1793
+ let result = [];
1794
+ for (let { pos, mount, frag } of mounts) {
1795
+ let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;
1796
+ let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);
1797
+ if (mount.overlay) {
1798
+ let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));
1799
+ let changes = findCoverChanges(ranges, overlay, from, to);
1800
+ for (let i = 0, pos = from;; i++) {
1801
+ let last = i == changes.length, end = last ? to : changes[i].from;
1802
+ if (end > pos)
1803
+ result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos, frag.to <= end));
1804
+ if (last)
1805
+ break;
1806
+ pos = changes[i].to;
1807
+ }
1808
+ }
1809
+ else {
1810
+ result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos, frag.to <= endPos));
1811
+ }
1812
+ }
1813
+ return result;
1814
+ }
1815
+
1816
+ export { DefaultBufferLength, IterMode, MountedTree, NodeProp, NodeSet, NodeType, NodeWeakMap, Parser, Tree, TreeBuffer, TreeCursor, TreeFragment, parseMixed };