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