@vuu-ui/vuu-data-react 0.8.0-debug → 0.8.1-debug

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.js CHANGED
@@ -1,22 +1,3 @@
1
- var __accessCheck = (obj, member, msg) => {
2
- if (!member.has(obj))
3
- throw TypeError("Cannot " + msg);
4
- };
5
- var __privateGet = (obj, member, getter) => {
6
- __accessCheck(obj, member, "read from private field");
7
- return getter ? getter.call(obj) : member.get(obj);
8
- };
9
- var __privateAdd = (obj, member, value) => {
10
- if (member.has(obj))
11
- throw TypeError("Cannot add the same private member more than once");
12
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
- };
14
- var __privateSet = (obj, member, value, setter) => {
15
- __accessCheck(obj, member, "write to private field");
16
- setter ? setter.call(obj, value) : member.set(obj, value);
17
- return value;
18
- };
19
-
20
1
  // src/hooks/useDataSource.ts
21
2
  import { getFullRange, metadataKeys, WindowRange } from "@vuu-ui/vuu-utils";
22
3
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -233,3166 +214,8 @@ var useTypeaheadSuggestions = () => {
233
214
  return getTypeaheadSuggestions;
234
215
  };
235
216
 
236
- // ../../node_modules/@lezer/common/dist/index.js
237
- var DefaultBufferLength = 1024;
238
- var nextPropID = 0;
239
- var Range = class {
240
- constructor(from, to) {
241
- this.from = from;
242
- this.to = to;
243
- }
244
- };
245
- var NodeProp = class {
246
- /// Create a new node prop type.
247
- constructor(config = {}) {
248
- this.id = nextPropID++;
249
- this.perNode = !!config.perNode;
250
- this.deserialize = config.deserialize || (() => {
251
- throw new Error("This node type doesn't define a deserialize function");
252
- });
253
- }
254
- /// This is meant to be used with
255
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
256
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
257
- /// prop values for each node type in the set. Takes a [match
258
- /// object](#common.NodeType^match) or function that returns undefined
259
- /// if the node type doesn't get this prop, and the prop's value if
260
- /// it does.
261
- add(match) {
262
- if (this.perNode)
263
- throw new RangeError("Can't add per-node props to node types");
264
- if (typeof match != "function")
265
- match = NodeType.match(match);
266
- return (type) => {
267
- let result = match(type);
268
- return result === void 0 ? null : [this, result];
269
- };
270
- }
271
- };
272
- NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
273
- NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
274
- NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
275
- NodeProp.contextHash = new NodeProp({ perNode: true });
276
- NodeProp.lookAhead = new NodeProp({ perNode: true });
277
- NodeProp.mounted = new NodeProp({ perNode: true });
278
- var noProps = /* @__PURE__ */ Object.create(null);
279
- var NodeType = class {
280
- /// @internal
281
- constructor(name, props, id, flags = 0) {
282
- this.name = name;
283
- this.props = props;
284
- this.id = id;
285
- this.flags = flags;
286
- }
287
- /// Define a node type.
288
- static define(spec) {
289
- let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
290
- let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
291
- let type = new NodeType(spec.name || "", props, spec.id, flags);
292
- if (spec.props)
293
- for (let src of spec.props) {
294
- if (!Array.isArray(src))
295
- src = src(type);
296
- if (src) {
297
- if (src[0].perNode)
298
- throw new RangeError("Can't store a per-node prop on a node type");
299
- props[src[0].id] = src[1];
300
- }
301
- }
302
- return type;
303
- }
304
- /// Retrieves a node prop for this type. Will return `undefined` if
305
- /// the prop isn't present on this node.
306
- prop(prop) {
307
- return this.props[prop.id];
308
- }
309
- /// True when this is the top node of a grammar.
310
- get isTop() {
311
- return (this.flags & 1) > 0;
312
- }
313
- /// True when this node is produced by a skip rule.
314
- get isSkipped() {
315
- return (this.flags & 2) > 0;
316
- }
317
- /// Indicates whether this is an error node.
318
- get isError() {
319
- return (this.flags & 4) > 0;
320
- }
321
- /// When true, this node type doesn't correspond to a user-declared
322
- /// named node, for example because it is used to cache repetition.
323
- get isAnonymous() {
324
- return (this.flags & 8) > 0;
325
- }
326
- /// Returns true when this node's name or one of its
327
- /// [groups](#common.NodeProp^group) matches the given string.
328
- is(name) {
329
- if (typeof name == "string") {
330
- if (this.name == name)
331
- return true;
332
- let group = this.prop(NodeProp.group);
333
- return group ? group.indexOf(name) > -1 : false;
334
- }
335
- return this.id == name;
336
- }
337
- /// Create a function from node types to arbitrary values by
338
- /// specifying an object whose property names are node or
339
- /// [group](#common.NodeProp^group) names. Often useful with
340
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
341
- /// names, separated by spaces, in a single property name to map
342
- /// multiple node names to a single value.
343
- static match(map) {
344
- let direct = /* @__PURE__ */ Object.create(null);
345
- for (let prop in map)
346
- for (let name of prop.split(" "))
347
- direct[name] = map[prop];
348
- return (node) => {
349
- for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
350
- let found = direct[i < 0 ? node.name : groups[i]];
351
- if (found)
352
- return found;
353
- }
354
- };
355
- }
356
- };
357
- NodeType.none = new NodeType(
358
- "",
359
- /* @__PURE__ */ Object.create(null),
360
- 0,
361
- 8
362
- /* NodeFlag.Anonymous */
363
- );
364
- var NodeSet = class {
365
- /// Create a set with the given types. The `id` property of each
366
- /// type should correspond to its position within the array.
367
- constructor(types) {
368
- this.types = types;
369
- for (let i = 0; i < types.length; i++)
370
- if (types[i].id != i)
371
- throw new RangeError("Node type ids should correspond to array positions when creating a node set");
372
- }
373
- /// Create a copy of this set with some node properties added. The
374
- /// arguments to this method can be created with
375
- /// [`NodeProp.add`](#common.NodeProp.add).
376
- extend(...props) {
377
- let newTypes = [];
378
- for (let type of this.types) {
379
- let newProps = null;
380
- for (let source of props) {
381
- let add = source(type);
382
- if (add) {
383
- if (!newProps)
384
- newProps = Object.assign({}, type.props);
385
- newProps[add[0].id] = add[1];
386
- }
387
- }
388
- newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
389
- }
390
- return new NodeSet(newTypes);
391
- }
392
- };
393
- var CachedNode = /* @__PURE__ */ new WeakMap();
394
- var CachedInnerNode = /* @__PURE__ */ new WeakMap();
395
- var IterMode;
396
- (function(IterMode2) {
397
- IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
398
- IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
399
- IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
400
- IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
401
- })(IterMode || (IterMode = {}));
402
- var Tree = class {
403
- /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
404
- constructor(type, children, positions, length, props) {
405
- this.type = type;
406
- this.children = children;
407
- this.positions = positions;
408
- this.length = length;
409
- this.props = null;
410
- if (props && props.length) {
411
- this.props = /* @__PURE__ */ Object.create(null);
412
- for (let [prop, value] of props)
413
- this.props[typeof prop == "number" ? prop : prop.id] = value;
414
- }
415
- }
416
- /// @internal
417
- toString() {
418
- let mounted = this.prop(NodeProp.mounted);
419
- if (mounted && !mounted.overlay)
420
- return mounted.tree.toString();
421
- let children = "";
422
- for (let ch of this.children) {
423
- let str = ch.toString();
424
- if (str) {
425
- if (children)
426
- children += ",";
427
- children += str;
428
- }
429
- }
430
- return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
431
- }
432
- /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
433
- /// the tree. Mode can be used to [control](#common.IterMode) which
434
- /// nodes the cursor visits.
435
- cursor(mode = 0) {
436
- return new TreeCursor(this.topNode, mode);
437
- }
438
- /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
439
- /// at the given position and side (see
440
- /// [`moveTo`](#common.TreeCursor.moveTo).
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
- /// Get a [syntax node](#common.SyntaxNode) object for the top of the
449
- /// tree.
450
- get topNode() {
451
- return new TreeNode(this, 0, 0, null);
452
- }
453
- /// Get the [syntax node](#common.SyntaxNode) at the given position.
454
- /// If `side` is -1, this will move into nodes that end at the
455
- /// position. If 1, it'll move into nodes that start at the
456
- /// position. With 0, it'll only enter nodes that cover the position
457
- /// from both sides.
458
- ///
459
- /// Note that this will not enter
460
- /// [overlays](#common.MountedTree.overlay), and you often want
461
- /// [`resolveInner`](#common.Tree.resolveInner) instead.
462
- resolve(pos, side = 0) {
463
- let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
464
- CachedNode.set(this, node);
465
- return node;
466
- }
467
- /// Like [`resolve`](#common.Tree.resolve), but will enter
468
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
469
- /// pointing into the innermost overlaid tree at the given position
470
- /// (with parent links going through all parent structure, including
471
- /// the host trees).
472
- resolveInner(pos, side = 0) {
473
- let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
474
- CachedInnerNode.set(this, node);
475
- return node;
476
- }
477
- /// Iterate over the tree and its children, calling `enter` for any
478
- /// node that touches the `from`/`to` region (if given) before
479
- /// running over such a node's children, and `leave` (if given) when
480
- /// leaving the node. When `enter` returns `false`, that node will
481
- /// not have its children iterated over (or `leave` called).
482
- iterate(spec) {
483
- let { enter, leave, from = 0, to = this.length } = spec;
484
- let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
485
- for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
486
- let entered = false;
487
- if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
488
- if (c.firstChild())
489
- continue;
490
- entered = true;
491
- }
492
- for (; ; ) {
493
- if (entered && leave && (anon || !c.type.isAnonymous))
494
- leave(c);
495
- if (c.nextSibling())
496
- break;
497
- if (!c.parent())
498
- return;
499
- entered = true;
500
- }
501
- }
502
- }
503
- /// Get the value of the given [node prop](#common.NodeProp) for this
504
- /// node. Works with both per-node and per-type props.
505
- prop(prop) {
506
- return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
507
- }
508
- /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
509
- /// format that can be passed to the [`Tree`](#common.Tree)
510
- /// constructor.
511
- get propValues() {
512
- let result = [];
513
- if (this.props)
514
- for (let id in this.props)
515
- result.push([+id, this.props[id]]);
516
- return result;
517
- }
518
- /// Balance the direct children of this tree, producing a copy of
519
- /// which may have children grouped into subtrees with type
520
- /// [`NodeType.none`](#common.NodeType^none).
521
- balance(config = {}) {
522
- return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
523
- }
524
- /// Build a tree from a postfix-ordered buffer of node information,
525
- /// or a cursor over such a buffer.
526
- static build(data) {
527
- return buildTree(data);
528
- }
529
- };
530
- Tree.empty = new Tree(NodeType.none, [], [], 0);
531
- var FlatBufferCursor = class {
532
- constructor(buffer, index) {
533
- this.buffer = buffer;
534
- this.index = index;
535
- }
536
- get id() {
537
- return this.buffer[this.index - 4];
538
- }
539
- get start() {
540
- return this.buffer[this.index - 3];
541
- }
542
- get end() {
543
- return this.buffer[this.index - 2];
544
- }
545
- get size() {
546
- return this.buffer[this.index - 1];
547
- }
548
- get pos() {
549
- return this.index;
550
- }
551
- next() {
552
- this.index -= 4;
553
- }
554
- fork() {
555
- return new FlatBufferCursor(this.buffer, this.index);
556
- }
557
- };
558
- var TreeBuffer = class {
559
- /// Create a tree buffer.
560
- constructor(buffer, length, set) {
561
- this.buffer = buffer;
562
- this.length = length;
563
- this.set = set;
564
- }
565
- /// @internal
566
- get type() {
567
- return NodeType.none;
568
- }
569
- /// @internal
570
- toString() {
571
- let result = [];
572
- for (let index = 0; index < this.buffer.length; ) {
573
- result.push(this.childString(index));
574
- index = this.buffer[index + 3];
575
- }
576
- return result.join(",");
577
- }
578
- /// @internal
579
- childString(index) {
580
- let id = this.buffer[index], endIndex = this.buffer[index + 3];
581
- let type = this.set.types[id], result = type.name;
582
- if (/\W/.test(result) && !type.isError)
583
- result = JSON.stringify(result);
584
- index += 4;
585
- if (endIndex == index)
586
- return result;
587
- let children = [];
588
- while (index < endIndex) {
589
- children.push(this.childString(index));
590
- index = this.buffer[index + 3];
591
- }
592
- return result + "(" + children.join(",") + ")";
593
- }
594
- /// @internal
595
- findChild(startIndex, endIndex, dir, pos, side) {
596
- let { buffer } = this, pick = -1;
597
- for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
598
- if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
599
- pick = i;
600
- if (dir > 0)
601
- break;
602
- }
603
- }
604
- return pick;
605
- }
606
- /// @internal
607
- slice(startI, endI, from) {
608
- let b = this.buffer;
609
- let copy = new Uint16Array(endI - startI), len = 0;
610
- for (let i = startI, j = 0; i < endI; ) {
611
- copy[j++] = b[i++];
612
- copy[j++] = b[i++] - from;
613
- let to = copy[j++] = b[i++] - from;
614
- copy[j++] = b[i++] - startI;
615
- len = Math.max(len, to);
616
- }
617
- return new TreeBuffer(copy, len, this.set);
618
- }
619
- };
620
- function checkSide(side, pos, from, to) {
621
- switch (side) {
622
- case -2:
623
- return from < pos;
624
- case -1:
625
- return to >= pos && from < pos;
626
- case 0:
627
- return from < pos && to > pos;
628
- case 1:
629
- return from <= pos && to > pos;
630
- case 2:
631
- return to > pos;
632
- case 4:
633
- return true;
634
- }
635
- }
636
- function enterUnfinishedNodesBefore(node, pos) {
637
- let scan = node.childBefore(pos);
638
- while (scan) {
639
- let last = scan.lastChild;
640
- if (!last || last.to != scan.to)
641
- break;
642
- if (last.type.isError && last.from == last.to) {
643
- node = scan;
644
- scan = last.prevSibling;
645
- } else {
646
- scan = last;
647
- }
648
- }
649
- return node;
650
- }
651
- function resolveNode(node, pos, side, overlays) {
652
- var _a;
653
- while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
654
- let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
655
- if (!parent)
656
- return node;
657
- node = parent;
658
- }
659
- let mode = overlays ? 0 : IterMode.IgnoreOverlays;
660
- if (overlays)
661
- for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
662
- if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
663
- node = parent;
664
- }
665
- for (; ; ) {
666
- let inner = node.enter(pos, side, mode);
667
- if (!inner)
668
- return node;
669
- node = inner;
670
- }
671
- }
672
- var TreeNode = class {
673
- constructor(_tree, from, index, _parent) {
674
- this._tree = _tree;
675
- this.from = from;
676
- this.index = index;
677
- this._parent = _parent;
678
- }
679
- get type() {
680
- return this._tree.type;
681
- }
682
- get name() {
683
- return this._tree.type.name;
684
- }
685
- get to() {
686
- return this.from + this._tree.length;
687
- }
688
- nextChild(i, dir, pos, side, mode = 0) {
689
- for (let parent = this; ; ) {
690
- for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
691
- let next = children[i], start = positions[i] + parent.from;
692
- if (!checkSide(side, pos, start, start + next.length))
693
- continue;
694
- if (next instanceof TreeBuffer) {
695
- if (mode & IterMode.ExcludeBuffers)
696
- continue;
697
- let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
698
- if (index > -1)
699
- return new BufferNode(new BufferContext(parent, next, i, start), null, index);
700
- } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
701
- let mounted;
702
- if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
703
- return new TreeNode(mounted.tree, start, i, parent);
704
- let inner = new TreeNode(next, start, i, parent);
705
- return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
706
- }
707
- }
708
- if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
709
- return null;
710
- if (parent.index >= 0)
711
- i = parent.index + dir;
712
- else
713
- i = dir < 0 ? -1 : parent._parent._tree.children.length;
714
- parent = parent._parent;
715
- if (!parent)
716
- return null;
717
- }
718
- }
719
- get firstChild() {
720
- return this.nextChild(
721
- 0,
722
- 1,
723
- 0,
724
- 4
725
- /* Side.DontCare */
726
- );
727
- }
728
- get lastChild() {
729
- return this.nextChild(
730
- this._tree.children.length - 1,
731
- -1,
732
- 0,
733
- 4
734
- /* Side.DontCare */
735
- );
736
- }
737
- childAfter(pos) {
738
- return this.nextChild(
739
- 0,
740
- 1,
741
- pos,
742
- 2
743
- /* Side.After */
744
- );
745
- }
746
- childBefore(pos) {
747
- return this.nextChild(
748
- this._tree.children.length - 1,
749
- -1,
750
- pos,
751
- -2
752
- /* Side.Before */
753
- );
754
- }
755
- enter(pos, side, mode = 0) {
756
- let mounted;
757
- if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
758
- let rPos = pos - this.from;
759
- for (let { from, to } of mounted.overlay) {
760
- if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
761
- return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
762
- }
763
- }
764
- return this.nextChild(0, 1, pos, side, mode);
765
- }
766
- nextSignificantParent() {
767
- let val = this;
768
- while (val.type.isAnonymous && val._parent)
769
- val = val._parent;
770
- return val;
771
- }
772
- get parent() {
773
- return this._parent ? this._parent.nextSignificantParent() : null;
774
- }
775
- get nextSibling() {
776
- return this._parent && this.index >= 0 ? this._parent.nextChild(
777
- this.index + 1,
778
- 1,
779
- 0,
780
- 4
781
- /* Side.DontCare */
782
- ) : null;
783
- }
784
- get prevSibling() {
785
- return this._parent && this.index >= 0 ? this._parent.nextChild(
786
- this.index - 1,
787
- -1,
788
- 0,
789
- 4
790
- /* Side.DontCare */
791
- ) : null;
792
- }
793
- cursor(mode = 0) {
794
- return new TreeCursor(this, mode);
795
- }
796
- get tree() {
797
- return this._tree;
798
- }
799
- toTree() {
800
- return this._tree;
801
- }
802
- resolve(pos, side = 0) {
803
- return resolveNode(this, pos, side, false);
804
- }
805
- resolveInner(pos, side = 0) {
806
- return resolveNode(this, pos, side, true);
807
- }
808
- enterUnfinishedNodesBefore(pos) {
809
- return enterUnfinishedNodesBefore(this, pos);
810
- }
811
- getChild(type, before = null, after = null) {
812
- let r = getChildren(this, type, before, after);
813
- return r.length ? r[0] : null;
814
- }
815
- getChildren(type, before = null, after = null) {
816
- return getChildren(this, type, before, after);
817
- }
818
- /// @internal
819
- toString() {
820
- return this._tree.toString();
821
- }
822
- get node() {
823
- return this;
824
- }
825
- matchContext(context) {
826
- return matchNodeContext(this, context);
827
- }
828
- };
829
- function getChildren(node, type, before, after) {
830
- let cur = node.cursor(), result = [];
831
- if (!cur.firstChild())
832
- return result;
833
- if (before != null) {
834
- while (!cur.type.is(before))
835
- if (!cur.nextSibling())
836
- return result;
837
- }
838
- for (; ; ) {
839
- if (after != null && cur.type.is(after))
840
- return result;
841
- if (cur.type.is(type))
842
- result.push(cur.node);
843
- if (!cur.nextSibling())
844
- return after == null ? result : [];
845
- }
846
- }
847
- function matchNodeContext(node, context, i = context.length - 1) {
848
- for (let p = node.parent; i >= 0; p = p.parent) {
849
- if (!p)
850
- return false;
851
- if (!p.type.isAnonymous) {
852
- if (context[i] && context[i] != p.name)
853
- return false;
854
- i--;
855
- }
856
- }
857
- return true;
858
- }
859
- var BufferContext = class {
860
- constructor(parent, buffer, index, start) {
861
- this.parent = parent;
862
- this.buffer = buffer;
863
- this.index = index;
864
- this.start = start;
865
- }
866
- };
867
- var BufferNode = class {
868
- get name() {
869
- return this.type.name;
870
- }
871
- get from() {
872
- return this.context.start + this.context.buffer.buffer[this.index + 1];
873
- }
874
- get to() {
875
- return this.context.start + this.context.buffer.buffer[this.index + 2];
876
- }
877
- constructor(context, _parent, index) {
878
- this.context = context;
879
- this._parent = _parent;
880
- this.index = index;
881
- this.type = context.buffer.set.types[context.buffer.buffer[index]];
882
- }
883
- child(dir, pos, side) {
884
- let { buffer } = this.context;
885
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
886
- return index < 0 ? null : new BufferNode(this.context, this, index);
887
- }
888
- get firstChild() {
889
- return this.child(
890
- 1,
891
- 0,
892
- 4
893
- /* Side.DontCare */
894
- );
895
- }
896
- get lastChild() {
897
- return this.child(
898
- -1,
899
- 0,
900
- 4
901
- /* Side.DontCare */
902
- );
903
- }
904
- childAfter(pos) {
905
- return this.child(
906
- 1,
907
- pos,
908
- 2
909
- /* Side.After */
910
- );
911
- }
912
- childBefore(pos) {
913
- return this.child(
914
- -1,
915
- pos,
916
- -2
917
- /* Side.Before */
918
- );
919
- }
920
- enter(pos, side, mode = 0) {
921
- if (mode & IterMode.ExcludeBuffers)
922
- return null;
923
- let { buffer } = this.context;
924
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
925
- return index < 0 ? null : new BufferNode(this.context, this, index);
926
- }
927
- get parent() {
928
- return this._parent || this.context.parent.nextSignificantParent();
929
- }
930
- externalSibling(dir) {
931
- return this._parent ? null : this.context.parent.nextChild(
932
- this.context.index + dir,
933
- dir,
934
- 0,
935
- 4
936
- /* Side.DontCare */
937
- );
938
- }
939
- get nextSibling() {
940
- let { buffer } = this.context;
941
- let after = buffer.buffer[this.index + 3];
942
- if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
943
- return new BufferNode(this.context, this._parent, after);
944
- return this.externalSibling(1);
945
- }
946
- get prevSibling() {
947
- let { buffer } = this.context;
948
- let parentStart = this._parent ? this._parent.index + 4 : 0;
949
- if (this.index == parentStart)
950
- return this.externalSibling(-1);
951
- return new BufferNode(this.context, this._parent, buffer.findChild(
952
- parentStart,
953
- this.index,
954
- -1,
955
- 0,
956
- 4
957
- /* Side.DontCare */
958
- ));
959
- }
960
- cursor(mode = 0) {
961
- return new TreeCursor(this, mode);
962
- }
963
- get tree() {
964
- return null;
965
- }
966
- toTree() {
967
- let children = [], positions = [];
968
- let { buffer } = this.context;
969
- let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
970
- if (endI > startI) {
971
- let from = buffer.buffer[this.index + 1];
972
- children.push(buffer.slice(startI, endI, from));
973
- positions.push(0);
974
- }
975
- return new Tree(this.type, children, positions, this.to - this.from);
976
- }
977
- resolve(pos, side = 0) {
978
- return resolveNode(this, pos, side, false);
979
- }
980
- resolveInner(pos, side = 0) {
981
- return resolveNode(this, pos, side, true);
982
- }
983
- enterUnfinishedNodesBefore(pos) {
984
- return enterUnfinishedNodesBefore(this, pos);
985
- }
986
- /// @internal
987
- toString() {
988
- return this.context.buffer.childString(this.index);
989
- }
990
- getChild(type, before = null, after = null) {
991
- let r = getChildren(this, type, before, after);
992
- return r.length ? r[0] : null;
993
- }
994
- getChildren(type, before = null, after = null) {
995
- return getChildren(this, type, before, after);
996
- }
997
- get node() {
998
- return this;
999
- }
1000
- matchContext(context) {
1001
- return matchNodeContext(this, context);
1002
- }
1003
- };
1004
- var TreeCursor = class {
1005
- /// Shorthand for `.type.name`.
1006
- get name() {
1007
- return this.type.name;
1008
- }
1009
- /// @internal
1010
- constructor(node, mode = 0) {
1011
- this.mode = mode;
1012
- this.buffer = null;
1013
- this.stack = [];
1014
- this.index = 0;
1015
- this.bufferNode = null;
1016
- if (node instanceof TreeNode) {
1017
- this.yieldNode(node);
1018
- } else {
1019
- this._tree = node.context.parent;
1020
- this.buffer = node.context;
1021
- for (let n = node._parent; n; n = n._parent)
1022
- this.stack.unshift(n.index);
1023
- this.bufferNode = node;
1024
- this.yieldBuf(node.index);
1025
- }
1026
- }
1027
- yieldNode(node) {
1028
- if (!node)
1029
- return false;
1030
- this._tree = node;
1031
- this.type = node.type;
1032
- this.from = node.from;
1033
- this.to = node.to;
1034
- return true;
1035
- }
1036
- yieldBuf(index, type) {
1037
- this.index = index;
1038
- let { start, buffer } = this.buffer;
1039
- this.type = type || buffer.set.types[buffer.buffer[index]];
1040
- this.from = start + buffer.buffer[index + 1];
1041
- this.to = start + buffer.buffer[index + 2];
1042
- return true;
1043
- }
1044
- yield(node) {
1045
- if (!node)
1046
- return false;
1047
- if (node instanceof TreeNode) {
1048
- this.buffer = null;
1049
- return this.yieldNode(node);
1050
- }
1051
- this.buffer = node.context;
1052
- return this.yieldBuf(node.index, node.type);
1053
- }
1054
- /// @internal
1055
- toString() {
1056
- return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
1057
- }
1058
- /// @internal
1059
- enterChild(dir, pos, side) {
1060
- if (!this.buffer)
1061
- return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
1062
- let { buffer } = this.buffer;
1063
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
1064
- if (index < 0)
1065
- return false;
1066
- this.stack.push(this.index);
1067
- return this.yieldBuf(index);
1068
- }
1069
- /// Move the cursor to this node's first child. When this returns
1070
- /// false, the node has no child, and the cursor has not been moved.
1071
- firstChild() {
1072
- return this.enterChild(
1073
- 1,
1074
- 0,
1075
- 4
1076
- /* Side.DontCare */
1077
- );
1078
- }
1079
- /// Move the cursor to this node's last child.
1080
- lastChild() {
1081
- return this.enterChild(
1082
- -1,
1083
- 0,
1084
- 4
1085
- /* Side.DontCare */
1086
- );
1087
- }
1088
- /// Move the cursor to the first child that ends after `pos`.
1089
- childAfter(pos) {
1090
- return this.enterChild(
1091
- 1,
1092
- pos,
1093
- 2
1094
- /* Side.After */
1095
- );
1096
- }
1097
- /// Move to the last child that starts before `pos`.
1098
- childBefore(pos) {
1099
- return this.enterChild(
1100
- -1,
1101
- pos,
1102
- -2
1103
- /* Side.Before */
1104
- );
1105
- }
1106
- /// Move the cursor to the child around `pos`. If side is -1 the
1107
- /// child may end at that position, when 1 it may start there. This
1108
- /// will also enter [overlaid](#common.MountedTree.overlay)
1109
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
1110
- /// set to false.
1111
- enter(pos, side, mode = this.mode) {
1112
- if (!this.buffer)
1113
- return this.yield(this._tree.enter(pos, side, mode));
1114
- return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
1115
- }
1116
- /// Move to the node's parent node, if this isn't the top node.
1117
- parent() {
1118
- if (!this.buffer)
1119
- return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
1120
- if (this.stack.length)
1121
- return this.yieldBuf(this.stack.pop());
1122
- let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
1123
- this.buffer = null;
1124
- return this.yieldNode(parent);
1125
- }
1126
- /// @internal
1127
- sibling(dir) {
1128
- if (!this.buffer)
1129
- return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
1130
- let { buffer } = this.buffer, d = this.stack.length - 1;
1131
- if (dir < 0) {
1132
- let parentStart = d < 0 ? 0 : this.stack[d] + 4;
1133
- if (this.index != parentStart)
1134
- return this.yieldBuf(buffer.findChild(
1135
- parentStart,
1136
- this.index,
1137
- -1,
1138
- 0,
1139
- 4
1140
- /* Side.DontCare */
1141
- ));
1142
- } else {
1143
- let after = buffer.buffer[this.index + 3];
1144
- if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
1145
- return this.yieldBuf(after);
1146
- }
1147
- return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
1148
- }
1149
- /// Move to this node's next sibling, if any.
1150
- nextSibling() {
1151
- return this.sibling(1);
1152
- }
1153
- /// Move to this node's previous sibling, if any.
1154
- prevSibling() {
1155
- return this.sibling(-1);
1156
- }
1157
- atLastNode(dir) {
1158
- let index, parent, { buffer } = this;
1159
- if (buffer) {
1160
- if (dir > 0) {
1161
- if (this.index < buffer.buffer.buffer.length)
1162
- return false;
1163
- } else {
1164
- for (let i = 0; i < this.index; i++)
1165
- if (buffer.buffer.buffer[i + 3] < this.index)
1166
- return false;
1167
- }
1168
- ({ index, parent } = buffer);
1169
- } else {
1170
- ({ index, _parent: parent } = this._tree);
1171
- }
1172
- for (; parent; { index, _parent: parent } = parent) {
1173
- if (index > -1)
1174
- for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
1175
- let child = parent._tree.children[i];
1176
- if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
1177
- return false;
1178
- }
1179
- }
1180
- return true;
1181
- }
1182
- move(dir, enter) {
1183
- if (enter && this.enterChild(
1184
- dir,
1185
- 0,
1186
- 4
1187
- /* Side.DontCare */
1188
- ))
1189
- return true;
1190
- for (; ; ) {
1191
- if (this.sibling(dir))
1192
- return true;
1193
- if (this.atLastNode(dir) || !this.parent())
1194
- return false;
1195
- }
1196
- }
1197
- /// Move to the next node in a
1198
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
1199
- /// traversal, going from a node to its first child or, if the
1200
- /// current node is empty or `enter` is false, its next sibling or
1201
- /// the next sibling of the first parent node that has one.
1202
- next(enter = true) {
1203
- return this.move(1, enter);
1204
- }
1205
- /// Move to the next node in a last-to-first pre-order traveral. A
1206
- /// node is followed by its last child or, if it has none, its
1207
- /// previous sibling or the previous sibling of the first parent
1208
- /// node that has one.
1209
- prev(enter = true) {
1210
- return this.move(-1, enter);
1211
- }
1212
- /// Move the cursor to the innermost node that covers `pos`. If
1213
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
1214
- /// it will enter nodes that start at `pos`.
1215
- moveTo(pos, side = 0) {
1216
- while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
1217
- if (!this.parent())
1218
- break;
1219
- while (this.enterChild(1, pos, side)) {
1220
- }
1221
- return this;
1222
- }
1223
- /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
1224
- /// position.
1225
- get node() {
1226
- if (!this.buffer)
1227
- return this._tree;
1228
- let cache = this.bufferNode, result = null, depth = 0;
1229
- if (cache && cache.context == this.buffer) {
1230
- scan:
1231
- for (let index = this.index, d = this.stack.length; d >= 0; ) {
1232
- for (let c = cache; c; c = c._parent)
1233
- if (c.index == index) {
1234
- if (index == this.index)
1235
- return c;
1236
- result = c;
1237
- depth = d + 1;
1238
- break scan;
1239
- }
1240
- index = this.stack[--d];
1241
- }
1242
- }
1243
- for (let i = depth; i < this.stack.length; i++)
1244
- result = new BufferNode(this.buffer, result, this.stack[i]);
1245
- return this.bufferNode = new BufferNode(this.buffer, result, this.index);
1246
- }
1247
- /// Get the [tree](#common.Tree) that represents the current node, if
1248
- /// any. Will return null when the node is in a [tree
1249
- /// buffer](#common.TreeBuffer).
1250
- get tree() {
1251
- return this.buffer ? null : this._tree._tree;
1252
- }
1253
- /// Iterate over the current node and all its descendants, calling
1254
- /// `enter` when entering a node and `leave`, if given, when leaving
1255
- /// one. When `enter` returns `false`, any children of that node are
1256
- /// skipped, and `leave` isn't called for it.
1257
- iterate(enter, leave) {
1258
- for (let depth = 0; ; ) {
1259
- let mustLeave = false;
1260
- if (this.type.isAnonymous || enter(this) !== false) {
1261
- if (this.firstChild()) {
1262
- depth++;
1263
- continue;
1264
- }
1265
- if (!this.type.isAnonymous)
1266
- mustLeave = true;
1267
- }
1268
- for (; ; ) {
1269
- if (mustLeave && leave)
1270
- leave(this);
1271
- mustLeave = this.type.isAnonymous;
1272
- if (this.nextSibling())
1273
- break;
1274
- if (!depth)
1275
- return;
1276
- this.parent();
1277
- depth--;
1278
- mustLeave = true;
1279
- }
1280
- }
1281
- }
1282
- /// Test whether the current node matches a given context—a sequence
1283
- /// of direct parent node names. Empty strings in the context array
1284
- /// are treated as wildcards.
1285
- matchContext(context) {
1286
- if (!this.buffer)
1287
- return matchNodeContext(this.node, context);
1288
- let { buffer } = this.buffer, { types } = buffer.set;
1289
- for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
1290
- if (d < 0)
1291
- return matchNodeContext(this.node, context, i);
1292
- let type = types[buffer.buffer[this.stack[d]]];
1293
- if (!type.isAnonymous) {
1294
- if (context[i] && context[i] != type.name)
1295
- return false;
1296
- i--;
1297
- }
1298
- }
1299
- return true;
1300
- }
1301
- };
1302
- function hasChild(tree) {
1303
- return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1304
- }
1305
- function buildTree(data) {
1306
- var _a;
1307
- let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1308
- let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1309
- let types = nodeSet.types;
1310
- let contextHash = 0, lookAhead = 0;
1311
- function takeNode(parentStart, minPos, children2, positions2, inRepeat) {
1312
- let { id, start, end, size } = cursor;
1313
- let lookAheadAtStart = lookAhead;
1314
- while (size < 0) {
1315
- cursor.next();
1316
- if (size == -1) {
1317
- let node2 = reused[id];
1318
- children2.push(node2);
1319
- positions2.push(start - parentStart);
1320
- return;
1321
- } else if (size == -3) {
1322
- contextHash = id;
1323
- return;
1324
- } else if (size == -4) {
1325
- lookAhead = id;
1326
- return;
1327
- } else {
1328
- throw new RangeError(`Unrecognized record size: ${size}`);
1329
- }
1330
- }
1331
- let type = types[id], node, buffer2;
1332
- let startPos = start - parentStart;
1333
- if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
1334
- let data2 = new Uint16Array(buffer2.size - buffer2.skip);
1335
- let endPos = cursor.pos - buffer2.size, index = data2.length;
1336
- while (cursor.pos > endPos)
1337
- index = copyToBuffer(buffer2.start, data2, index);
1338
- node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
1339
- startPos = buffer2.start - parentStart;
1340
- } else {
1341
- let endPos = cursor.pos - size;
1342
- cursor.next();
1343
- let localChildren = [], localPositions = [];
1344
- let localInRepeat = id >= minRepeatType ? id : -1;
1345
- let lastGroup = 0, lastEnd = end;
1346
- while (cursor.pos > endPos) {
1347
- if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1348
- if (cursor.end <= lastEnd - maxBufferLength) {
1349
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
1350
- lastGroup = localChildren.length;
1351
- lastEnd = cursor.end;
1352
- }
1353
- cursor.next();
1354
- } else {
1355
- takeNode(start, endPos, localChildren, localPositions, localInRepeat);
1356
- }
1357
- }
1358
- if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1359
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
1360
- localChildren.reverse();
1361
- localPositions.reverse();
1362
- if (localInRepeat > -1 && lastGroup > 0) {
1363
- let make = makeBalanced(type);
1364
- node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1365
- } else {
1366
- node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
1367
- }
1368
- }
1369
- children2.push(node);
1370
- positions2.push(startPos);
1371
- }
1372
- function makeBalanced(type) {
1373
- return (children2, positions2, length2) => {
1374
- let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp;
1375
- if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) {
1376
- if (!lastI && last.type == type && last.length == length2)
1377
- return last;
1378
- if (lookAheadProp = last.prop(NodeProp.lookAhead))
1379
- lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
1380
- }
1381
- return makeTree(type, children2, positions2, length2, lookAhead2);
1382
- };
1383
- }
1384
- function makeRepeatLeaf(children2, positions2, base, i, from, to, type, lookAhead2) {
1385
- let localChildren = [], localPositions = [];
1386
- while (children2.length > i) {
1387
- localChildren.push(children2.pop());
1388
- localPositions.push(positions2.pop() + base - from);
1389
- }
1390
- children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to));
1391
- positions2.push(from - base);
1392
- }
1393
- function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) {
1394
- if (contextHash) {
1395
- let pair2 = [NodeProp.contextHash, contextHash];
1396
- props = props ? [pair2].concat(props) : [pair2];
1397
- }
1398
- if (lookAhead2 > 25) {
1399
- let pair2 = [NodeProp.lookAhead, lookAhead2];
1400
- props = props ? [pair2].concat(props) : [pair2];
1401
- }
1402
- return new Tree(type, children2, positions2, length2, props);
1403
- }
1404
- function findBufferSize(maxSize, inRepeat) {
1405
- let fork = cursor.fork();
1406
- let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1407
- let result = { size: 0, start: 0, skip: 0 };
1408
- scan:
1409
- for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
1410
- let nodeSize2 = fork.size;
1411
- if (fork.id == inRepeat && nodeSize2 >= 0) {
1412
- result.size = size;
1413
- result.start = start;
1414
- result.skip = skip;
1415
- skip += 4;
1416
- size += 4;
1417
- fork.next();
1418
- continue;
1419
- }
1420
- let startPos = fork.pos - nodeSize2;
1421
- if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
1422
- break;
1423
- let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1424
- let nodeStart = fork.start;
1425
- fork.next();
1426
- while (fork.pos > startPos) {
1427
- if (fork.size < 0) {
1428
- if (fork.size == -3)
1429
- localSkipped += 4;
1430
- else
1431
- break scan;
1432
- } else if (fork.id >= minRepeatType) {
1433
- localSkipped += 4;
1434
- }
1435
- fork.next();
1436
- }
1437
- start = nodeStart;
1438
- size += nodeSize2;
1439
- skip += localSkipped;
1440
- }
1441
- if (inRepeat < 0 || size == maxSize) {
1442
- result.size = size;
1443
- result.start = start;
1444
- result.skip = skip;
1445
- }
1446
- return result.size > 4 ? result : void 0;
1447
- }
1448
- function copyToBuffer(bufferStart, buffer2, index) {
1449
- let { id, start, end, size } = cursor;
1450
- cursor.next();
1451
- if (size >= 0 && id < minRepeatType) {
1452
- let startIndex = index;
1453
- if (size > 4) {
1454
- let endPos = cursor.pos - (size - 4);
1455
- while (cursor.pos > endPos)
1456
- index = copyToBuffer(bufferStart, buffer2, index);
1457
- }
1458
- buffer2[--index] = startIndex;
1459
- buffer2[--index] = end - bufferStart;
1460
- buffer2[--index] = start - bufferStart;
1461
- buffer2[--index] = id;
1462
- } else if (size == -3) {
1463
- contextHash = id;
1464
- } else if (size == -4) {
1465
- lookAhead = id;
1466
- }
1467
- return index;
1468
- }
1469
- let children = [], positions = [];
1470
- while (cursor.pos > 0)
1471
- takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1472
- let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
1473
- return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1474
- }
1475
- var nodeSizeCache = /* @__PURE__ */ new WeakMap();
1476
- function nodeSize(balanceType, node) {
1477
- if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1478
- return 1;
1479
- let size = nodeSizeCache.get(node);
1480
- if (size == null) {
1481
- size = 1;
1482
- for (let child of node.children) {
1483
- if (child.type != balanceType || !(child instanceof Tree)) {
1484
- size = 1;
1485
- break;
1486
- }
1487
- size += nodeSize(balanceType, child);
1488
- }
1489
- nodeSizeCache.set(node, size);
1490
- }
1491
- return size;
1492
- }
1493
- function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
1494
- let total = 0;
1495
- for (let i = from; i < to; i++)
1496
- total += nodeSize(balanceType, children[i]);
1497
- let maxChild = Math.ceil(
1498
- total * 1.5 / 8
1499
- /* Balance.BranchFactor */
1500
- );
1501
- let localChildren = [], localPositions = [];
1502
- function divide(children2, positions2, from2, to2, offset) {
1503
- for (let i = from2; i < to2; ) {
1504
- let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children2[i]);
1505
- i++;
1506
- for (; i < to2; i++) {
1507
- let nextSize = nodeSize(balanceType, children2[i]);
1508
- if (groupSize + nextSize >= maxChild)
1509
- break;
1510
- groupSize += nextSize;
1511
- }
1512
- if (i == groupFrom + 1) {
1513
- if (groupSize > maxChild) {
1514
- let only = children2[groupFrom];
1515
- divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
1516
- continue;
1517
- }
1518
- localChildren.push(children2[groupFrom]);
1519
- } else {
1520
- let length2 = positions2[i - 1] + children2[i - 1].length - groupStart;
1521
- localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i, groupStart, length2, null, mkTree));
1522
- }
1523
- localPositions.push(groupStart + offset - start);
1524
- }
1525
- }
1526
- divide(children, positions, from, to, 0);
1527
- return (mkTop || mkTree)(localChildren, localPositions, length);
1528
- }
1529
- var Parser = class {
1530
- /// Start a parse, returning a [partial parse](#common.PartialParse)
1531
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
1532
- /// make the parse incremental.
1533
- ///
1534
- /// By default, the entire input is parsed. You can pass `ranges`,
1535
- /// which should be a sorted array of non-empty, non-overlapping
1536
- /// ranges, to parse only those ranges. The tree returned in that
1537
- /// case will start at `ranges[0].from`.
1538
- startParse(input, fragments, ranges) {
1539
- if (typeof input == "string")
1540
- input = new StringInput(input);
1541
- ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map((r) => new Range(r.from, r.to)) : [new Range(0, 0)];
1542
- return this.createParse(input, fragments || [], ranges);
1543
- }
1544
- /// Run a full parse, returning the resulting tree.
1545
- parse(input, fragments, ranges) {
1546
- let parse = this.startParse(input, fragments, ranges);
1547
- for (; ; ) {
1548
- let done = parse.advance();
1549
- if (done)
1550
- return done;
1551
- }
1552
- }
1553
- };
1554
- var StringInput = class {
1555
- constructor(string) {
1556
- this.string = string;
1557
- }
1558
- get length() {
1559
- return this.string.length;
1560
- }
1561
- chunk(from) {
1562
- return this.string.slice(from);
1563
- }
1564
- get lineChunks() {
1565
- return false;
1566
- }
1567
- read(from, to) {
1568
- return this.string.slice(from, to);
1569
- }
1570
- };
1571
- var stoppedInner = new NodeProp({ perNode: true });
1572
-
1573
- // ../../node_modules/@lezer/lr/dist/index.js
1574
- var Stack = class {
1575
- /// @internal
1576
- constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) {
1577
- this.p = p;
1578
- this.stack = stack;
1579
- this.state = state;
1580
- this.reducePos = reducePos;
1581
- this.pos = pos;
1582
- this.score = score;
1583
- this.buffer = buffer;
1584
- this.bufferBase = bufferBase;
1585
- this.curContext = curContext;
1586
- this.lookAhead = lookAhead;
1587
- this.parent = parent;
1588
- }
1589
- /// @internal
1590
- toString() {
1591
- return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
1592
- }
1593
- // Start an empty stack
1594
- /// @internal
1595
- static start(p, state, pos = 0) {
1596
- let cx = p.parser.context;
1597
- return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
1598
- }
1599
- /// The stack's current [context](#lr.ContextTracker) value, if
1600
- /// any. Its type will depend on the context tracker's type
1601
- /// parameter, or it will be `null` if there is no context
1602
- /// tracker.
1603
- get context() {
1604
- return this.curContext ? this.curContext.context : null;
1605
- }
1606
- // Push a state onto the stack, tracking its start position as well
1607
- // as the buffer base at that point.
1608
- /// @internal
1609
- pushState(state, start) {
1610
- this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
1611
- this.state = state;
1612
- }
1613
- // Apply a reduce action
1614
- /// @internal
1615
- reduce(action) {
1616
- var _a;
1617
- let depth = action >> 19, type = action & 65535;
1618
- let { parser: parser2 } = this.p;
1619
- let dPrec = parser2.dynamicPrecedence(type);
1620
- if (dPrec)
1621
- this.score += dPrec;
1622
- if (depth == 0) {
1623
- this.pushState(parser2.getGoto(this.state, type, true), this.reducePos);
1624
- if (type < parser2.minRepeatTerm)
1625
- this.storeNode(type, this.reducePos, this.reducePos, 4, true);
1626
- this.reduceContext(type, this.reducePos);
1627
- return;
1628
- }
1629
- let base = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0);
1630
- let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
1631
- if (size >= 2e3 && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
1632
- if (start == this.p.lastBigReductionStart) {
1633
- this.p.bigReductionCount++;
1634
- this.p.lastBigReductionSize = size;
1635
- } else if (this.p.lastBigReductionSize < size) {
1636
- this.p.bigReductionCount = 1;
1637
- this.p.lastBigReductionStart = start;
1638
- this.p.lastBigReductionSize = size;
1639
- }
1640
- }
1641
- let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
1642
- if (type < parser2.minRepeatTerm || action & 131072) {
1643
- let pos = parser2.stateFlag(
1644
- this.state,
1645
- 1
1646
- /* StateFlag.Skipped */
1647
- ) ? this.pos : this.reducePos;
1648
- this.storeNode(type, start, pos, count + 4, true);
1649
- }
1650
- if (action & 262144) {
1651
- this.state = this.stack[base];
1652
- } else {
1653
- let baseStateID = this.stack[base - 3];
1654
- this.state = parser2.getGoto(baseStateID, type, true);
1655
- }
1656
- while (this.stack.length > base)
1657
- this.stack.pop();
1658
- this.reduceContext(type, start);
1659
- }
1660
- // Shift a value into the buffer
1661
- /// @internal
1662
- storeNode(term, start, end, size = 4, isReduce = false) {
1663
- if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
1664
- let cur = this, top = this.buffer.length;
1665
- if (top == 0 && cur.parent) {
1666
- top = cur.bufferBase - cur.parent.bufferBase;
1667
- cur = cur.parent;
1668
- }
1669
- if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) {
1670
- if (start == end)
1671
- return;
1672
- if (cur.buffer[top - 2] >= start) {
1673
- cur.buffer[top - 2] = end;
1674
- return;
1675
- }
1676
- }
1677
- }
1678
- if (!isReduce || this.pos == end) {
1679
- this.buffer.push(term, start, end, size);
1680
- } else {
1681
- let index = this.buffer.length;
1682
- if (index > 0 && this.buffer[index - 4] != 0)
1683
- while (index > 0 && this.buffer[index - 2] > end) {
1684
- this.buffer[index] = this.buffer[index - 4];
1685
- this.buffer[index + 1] = this.buffer[index - 3];
1686
- this.buffer[index + 2] = this.buffer[index - 2];
1687
- this.buffer[index + 3] = this.buffer[index - 1];
1688
- index -= 4;
1689
- if (size > 4)
1690
- size -= 4;
1691
- }
1692
- this.buffer[index] = term;
1693
- this.buffer[index + 1] = start;
1694
- this.buffer[index + 2] = end;
1695
- this.buffer[index + 3] = size;
1696
- }
1697
- }
1698
- // Apply a shift action
1699
- /// @internal
1700
- shift(action, next, nextEnd) {
1701
- let start = this.pos;
1702
- if (action & 131072) {
1703
- this.pushState(action & 65535, this.pos);
1704
- } else if ((action & 262144) == 0) {
1705
- let nextState = action, { parser: parser2 } = this.p;
1706
- if (nextEnd > this.pos || next <= parser2.maxNode) {
1707
- this.pos = nextEnd;
1708
- if (!parser2.stateFlag(
1709
- nextState,
1710
- 1
1711
- /* StateFlag.Skipped */
1712
- ))
1713
- this.reducePos = nextEnd;
1714
- }
1715
- this.pushState(nextState, start);
1716
- this.shiftContext(next, start);
1717
- if (next <= parser2.maxNode)
1718
- this.buffer.push(next, start, nextEnd, 4);
1719
- } else {
1720
- this.pos = nextEnd;
1721
- this.shiftContext(next, start);
1722
- if (next <= this.p.parser.maxNode)
1723
- this.buffer.push(next, start, nextEnd, 4);
1724
- }
1725
- }
1726
- // Apply an action
1727
- /// @internal
1728
- apply(action, next, nextEnd) {
1729
- if (action & 65536)
1730
- this.reduce(action);
1731
- else
1732
- this.shift(action, next, nextEnd);
1733
- }
1734
- // Add a prebuilt (reused) node into the buffer.
1735
- /// @internal
1736
- useNode(value, next) {
1737
- let index = this.p.reused.length - 1;
1738
- if (index < 0 || this.p.reused[index] != value) {
1739
- this.p.reused.push(value);
1740
- index++;
1741
- }
1742
- let start = this.pos;
1743
- this.reducePos = this.pos = start + value.length;
1744
- this.pushState(next, start);
1745
- this.buffer.push(
1746
- index,
1747
- start,
1748
- this.reducePos,
1749
- -1
1750
- /* size == -1 means this is a reused value */
1751
- );
1752
- if (this.curContext)
1753
- this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
1754
- }
1755
- // Split the stack. Due to the buffer sharing and the fact
1756
- // that `this.stack` tends to stay quite shallow, this isn't very
1757
- // expensive.
1758
- /// @internal
1759
- split() {
1760
- let parent = this;
1761
- let off = parent.buffer.length;
1762
- while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
1763
- off -= 4;
1764
- let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
1765
- while (parent && base == parent.bufferBase)
1766
- parent = parent.parent;
1767
- return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
1768
- }
1769
- // Try to recover from an error by 'deleting' (ignoring) one token.
1770
- /// @internal
1771
- recoverByDelete(next, nextEnd) {
1772
- let isNode = next <= this.p.parser.maxNode;
1773
- if (isNode)
1774
- this.storeNode(next, this.pos, nextEnd, 4);
1775
- this.storeNode(0, this.pos, nextEnd, isNode ? 8 : 4);
1776
- this.pos = this.reducePos = nextEnd;
1777
- this.score -= 190;
1778
- }
1779
- /// Check if the given term would be able to be shifted (optionally
1780
- /// after some reductions) on this stack. This can be useful for
1781
- /// external tokenizers that want to make sure they only provide a
1782
- /// given token when it applies.
1783
- canShift(term) {
1784
- for (let sim = new SimulatedStack(this); ; ) {
1785
- let action = this.p.parser.stateSlot(
1786
- sim.state,
1787
- 4
1788
- /* ParseState.DefaultReduce */
1789
- ) || this.p.parser.hasAction(sim.state, term);
1790
- if (action == 0)
1791
- return false;
1792
- if ((action & 65536) == 0)
1793
- return true;
1794
- sim.reduce(action);
1795
- }
1796
- }
1797
- // Apply up to Recover.MaxNext recovery actions that conceptually
1798
- // inserts some missing token or rule.
1799
- /// @internal
1800
- recoverByInsert(next) {
1801
- if (this.stack.length >= 300)
1802
- return [];
1803
- let nextStates = this.p.parser.nextStates(this.state);
1804
- if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
1805
- let best = [];
1806
- for (let i = 0, s; i < nextStates.length; i += 2) {
1807
- if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
1808
- best.push(nextStates[i], s);
1809
- }
1810
- if (this.stack.length < 120)
1811
- for (let i = 0; best.length < 4 << 1 && i < nextStates.length; i += 2) {
1812
- let s = nextStates[i + 1];
1813
- if (!best.some((v, i2) => i2 & 1 && v == s))
1814
- best.push(nextStates[i], s);
1815
- }
1816
- nextStates = best;
1817
- }
1818
- let result = [];
1819
- for (let i = 0; i < nextStates.length && result.length < 4; i += 2) {
1820
- let s = nextStates[i + 1];
1821
- if (s == this.state)
1822
- continue;
1823
- let stack = this.split();
1824
- stack.pushState(s, this.pos);
1825
- stack.storeNode(0, stack.pos, stack.pos, 4, true);
1826
- stack.shiftContext(nextStates[i], this.pos);
1827
- stack.score -= 200;
1828
- result.push(stack);
1829
- }
1830
- return result;
1831
- }
1832
- // Force a reduce, if possible. Return false if that can't
1833
- // be done.
1834
- /// @internal
1835
- forceReduce() {
1836
- let reduce = this.p.parser.stateSlot(
1837
- this.state,
1838
- 5
1839
- /* ParseState.ForcedReduce */
1840
- );
1841
- if ((reduce & 65536) == 0)
1842
- return false;
1843
- let { parser: parser2 } = this.p;
1844
- if (!parser2.validAction(this.state, reduce)) {
1845
- let depth = reduce >> 19, term = reduce & 65535;
1846
- let target = this.stack.length - depth * 3;
1847
- if (target < 0 || parser2.getGoto(this.stack[target], term, false) < 0)
1848
- return false;
1849
- this.storeNode(0, this.reducePos, this.reducePos, 4, true);
1850
- this.score -= 100;
1851
- }
1852
- this.reducePos = this.pos;
1853
- this.reduce(reduce);
1854
- return true;
1855
- }
1856
- /// @internal
1857
- forceAll() {
1858
- while (!this.p.parser.stateFlag(
1859
- this.state,
1860
- 2
1861
- /* StateFlag.Accepting */
1862
- )) {
1863
- if (!this.forceReduce()) {
1864
- this.storeNode(0, this.pos, this.pos, 4, true);
1865
- break;
1866
- }
1867
- }
1868
- return this;
1869
- }
1870
- /// Check whether this state has no further actions (assumed to be a direct descendant of the
1871
- /// top state, since any other states must be able to continue
1872
- /// somehow). @internal
1873
- get deadEnd() {
1874
- if (this.stack.length != 3)
1875
- return false;
1876
- let { parser: parser2 } = this.p;
1877
- return parser2.data[parser2.stateSlot(
1878
- this.state,
1879
- 1
1880
- /* ParseState.Actions */
1881
- )] == 65535 && !parser2.stateSlot(
1882
- this.state,
1883
- 4
1884
- /* ParseState.DefaultReduce */
1885
- );
1886
- }
1887
- /// Restart the stack (put it back in its start state). Only safe
1888
- /// when this.stack.length == 3 (state is directly below the top
1889
- /// state). @internal
1890
- restart() {
1891
- this.state = this.stack[0];
1892
- this.stack.length = 0;
1893
- }
1894
- /// @internal
1895
- sameState(other) {
1896
- if (this.state != other.state || this.stack.length != other.stack.length)
1897
- return false;
1898
- for (let i = 0; i < this.stack.length; i += 3)
1899
- if (this.stack[i] != other.stack[i])
1900
- return false;
1901
- return true;
1902
- }
1903
- /// Get the parser used by this stack.
1904
- get parser() {
1905
- return this.p.parser;
1906
- }
1907
- /// Test whether a given dialect (by numeric ID, as exported from
1908
- /// the terms file) is enabled.
1909
- dialectEnabled(dialectID) {
1910
- return this.p.parser.dialect.flags[dialectID];
1911
- }
1912
- shiftContext(term, start) {
1913
- if (this.curContext)
1914
- this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
1915
- }
1916
- reduceContext(term, start) {
1917
- if (this.curContext)
1918
- this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
1919
- }
1920
- /// @internal
1921
- emitContext() {
1922
- let last = this.buffer.length - 1;
1923
- if (last < 0 || this.buffer[last] != -3)
1924
- this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3);
1925
- }
1926
- /// @internal
1927
- emitLookAhead() {
1928
- let last = this.buffer.length - 1;
1929
- if (last < 0 || this.buffer[last] != -4)
1930
- this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4);
1931
- }
1932
- updateContext(context) {
1933
- if (context != this.curContext.context) {
1934
- let newCx = new StackContext(this.curContext.tracker, context);
1935
- if (newCx.hash != this.curContext.hash)
1936
- this.emitContext();
1937
- this.curContext = newCx;
1938
- }
1939
- }
1940
- /// @internal
1941
- setLookAhead(lookAhead) {
1942
- if (lookAhead > this.lookAhead) {
1943
- this.emitLookAhead();
1944
- this.lookAhead = lookAhead;
1945
- }
1946
- }
1947
- /// @internal
1948
- close() {
1949
- if (this.curContext && this.curContext.tracker.strict)
1950
- this.emitContext();
1951
- if (this.lookAhead > 0)
1952
- this.emitLookAhead();
1953
- }
1954
- };
1955
- var StackContext = class {
1956
- constructor(tracker, context) {
1957
- this.tracker = tracker;
1958
- this.context = context;
1959
- this.hash = tracker.strict ? tracker.hash(context) : 0;
1960
- }
1961
- };
1962
- var Recover;
1963
- (function(Recover2) {
1964
- Recover2[Recover2["Insert"] = 200] = "Insert";
1965
- Recover2[Recover2["Delete"] = 190] = "Delete";
1966
- Recover2[Recover2["Reduce"] = 100] = "Reduce";
1967
- Recover2[Recover2["MaxNext"] = 4] = "MaxNext";
1968
- Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
1969
- Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
1970
- Recover2[Recover2["MinBigReduction"] = 2e3] = "MinBigReduction";
1971
- })(Recover || (Recover = {}));
1972
- var SimulatedStack = class {
1973
- constructor(start) {
1974
- this.start = start;
1975
- this.state = start.state;
1976
- this.stack = start.stack;
1977
- this.base = this.stack.length;
1978
- }
1979
- reduce(action) {
1980
- let term = action & 65535, depth = action >> 19;
1981
- if (depth == 0) {
1982
- if (this.stack == this.start.stack)
1983
- this.stack = this.stack.slice();
1984
- this.stack.push(this.state, 0, 0);
1985
- this.base += 3;
1986
- } else {
1987
- this.base -= (depth - 1) * 3;
1988
- }
1989
- let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
1990
- this.state = goto;
1991
- }
1992
- };
1993
- var StackBufferCursor = class {
1994
- constructor(stack, pos, index) {
1995
- this.stack = stack;
1996
- this.pos = pos;
1997
- this.index = index;
1998
- this.buffer = stack.buffer;
1999
- if (this.index == 0)
2000
- this.maybeNext();
2001
- }
2002
- static create(stack, pos = stack.bufferBase + stack.buffer.length) {
2003
- return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
2004
- }
2005
- maybeNext() {
2006
- let next = this.stack.parent;
2007
- if (next != null) {
2008
- this.index = this.stack.bufferBase - next.bufferBase;
2009
- this.stack = next;
2010
- this.buffer = next.buffer;
2011
- }
2012
- }
2013
- get id() {
2014
- return this.buffer[this.index - 4];
2015
- }
2016
- get start() {
2017
- return this.buffer[this.index - 3];
2018
- }
2019
- get end() {
2020
- return this.buffer[this.index - 2];
2021
- }
2022
- get size() {
2023
- return this.buffer[this.index - 1];
2024
- }
2025
- next() {
2026
- this.index -= 4;
2027
- this.pos -= 4;
2028
- if (this.index == 0)
2029
- this.maybeNext();
2030
- }
2031
- fork() {
2032
- return new StackBufferCursor(this.stack, this.pos, this.index);
2033
- }
2034
- };
2035
- function decodeArray(input, Type = Uint16Array) {
2036
- if (typeof input != "string")
2037
- return input;
2038
- let array = null;
2039
- for (let pos = 0, out = 0; pos < input.length; ) {
2040
- let value = 0;
2041
- for (; ; ) {
2042
- let next = input.charCodeAt(pos++), stop = false;
2043
- if (next == 126) {
2044
- value = 65535;
2045
- break;
2046
- }
2047
- if (next >= 92)
2048
- next--;
2049
- if (next >= 34)
2050
- next--;
2051
- let digit = next - 32;
2052
- if (digit >= 46) {
2053
- digit -= 46;
2054
- stop = true;
2055
- }
2056
- value += digit;
2057
- if (stop)
2058
- break;
2059
- value *= 46;
2060
- }
2061
- if (array)
2062
- array[out++] = value;
2063
- else
2064
- array = new Type(value);
2065
- }
2066
- return array;
2067
- }
2068
- var CachedToken = class {
2069
- constructor() {
2070
- this.start = -1;
2071
- this.value = -1;
2072
- this.end = -1;
2073
- this.extended = -1;
2074
- this.lookAhead = 0;
2075
- this.mask = 0;
2076
- this.context = 0;
2077
- }
2078
- };
2079
- var nullToken = new CachedToken();
2080
- var InputStream = class {
2081
- /// @internal
2082
- constructor(input, ranges) {
2083
- this.input = input;
2084
- this.ranges = ranges;
2085
- this.chunk = "";
2086
- this.chunkOff = 0;
2087
- this.chunk2 = "";
2088
- this.chunk2Pos = 0;
2089
- this.next = -1;
2090
- this.token = nullToken;
2091
- this.rangeIndex = 0;
2092
- this.pos = this.chunkPos = ranges[0].from;
2093
- this.range = ranges[0];
2094
- this.end = ranges[ranges.length - 1].to;
2095
- this.readNext();
2096
- }
2097
- /// @internal
2098
- resolveOffset(offset, assoc) {
2099
- let range = this.range, index = this.rangeIndex;
2100
- let pos = this.pos + offset;
2101
- while (pos < range.from) {
2102
- if (!index)
2103
- return null;
2104
- let next = this.ranges[--index];
2105
- pos -= range.from - next.to;
2106
- range = next;
2107
- }
2108
- while (assoc < 0 ? pos > range.to : pos >= range.to) {
2109
- if (index == this.ranges.length - 1)
2110
- return null;
2111
- let next = this.ranges[++index];
2112
- pos += next.from - range.to;
2113
- range = next;
2114
- }
2115
- return pos;
2116
- }
2117
- /// @internal
2118
- clipPos(pos) {
2119
- if (pos >= this.range.from && pos < this.range.to)
2120
- return pos;
2121
- for (let range of this.ranges)
2122
- if (range.to > pos)
2123
- return Math.max(pos, range.from);
2124
- return this.end;
2125
- }
2126
- /// Look at a code unit near the stream position. `.peek(0)` equals
2127
- /// `.next`, `.peek(-1)` gives you the previous character, and so
2128
- /// on.
2129
- ///
2130
- /// Note that looking around during tokenizing creates dependencies
2131
- /// on potentially far-away content, which may reduce the
2132
- /// effectiveness incremental parsing—when looking forward—or even
2133
- /// cause invalid reparses when looking backward more than 25 code
2134
- /// units, since the library does not track lookbehind.
2135
- peek(offset) {
2136
- let idx = this.chunkOff + offset, pos, result;
2137
- if (idx >= 0 && idx < this.chunk.length) {
2138
- pos = this.pos + offset;
2139
- result = this.chunk.charCodeAt(idx);
2140
- } else {
2141
- let resolved = this.resolveOffset(offset, 1);
2142
- if (resolved == null)
2143
- return -1;
2144
- pos = resolved;
2145
- if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
2146
- result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
2147
- } else {
2148
- let i = this.rangeIndex, range = this.range;
2149
- while (range.to <= pos)
2150
- range = this.ranges[++i];
2151
- this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
2152
- if (pos + this.chunk2.length > range.to)
2153
- this.chunk2 = this.chunk2.slice(0, range.to - pos);
2154
- result = this.chunk2.charCodeAt(0);
2155
- }
2156
- }
2157
- if (pos >= this.token.lookAhead)
2158
- this.token.lookAhead = pos + 1;
2159
- return result;
2160
- }
2161
- /// Accept a token. By default, the end of the token is set to the
2162
- /// current stream position, but you can pass an offset (relative to
2163
- /// the stream position) to change that.
2164
- acceptToken(token, endOffset = 0) {
2165
- let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
2166
- if (end == null || end < this.token.start)
2167
- throw new RangeError("Token end out of bounds");
2168
- this.token.value = token;
2169
- this.token.end = end;
2170
- }
2171
- getChunk() {
2172
- if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
2173
- let { chunk, chunkPos } = this;
2174
- this.chunk = this.chunk2;
2175
- this.chunkPos = this.chunk2Pos;
2176
- this.chunk2 = chunk;
2177
- this.chunk2Pos = chunkPos;
2178
- this.chunkOff = this.pos - this.chunkPos;
2179
- } else {
2180
- this.chunk2 = this.chunk;
2181
- this.chunk2Pos = this.chunkPos;
2182
- let nextChunk = this.input.chunk(this.pos);
2183
- let end = this.pos + nextChunk.length;
2184
- this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
2185
- this.chunkPos = this.pos;
2186
- this.chunkOff = 0;
2187
- }
2188
- }
2189
- readNext() {
2190
- if (this.chunkOff >= this.chunk.length) {
2191
- this.getChunk();
2192
- if (this.chunkOff == this.chunk.length)
2193
- return this.next = -1;
2194
- }
2195
- return this.next = this.chunk.charCodeAt(this.chunkOff);
2196
- }
2197
- /// Move the stream forward N (defaults to 1) code units. Returns
2198
- /// the new value of [`next`](#lr.InputStream.next).
2199
- advance(n = 1) {
2200
- this.chunkOff += n;
2201
- while (this.pos + n >= this.range.to) {
2202
- if (this.rangeIndex == this.ranges.length - 1)
2203
- return this.setDone();
2204
- n -= this.range.to - this.pos;
2205
- this.range = this.ranges[++this.rangeIndex];
2206
- this.pos = this.range.from;
2207
- }
2208
- this.pos += n;
2209
- if (this.pos >= this.token.lookAhead)
2210
- this.token.lookAhead = this.pos + 1;
2211
- return this.readNext();
2212
- }
2213
- setDone() {
2214
- this.pos = this.chunkPos = this.end;
2215
- this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
2216
- this.chunk = "";
2217
- return this.next = -1;
2218
- }
2219
- /// @internal
2220
- reset(pos, token) {
2221
- if (token) {
2222
- this.token = token;
2223
- token.start = pos;
2224
- token.lookAhead = pos + 1;
2225
- token.value = token.extended = -1;
2226
- } else {
2227
- this.token = nullToken;
2228
- }
2229
- if (this.pos != pos) {
2230
- this.pos = pos;
2231
- if (pos == this.end) {
2232
- this.setDone();
2233
- return this;
2234
- }
2235
- while (pos < this.range.from)
2236
- this.range = this.ranges[--this.rangeIndex];
2237
- while (pos >= this.range.to)
2238
- this.range = this.ranges[++this.rangeIndex];
2239
- if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
2240
- this.chunkOff = pos - this.chunkPos;
2241
- } else {
2242
- this.chunk = "";
2243
- this.chunkOff = 0;
2244
- }
2245
- this.readNext();
2246
- }
2247
- return this;
2248
- }
2249
- /// @internal
2250
- read(from, to) {
2251
- if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
2252
- return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
2253
- if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
2254
- return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
2255
- if (from >= this.range.from && to <= this.range.to)
2256
- return this.input.read(from, to);
2257
- let result = "";
2258
- for (let r of this.ranges) {
2259
- if (r.from >= to)
2260
- break;
2261
- if (r.to > from)
2262
- result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
2263
- }
2264
- return result;
2265
- }
2266
- };
2267
- var TokenGroup = class {
2268
- constructor(data, id) {
2269
- this.data = data;
2270
- this.id = id;
2271
- }
2272
- token(input, stack) {
2273
- let { parser: parser2 } = stack.p;
2274
- readToken(this.data, input, stack, this.id, parser2.data, parser2.tokenPrecTable);
2275
- }
2276
- };
2277
- TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2278
- var LocalTokenGroup = class {
2279
- constructor(data, precTable, elseToken) {
2280
- this.precTable = precTable;
2281
- this.elseToken = elseToken;
2282
- this.data = typeof data == "string" ? decodeArray(data) : data;
2283
- }
2284
- token(input, stack) {
2285
- let start = input.pos, skipped = 0;
2286
- for (; ; ) {
2287
- readToken(this.data, input, stack, 0, this.data, this.precTable);
2288
- if (input.token.value > -1)
2289
- break;
2290
- if (this.elseToken == null)
2291
- return;
2292
- if (input.next < 0)
2293
- break;
2294
- input.advance();
2295
- input.reset(input.pos, input.token);
2296
- skipped++;
2297
- }
2298
- if (skipped) {
2299
- input.reset(start, input.token);
2300
- input.acceptToken(this.elseToken, skipped);
2301
- }
2302
- }
2303
- };
2304
- LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2305
- function readToken(data, input, stack, group, precTable, precOffset) {
2306
- let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
2307
- scan:
2308
- for (; ; ) {
2309
- if ((groupMask & data[state]) == 0)
2310
- break;
2311
- let accEnd = data[state + 1];
2312
- for (let i = state + 3; i < accEnd; i += 2)
2313
- if ((data[i + 1] & groupMask) > 0) {
2314
- let term = data[i];
2315
- if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
2316
- input.acceptToken(term);
2317
- break;
2318
- }
2319
- }
2320
- let next = input.next, low = 0, high = data[state + 2];
2321
- if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 && data[accEnd + high * 3 - 3] == 65535) {
2322
- state = data[accEnd + high * 3 - 1];
2323
- continue scan;
2324
- }
2325
- for (; low < high; ) {
2326
- let mid = low + high >> 1;
2327
- let index = accEnd + mid + (mid << 1);
2328
- let from = data[index], to = data[index + 1] || 65536;
2329
- if (next < from)
2330
- high = mid;
2331
- else if (next >= to)
2332
- low = mid + 1;
2333
- else {
2334
- state = data[index + 2];
2335
- input.advance();
2336
- continue scan;
2337
- }
2338
- }
2339
- break;
2340
- }
2341
- }
2342
- function findOffset(data, start, term) {
2343
- for (let i = start, next; (next = data[i]) != 65535; i++)
2344
- if (next == term)
2345
- return i - start;
2346
- return -1;
2347
- }
2348
- function overrides(token, prev, tableData, tableOffset) {
2349
- let iPrev = findOffset(tableData, tableOffset, prev);
2350
- return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
2351
- }
2352
- var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
2353
- var stackIDs = null;
2354
- var Safety;
2355
- (function(Safety2) {
2356
- Safety2[Safety2["Margin"] = 25] = "Margin";
2357
- })(Safety || (Safety = {}));
2358
- function cutAt(tree, pos, side) {
2359
- let cursor = tree.cursor(IterMode.IncludeAnonymous);
2360
- cursor.moveTo(pos);
2361
- for (; ; ) {
2362
- if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
2363
- for (; ; ) {
2364
- if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
2365
- return side < 0 ? Math.max(0, Math.min(
2366
- cursor.to - 1,
2367
- pos - 25
2368
- /* Safety.Margin */
2369
- )) : Math.min(tree.length, Math.max(
2370
- cursor.from + 1,
2371
- pos + 25
2372
- /* Safety.Margin */
2373
- ));
2374
- if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
2375
- break;
2376
- if (!cursor.parent())
2377
- return side < 0 ? 0 : tree.length;
2378
- }
2379
- }
2380
- }
2381
- var FragmentCursor = class {
2382
- constructor(fragments, nodeSet) {
2383
- this.fragments = fragments;
2384
- this.nodeSet = nodeSet;
2385
- this.i = 0;
2386
- this.fragment = null;
2387
- this.safeFrom = -1;
2388
- this.safeTo = -1;
2389
- this.trees = [];
2390
- this.start = [];
2391
- this.index = [];
2392
- this.nextFragment();
2393
- }
2394
- nextFragment() {
2395
- let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
2396
- if (fr) {
2397
- this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
2398
- this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
2399
- while (this.trees.length) {
2400
- this.trees.pop();
2401
- this.start.pop();
2402
- this.index.pop();
2403
- }
2404
- this.trees.push(fr.tree);
2405
- this.start.push(-fr.offset);
2406
- this.index.push(0);
2407
- this.nextStart = this.safeFrom;
2408
- } else {
2409
- this.nextStart = 1e9;
2410
- }
2411
- }
2412
- // `pos` must be >= any previously given `pos` for this cursor
2413
- nodeAt(pos) {
2414
- if (pos < this.nextStart)
2415
- return null;
2416
- while (this.fragment && this.safeTo <= pos)
2417
- this.nextFragment();
2418
- if (!this.fragment)
2419
- return null;
2420
- for (; ; ) {
2421
- let last = this.trees.length - 1;
2422
- if (last < 0) {
2423
- this.nextFragment();
2424
- return null;
2425
- }
2426
- let top = this.trees[last], index = this.index[last];
2427
- if (index == top.children.length) {
2428
- this.trees.pop();
2429
- this.start.pop();
2430
- this.index.pop();
2431
- continue;
2432
- }
2433
- let next = top.children[index];
2434
- let start = this.start[last] + top.positions[index];
2435
- if (start > pos) {
2436
- this.nextStart = start;
2437
- return null;
2438
- }
2439
- if (next instanceof Tree) {
2440
- if (start == pos) {
2441
- if (start < this.safeFrom)
2442
- return null;
2443
- let end = start + next.length;
2444
- if (end <= this.safeTo) {
2445
- let lookAhead = next.prop(NodeProp.lookAhead);
2446
- if (!lookAhead || end + lookAhead < this.fragment.to)
2447
- return next;
2448
- }
2449
- }
2450
- this.index[last]++;
2451
- if (start + next.length >= Math.max(this.safeFrom, pos)) {
2452
- this.trees.push(next);
2453
- this.start.push(start);
2454
- this.index.push(0);
2455
- }
2456
- } else {
2457
- this.index[last]++;
2458
- this.nextStart = start + next.length;
2459
- }
2460
- }
2461
- }
2462
- };
2463
- var TokenCache = class {
2464
- constructor(parser2, stream) {
2465
- this.stream = stream;
2466
- this.tokens = [];
2467
- this.mainToken = null;
2468
- this.actions = [];
2469
- this.tokens = parser2.tokenizers.map((_) => new CachedToken());
2470
- }
2471
- getActions(stack) {
2472
- let actionIndex = 0;
2473
- let main = null;
2474
- let { parser: parser2 } = stack.p, { tokenizers } = parser2;
2475
- let mask = parser2.stateSlot(
2476
- stack.state,
2477
- 3
2478
- /* ParseState.TokenizerMask */
2479
- );
2480
- let context = stack.curContext ? stack.curContext.hash : 0;
2481
- let lookAhead = 0;
2482
- for (let i = 0; i < tokenizers.length; i++) {
2483
- if ((1 << i & mask) == 0)
2484
- continue;
2485
- let tokenizer = tokenizers[i], token = this.tokens[i];
2486
- if (main && !tokenizer.fallback)
2487
- continue;
2488
- if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
2489
- this.updateCachedToken(token, tokenizer, stack);
2490
- token.mask = mask;
2491
- token.context = context;
2492
- }
2493
- if (token.lookAhead > token.end + 25)
2494
- lookAhead = Math.max(token.lookAhead, lookAhead);
2495
- if (token.value != 0) {
2496
- let startIndex = actionIndex;
2497
- if (token.extended > -1)
2498
- actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
2499
- actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
2500
- if (!tokenizer.extend) {
2501
- main = token;
2502
- if (actionIndex > startIndex)
2503
- break;
2504
- }
2505
- }
2506
- }
2507
- while (this.actions.length > actionIndex)
2508
- this.actions.pop();
2509
- if (lookAhead)
2510
- stack.setLookAhead(lookAhead);
2511
- if (!main && stack.pos == this.stream.end) {
2512
- main = new CachedToken();
2513
- main.value = stack.p.parser.eofTerm;
2514
- main.start = main.end = stack.pos;
2515
- actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
2516
- }
2517
- this.mainToken = main;
2518
- return this.actions;
2519
- }
2520
- getMainToken(stack) {
2521
- if (this.mainToken)
2522
- return this.mainToken;
2523
- let main = new CachedToken(), { pos, p } = stack;
2524
- main.start = pos;
2525
- main.end = Math.min(pos + 1, p.stream.end);
2526
- main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
2527
- return main;
2528
- }
2529
- updateCachedToken(token, tokenizer, stack) {
2530
- let start = this.stream.clipPos(stack.pos);
2531
- tokenizer.token(this.stream.reset(start, token), stack);
2532
- if (token.value > -1) {
2533
- let { parser: parser2 } = stack.p;
2534
- for (let i = 0; i < parser2.specialized.length; i++)
2535
- if (parser2.specialized[i] == token.value) {
2536
- let result = parser2.specializers[i](this.stream.read(token.start, token.end), stack);
2537
- if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
2538
- if ((result & 1) == 0)
2539
- token.value = result >> 1;
2540
- else
2541
- token.extended = result >> 1;
2542
- break;
2543
- }
2544
- }
2545
- } else {
2546
- token.value = 0;
2547
- token.end = this.stream.clipPos(start + 1);
2548
- }
2549
- }
2550
- putAction(action, token, end, index) {
2551
- for (let i = 0; i < index; i += 3)
2552
- if (this.actions[i] == action)
2553
- return index;
2554
- this.actions[index++] = action;
2555
- this.actions[index++] = token;
2556
- this.actions[index++] = end;
2557
- return index;
2558
- }
2559
- addActions(stack, token, end, index) {
2560
- let { state } = stack, { parser: parser2 } = stack.p, { data } = parser2;
2561
- for (let set = 0; set < 2; set++) {
2562
- for (let i = parser2.stateSlot(
2563
- state,
2564
- set ? 2 : 1
2565
- /* ParseState.Actions */
2566
- ); ; i += 3) {
2567
- if (data[i] == 65535) {
2568
- if (data[i + 1] == 1) {
2569
- i = pair(data, i + 2);
2570
- } else {
2571
- if (index == 0 && data[i + 1] == 2)
2572
- index = this.putAction(pair(data, i + 2), token, end, index);
2573
- break;
2574
- }
2575
- }
2576
- if (data[i] == token)
2577
- index = this.putAction(pair(data, i + 1), token, end, index);
2578
- }
2579
- }
2580
- return index;
2581
- }
2582
- };
2583
- var Rec;
2584
- (function(Rec2) {
2585
- Rec2[Rec2["Distance"] = 5] = "Distance";
2586
- Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
2587
- Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune";
2588
- Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit";
2589
- Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth";
2590
- Rec2[Rec2["CutTo"] = 9e3] = "CutTo";
2591
- Rec2[Rec2["MaxLeftAssociativeReductionCount"] = 300] = "MaxLeftAssociativeReductionCount";
2592
- Rec2[Rec2["MaxStackCount"] = 12] = "MaxStackCount";
2593
- })(Rec || (Rec = {}));
2594
- var Parse = class {
2595
- constructor(parser2, input, fragments, ranges) {
2596
- this.parser = parser2;
2597
- this.input = input;
2598
- this.ranges = ranges;
2599
- this.recovering = 0;
2600
- this.nextStackID = 9812;
2601
- this.minStackPos = 0;
2602
- this.reused = [];
2603
- this.stoppedAt = null;
2604
- this.lastBigReductionStart = -1;
2605
- this.lastBigReductionSize = 0;
2606
- this.bigReductionCount = 0;
2607
- this.stream = new InputStream(input, ranges);
2608
- this.tokens = new TokenCache(parser2, this.stream);
2609
- this.topTerm = parser2.top[1];
2610
- let { from } = ranges[0];
2611
- this.stacks = [Stack.start(this, parser2.top[0], from)];
2612
- this.fragments = fragments.length && this.stream.end - from > parser2.bufferLength * 4 ? new FragmentCursor(fragments, parser2.nodeSet) : null;
2613
- }
2614
- get parsedPos() {
2615
- return this.minStackPos;
2616
- }
2617
- // Move the parser forward. This will process all parse stacks at
2618
- // `this.pos` and try to advance them to a further position. If no
2619
- // stack for such a position is found, it'll start error-recovery.
2620
- //
2621
- // When the parse is finished, this will return a syntax tree. When
2622
- // not, it returns `null`.
2623
- advance() {
2624
- let stacks = this.stacks, pos = this.minStackPos;
2625
- let newStacks = this.stacks = [];
2626
- let stopped, stoppedTokens;
2627
- if (this.bigReductionCount > 300 && stacks.length == 1) {
2628
- let [s] = stacks;
2629
- while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) {
2630
- }
2631
- this.bigReductionCount = this.lastBigReductionSize = 0;
2632
- }
2633
- for (let i = 0; i < stacks.length; i++) {
2634
- let stack = stacks[i];
2635
- for (; ; ) {
2636
- this.tokens.mainToken = null;
2637
- if (stack.pos > pos) {
2638
- newStacks.push(stack);
2639
- } else if (this.advanceStack(stack, newStacks, stacks)) {
2640
- continue;
2641
- } else {
2642
- if (!stopped) {
2643
- stopped = [];
2644
- stoppedTokens = [];
2645
- }
2646
- stopped.push(stack);
2647
- let tok = this.tokens.getMainToken(stack);
2648
- stoppedTokens.push(tok.value, tok.end);
2649
- }
2650
- break;
2651
- }
2652
- }
2653
- if (!newStacks.length) {
2654
- let finished = stopped && findFinished(stopped);
2655
- if (finished)
2656
- return this.stackToTree(finished);
2657
- if (this.parser.strict) {
2658
- if (verbose && stopped)
2659
- console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
2660
- throw new SyntaxError("No parse at " + pos);
2661
- }
2662
- if (!this.recovering)
2663
- this.recovering = 5;
2664
- }
2665
- if (this.recovering && stopped) {
2666
- let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
2667
- if (finished)
2668
- return this.stackToTree(finished.forceAll());
2669
- }
2670
- if (this.recovering) {
2671
- let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
2672
- if (newStacks.length > maxRemaining) {
2673
- newStacks.sort((a, b) => b.score - a.score);
2674
- while (newStacks.length > maxRemaining)
2675
- newStacks.pop();
2676
- }
2677
- if (newStacks.some((s) => s.reducePos > pos))
2678
- this.recovering--;
2679
- } else if (newStacks.length > 1) {
2680
- outer:
2681
- for (let i = 0; i < newStacks.length - 1; i++) {
2682
- let stack = newStacks[i];
2683
- for (let j = i + 1; j < newStacks.length; j++) {
2684
- let other = newStacks[j];
2685
- if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) {
2686
- if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) {
2687
- newStacks.splice(j--, 1);
2688
- } else {
2689
- newStacks.splice(i--, 1);
2690
- continue outer;
2691
- }
2692
- }
2693
- }
2694
- }
2695
- if (newStacks.length > 12)
2696
- newStacks.splice(
2697
- 12,
2698
- newStacks.length - 12
2699
- /* Rec.MaxStackCount */
2700
- );
2701
- }
2702
- this.minStackPos = newStacks[0].pos;
2703
- for (let i = 1; i < newStacks.length; i++)
2704
- if (newStacks[i].pos < this.minStackPos)
2705
- this.minStackPos = newStacks[i].pos;
2706
- return null;
2707
- }
2708
- stopAt(pos) {
2709
- if (this.stoppedAt != null && this.stoppedAt < pos)
2710
- throw new RangeError("Can't move stoppedAt forward");
2711
- this.stoppedAt = pos;
2712
- }
2713
- // Returns an updated version of the given stack, or null if the
2714
- // stack can't advance normally. When `split` and `stacks` are
2715
- // given, stacks split off by ambiguous operations will be pushed to
2716
- // `split`, or added to `stacks` if they move `pos` forward.
2717
- advanceStack(stack, stacks, split) {
2718
- let start = stack.pos, { parser: parser2 } = this;
2719
- let base = verbose ? this.stackID(stack) + " -> " : "";
2720
- if (this.stoppedAt != null && start > this.stoppedAt)
2721
- return stack.forceReduce() ? stack : null;
2722
- if (this.fragments) {
2723
- let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
2724
- for (let cached = this.fragments.nodeAt(start); cached; ) {
2725
- let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser2.getGoto(stack.state, cached.type.id) : -1;
2726
- if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
2727
- stack.useNode(cached, match);
2728
- if (verbose)
2729
- console.log(base + this.stackID(stack) + ` (via reuse of ${parser2.getName(cached.type.id)})`);
2730
- return true;
2731
- }
2732
- if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
2733
- break;
2734
- let inner = cached.children[0];
2735
- if (inner instanceof Tree && cached.positions[0] == 0)
2736
- cached = inner;
2737
- else
2738
- break;
2739
- }
2740
- }
2741
- let defaultReduce = parser2.stateSlot(
2742
- stack.state,
2743
- 4
2744
- /* ParseState.DefaultReduce */
2745
- );
2746
- if (defaultReduce > 0) {
2747
- stack.reduce(defaultReduce);
2748
- if (verbose)
2749
- console.log(base + this.stackID(stack) + ` (via always-reduce ${parser2.getName(
2750
- defaultReduce & 65535
2751
- /* Action.ValueMask */
2752
- )})`);
2753
- return true;
2754
- }
2755
- if (stack.stack.length >= 15e3) {
2756
- while (stack.stack.length > 9e3 && stack.forceReduce()) {
2757
- }
2758
- }
2759
- let actions = this.tokens.getActions(stack);
2760
- for (let i = 0; i < actions.length; ) {
2761
- let action = actions[i++], term = actions[i++], end = actions[i++];
2762
- let last = i == actions.length || !split;
2763
- let localStack = last ? stack : stack.split();
2764
- localStack.apply(action, term, end);
2765
- if (verbose)
2766
- console.log(base + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser2.getName(
2767
- action & 65535
2768
- /* Action.ValueMask */
2769
- )}`} for ${parser2.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
2770
- if (last)
2771
- return true;
2772
- else if (localStack.pos > start)
2773
- stacks.push(localStack);
2774
- else
2775
- split.push(localStack);
2776
- }
2777
- return false;
2778
- }
2779
- // Advance a given stack forward as far as it will go. Returns the
2780
- // (possibly updated) stack if it got stuck, or null if it moved
2781
- // forward and was given to `pushStackDedup`.
2782
- advanceFully(stack, newStacks) {
2783
- let pos = stack.pos;
2784
- for (; ; ) {
2785
- if (!this.advanceStack(stack, null, null))
2786
- return false;
2787
- if (stack.pos > pos) {
2788
- pushStackDedup(stack, newStacks);
2789
- return true;
2790
- }
2791
- }
2792
- }
2793
- runRecovery(stacks, tokens, newStacks) {
2794
- let finished = null, restarted = false;
2795
- for (let i = 0; i < stacks.length; i++) {
2796
- let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
2797
- let base = verbose ? this.stackID(stack) + " -> " : "";
2798
- if (stack.deadEnd) {
2799
- if (restarted)
2800
- continue;
2801
- restarted = true;
2802
- stack.restart();
2803
- if (verbose)
2804
- console.log(base + this.stackID(stack) + " (restarted)");
2805
- let done = this.advanceFully(stack, newStacks);
2806
- if (done)
2807
- continue;
2808
- }
2809
- let force = stack.split(), forceBase = base;
2810
- for (let j = 0; force.forceReduce() && j < 10; j++) {
2811
- if (verbose)
2812
- console.log(forceBase + this.stackID(force) + " (via force-reduce)");
2813
- let done = this.advanceFully(force, newStacks);
2814
- if (done)
2815
- break;
2816
- if (verbose)
2817
- forceBase = this.stackID(force) + " -> ";
2818
- }
2819
- for (let insert of stack.recoverByInsert(token)) {
2820
- if (verbose)
2821
- console.log(base + this.stackID(insert) + " (via recover-insert)");
2822
- this.advanceFully(insert, newStacks);
2823
- }
2824
- if (this.stream.end > stack.pos) {
2825
- if (tokenEnd == stack.pos) {
2826
- tokenEnd++;
2827
- token = 0;
2828
- }
2829
- stack.recoverByDelete(token, tokenEnd);
2830
- if (verbose)
2831
- console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
2832
- pushStackDedup(stack, newStacks);
2833
- } else if (!finished || finished.score < stack.score) {
2834
- finished = stack;
2835
- }
2836
- }
2837
- return finished;
2838
- }
2839
- // Convert the stack's buffer to a syntax tree.
2840
- stackToTree(stack) {
2841
- stack.close();
2842
- return Tree.build({
2843
- buffer: StackBufferCursor.create(stack),
2844
- nodeSet: this.parser.nodeSet,
2845
- topID: this.topTerm,
2846
- maxBufferLength: this.parser.bufferLength,
2847
- reused: this.reused,
2848
- start: this.ranges[0].from,
2849
- length: stack.pos - this.ranges[0].from,
2850
- minRepeatType: this.parser.minRepeatTerm
2851
- });
2852
- }
2853
- stackID(stack) {
2854
- let id = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack);
2855
- if (!id)
2856
- stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
2857
- return id + stack;
2858
- }
2859
- };
2860
- function pushStackDedup(stack, newStacks) {
2861
- for (let i = 0; i < newStacks.length; i++) {
2862
- let other = newStacks[i];
2863
- if (other.pos == stack.pos && other.sameState(stack)) {
2864
- if (newStacks[i].score < stack.score)
2865
- newStacks[i] = stack;
2866
- return;
2867
- }
2868
- }
2869
- newStacks.push(stack);
2870
- }
2871
- var Dialect = class {
2872
- constructor(source, flags, disabled) {
2873
- this.source = source;
2874
- this.flags = flags;
2875
- this.disabled = disabled;
2876
- }
2877
- allows(term) {
2878
- return !this.disabled || this.disabled[term] == 0;
2879
- }
2880
- };
2881
- var LRParser = class extends Parser {
2882
- /// @internal
2883
- constructor(spec) {
2884
- super();
2885
- this.wrappers = [];
2886
- if (spec.version != 14)
2887
- throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
2888
- let nodeNames = spec.nodeNames.split(" ");
2889
- this.minRepeatTerm = nodeNames.length;
2890
- for (let i = 0; i < spec.repeatNodeCount; i++)
2891
- nodeNames.push("");
2892
- let topTerms = Object.keys(spec.topRules).map((r) => spec.topRules[r][1]);
2893
- let nodeProps = [];
2894
- for (let i = 0; i < nodeNames.length; i++)
2895
- nodeProps.push([]);
2896
- function setProp(nodeID, prop, value) {
2897
- nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
2898
- }
2899
- if (spec.nodeProps)
2900
- for (let propSpec of spec.nodeProps) {
2901
- let prop = propSpec[0];
2902
- if (typeof prop == "string")
2903
- prop = NodeProp[prop];
2904
- for (let i = 1; i < propSpec.length; ) {
2905
- let next = propSpec[i++];
2906
- if (next >= 0) {
2907
- setProp(next, prop, propSpec[i++]);
2908
- } else {
2909
- let value = propSpec[i + -next];
2910
- for (let j = -next; j > 0; j--)
2911
- setProp(propSpec[i++], prop, value);
2912
- i++;
2913
- }
2914
- }
2915
- }
2916
- this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
2917
- name: i >= this.minRepeatTerm ? void 0 : name,
2918
- id: i,
2919
- props: nodeProps[i],
2920
- top: topTerms.indexOf(i) > -1,
2921
- error: i == 0,
2922
- skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
2923
- })));
2924
- if (spec.propSources)
2925
- this.nodeSet = this.nodeSet.extend(...spec.propSources);
2926
- this.strict = false;
2927
- this.bufferLength = DefaultBufferLength;
2928
- let tokenArray = decodeArray(spec.tokenData);
2929
- this.context = spec.context;
2930
- this.specializerSpecs = spec.specialized || [];
2931
- this.specialized = new Uint16Array(this.specializerSpecs.length);
2932
- for (let i = 0; i < this.specializerSpecs.length; i++)
2933
- this.specialized[i] = this.specializerSpecs[i].term;
2934
- this.specializers = this.specializerSpecs.map(getSpecializer);
2935
- this.states = decodeArray(spec.states, Uint32Array);
2936
- this.data = decodeArray(spec.stateData);
2937
- this.goto = decodeArray(spec.goto);
2938
- this.maxTerm = spec.maxTerm;
2939
- this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
2940
- this.topRules = spec.topRules;
2941
- this.dialects = spec.dialects || {};
2942
- this.dynamicPrecedences = spec.dynamicPrecedences || null;
2943
- this.tokenPrecTable = spec.tokenPrec;
2944
- this.termNames = spec.termNames || null;
2945
- this.maxNode = this.nodeSet.types.length - 1;
2946
- this.dialect = this.parseDialect();
2947
- this.top = this.topRules[Object.keys(this.topRules)[0]];
2948
- }
2949
- createParse(input, fragments, ranges) {
2950
- let parse = new Parse(this, input, fragments, ranges);
2951
- for (let w of this.wrappers)
2952
- parse = w(parse, input, fragments, ranges);
2953
- return parse;
2954
- }
2955
- /// Get a goto table entry @internal
2956
- getGoto(state, term, loose = false) {
2957
- let table = this.goto;
2958
- if (term >= table[0])
2959
- return -1;
2960
- for (let pos = table[term + 1]; ; ) {
2961
- let groupTag = table[pos++], last = groupTag & 1;
2962
- let target = table[pos++];
2963
- if (last && loose)
2964
- return target;
2965
- for (let end = pos + (groupTag >> 1); pos < end; pos++)
2966
- if (table[pos] == state)
2967
- return target;
2968
- if (last)
2969
- return -1;
2970
- }
2971
- }
2972
- /// Check if this state has an action for a given terminal @internal
2973
- hasAction(state, terminal) {
2974
- let data = this.data;
2975
- for (let set = 0; set < 2; set++) {
2976
- for (let i = this.stateSlot(
2977
- state,
2978
- set ? 2 : 1
2979
- /* ParseState.Actions */
2980
- ), next; ; i += 3) {
2981
- if ((next = data[i]) == 65535) {
2982
- if (data[i + 1] == 1)
2983
- next = data[i = pair(data, i + 2)];
2984
- else if (data[i + 1] == 2)
2985
- return pair(data, i + 2);
2986
- else
2987
- break;
2988
- }
2989
- if (next == terminal || next == 0)
2990
- return pair(data, i + 1);
2991
- }
2992
- }
2993
- return 0;
2994
- }
2995
- /// @internal
2996
- stateSlot(state, slot) {
2997
- return this.states[state * 6 + slot];
2998
- }
2999
- /// @internal
3000
- stateFlag(state, flag) {
3001
- return (this.stateSlot(
3002
- state,
3003
- 0
3004
- /* ParseState.Flags */
3005
- ) & flag) > 0;
3006
- }
3007
- /// @internal
3008
- validAction(state, action) {
3009
- if (action == this.stateSlot(
3010
- state,
3011
- 4
3012
- /* ParseState.DefaultReduce */
3013
- ))
3014
- return true;
3015
- for (let i = this.stateSlot(
3016
- state,
3017
- 1
3018
- /* ParseState.Actions */
3019
- ); ; i += 3) {
3020
- if (this.data[i] == 65535) {
3021
- if (this.data[i + 1] == 1)
3022
- i = pair(this.data, i + 2);
3023
- else
3024
- return false;
3025
- }
3026
- if (action == pair(this.data, i + 1))
3027
- return true;
3028
- }
3029
- }
3030
- /// Get the states that can follow this one through shift actions or
3031
- /// goto jumps. @internal
3032
- nextStates(state) {
3033
- let result = [];
3034
- for (let i = this.stateSlot(
3035
- state,
3036
- 1
3037
- /* ParseState.Actions */
3038
- ); ; i += 3) {
3039
- if (this.data[i] == 65535) {
3040
- if (this.data[i + 1] == 1)
3041
- i = pair(this.data, i + 2);
3042
- else
3043
- break;
3044
- }
3045
- if ((this.data[i + 2] & 65536 >> 16) == 0) {
3046
- let value = this.data[i + 1];
3047
- if (!result.some((v, i2) => i2 & 1 && v == value))
3048
- result.push(this.data[i], value);
3049
- }
3050
- }
3051
- return result;
3052
- }
3053
- /// Configure the parser. Returns a new parser instance that has the
3054
- /// given settings modified. Settings not provided in `config` are
3055
- /// kept from the original parser.
3056
- configure(config) {
3057
- let copy = Object.assign(Object.create(LRParser.prototype), this);
3058
- if (config.props)
3059
- copy.nodeSet = this.nodeSet.extend(...config.props);
3060
- if (config.top) {
3061
- let info = this.topRules[config.top];
3062
- if (!info)
3063
- throw new RangeError(`Invalid top rule name ${config.top}`);
3064
- copy.top = info;
3065
- }
3066
- if (config.tokenizers)
3067
- copy.tokenizers = this.tokenizers.map((t) => {
3068
- let found = config.tokenizers.find((r) => r.from == t);
3069
- return found ? found.to : t;
3070
- });
3071
- if (config.specializers) {
3072
- copy.specializers = this.specializers.slice();
3073
- copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
3074
- let found = config.specializers.find((r) => r.from == s.external);
3075
- if (!found)
3076
- return s;
3077
- let spec = Object.assign(Object.assign({}, s), { external: found.to });
3078
- copy.specializers[i] = getSpecializer(spec);
3079
- return spec;
3080
- });
3081
- }
3082
- if (config.contextTracker)
3083
- copy.context = config.contextTracker;
3084
- if (config.dialect)
3085
- copy.dialect = this.parseDialect(config.dialect);
3086
- if (config.strict != null)
3087
- copy.strict = config.strict;
3088
- if (config.wrap)
3089
- copy.wrappers = copy.wrappers.concat(config.wrap);
3090
- if (config.bufferLength != null)
3091
- copy.bufferLength = config.bufferLength;
3092
- return copy;
3093
- }
3094
- /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
3095
- /// are registered for this parser.
3096
- hasWrappers() {
3097
- return this.wrappers.length > 0;
3098
- }
3099
- /// Returns the name associated with a given term. This will only
3100
- /// work for all terms when the parser was generated with the
3101
- /// `--names` option. By default, only the names of tagged terms are
3102
- /// stored.
3103
- getName(term) {
3104
- return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
3105
- }
3106
- /// The eof term id is always allocated directly after the node
3107
- /// types. @internal
3108
- get eofTerm() {
3109
- return this.maxNode + 1;
3110
- }
3111
- /// The type of top node produced by the parser.
3112
- get topNode() {
3113
- return this.nodeSet.types[this.top[1]];
3114
- }
3115
- /// @internal
3116
- dynamicPrecedence(term) {
3117
- let prec = this.dynamicPrecedences;
3118
- return prec == null ? 0 : prec[term] || 0;
3119
- }
3120
- /// @internal
3121
- parseDialect(dialect) {
3122
- let values = Object.keys(this.dialects), flags = values.map(() => false);
3123
- if (dialect)
3124
- for (let part of dialect.split(" ")) {
3125
- let id = values.indexOf(part);
3126
- if (id >= 0)
3127
- flags[id] = true;
3128
- }
3129
- let disabled = null;
3130
- for (let i = 0; i < values.length; i++)
3131
- if (!flags[i]) {
3132
- for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535; )
3133
- (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
3134
- }
3135
- return new Dialect(dialect, flags, disabled);
3136
- }
3137
- /// Used by the output of the parser generator. Not available to
3138
- /// user code. @hide
3139
- static deserialize(spec) {
3140
- return new LRParser(spec);
3141
- }
3142
- };
3143
- function pair(data, off) {
3144
- return data[off] | data[off + 1] << 16;
3145
- }
3146
- function findFinished(stacks) {
3147
- let best = null;
3148
- for (let stack of stacks) {
3149
- let stopped = stack.p.stoppedAt;
3150
- if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(
3151
- stack.state,
3152
- 2
3153
- /* StateFlag.Accepting */
3154
- ) && (!best || best.score < stack.score))
3155
- best = stack;
3156
- }
3157
- return best;
3158
- }
3159
- function getSpecializer(spec) {
3160
- if (spec.external) {
3161
- let mask = spec.extend ? 1 : 0;
3162
- return (value, stack) => spec.external(value, stack) << 1 | mask;
3163
- }
3164
- return spec.get;
3165
- }
3166
-
3167
- // ../vuu-filter-parser/src/generated/filter-parser.js
3168
- var parser = LRParser.deserialize({
3169
- version: 14,
3170
- states: "%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",
3171
- stateData: "#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",
3172
- goto: "#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",
3173
- nodeNames: "\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",
3174
- maxTerm: 39,
3175
- skippedNodes: [0],
3176
- repeatNodeCount: 1,
3177
- tokenData: "6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",
3178
- tokenizers: [0, 1],
3179
- topRules: { "Filter": [0, 1] },
3180
- tokenPrec: 0
3181
- });
3182
-
3183
- // ../vuu-filter-parser/src/FilterTreeWalker.ts
3184
- import {
3185
- isMultiClauseFilter,
3186
- isMultiValueFilter,
3187
- isSingleValueFilter
3188
- } from "@vuu-ui/vuu-utils";
3189
- var _filter;
3190
- var FilterExpression = class {
3191
- constructor() {
3192
- __privateAdd(this, _filter, void 0);
3193
- }
3194
- setFilterCombinatorOp(op, filter = __privateGet(this, _filter)) {
3195
- if (isMultiClauseFilter(filter) && filter.op === op) {
3196
- return;
3197
- } else {
3198
- __privateSet(this, _filter, {
3199
- op,
3200
- filters: [__privateGet(this, _filter)]
3201
- });
3202
- }
3203
- }
3204
- add(filter) {
3205
- if (__privateGet(this, _filter) === void 0) {
3206
- __privateSet(this, _filter, filter);
3207
- } else if (isMultiClauseFilter(__privateGet(this, _filter))) {
3208
- __privateGet(this, _filter).filters.push(filter);
3209
- } else {
3210
- throw Error(`Invalid filter passed to FilterExpression`);
3211
- }
3212
- }
3213
- setColumn(column, filter = __privateGet(this, _filter)) {
3214
- if (isMultiClauseFilter(filter)) {
3215
- const target = filter.filters.at(-1);
3216
- if (target) {
3217
- this.setColumn(column, target);
3218
- }
3219
- } else if (filter) {
3220
- filter.column = column;
3221
- }
3222
- }
3223
- setOp(value, filter = __privateGet(this, _filter)) {
3224
- if (isMultiClauseFilter(filter)) {
3225
- const target = filter.filters.at(-1);
3226
- if (target) {
3227
- this.setOp(value, target);
3228
- }
3229
- } else if (filter) {
3230
- filter.op = value;
3231
- }
3232
- }
3233
- setValue(value, filter = __privateGet(this, _filter)) {
3234
- var _a;
3235
- if (isMultiClauseFilter(filter)) {
3236
- const target = filter.filters.at(-1);
3237
- if (target) {
3238
- this.setValue(value, target);
3239
- }
3240
- } else if (isMultiValueFilter(filter)) {
3241
- (_a = filter.values) != null ? _a : filter.values = [];
3242
- filter.values.push(value);
3243
- } else if (isSingleValueFilter(filter)) {
3244
- filter.value = value;
3245
- }
3246
- }
3247
- toJSON(filter = __privateGet(this, _filter)) {
3248
- if (this.name) {
3249
- return {
3250
- ...filter,
3251
- name: this.name
3252
- };
3253
- } else {
3254
- return filter;
3255
- }
3256
- }
3257
- };
3258
- _filter = new WeakMap();
3259
- var walkTree = (tree, source) => {
3260
- const filterExpression = new FilterExpression();
3261
- const cursor = tree.cursor();
3262
- do {
3263
- const { name, from, to } = cursor;
3264
- switch (name) {
3265
- case "ColumnValueExpression":
3266
- filterExpression.add({});
3267
- break;
3268
- case "ColumnSetExpression":
3269
- filterExpression.add({ op: "in" });
3270
- break;
3271
- case "Or":
3272
- case "And":
3273
- filterExpression.setFilterCombinatorOp(source.substring(from, to));
3274
- break;
3275
- case "Column":
3276
- filterExpression.setColumn(source.substring(from, to));
3277
- break;
3278
- case "Operator":
3279
- filterExpression.setOp(source.substring(from, to));
3280
- break;
3281
- case "String":
3282
- filterExpression.setValue(source.substring(from + 1, to - 1));
3283
- break;
3284
- case "Number":
3285
- filterExpression.setValue(parseFloat(source.substring(from, to)));
3286
- break;
3287
- case "True":
3288
- filterExpression.setValue(true);
3289
- break;
3290
- case "False":
3291
- filterExpression.setValue(false);
3292
- break;
3293
- case "FilterName":
3294
- filterExpression.name = source.substring(from, to);
3295
- break;
3296
- default:
3297
- }
3298
- } while (cursor.next());
3299
- return filterExpression.toJSON();
3300
- };
3301
-
3302
- // ../vuu-filter-parser/src/FilterParser.ts
3303
- var strictParser = parser.configure({ strict: true });
3304
- var parseFilter = (filterQuery) => {
3305
- const parseTree = strictParser.parse(filterQuery);
3306
- const filter = walkTree(parseTree, filterQuery);
3307
- return filter;
3308
- };
3309
-
3310
- // ../vuu-filter-parser/src/filter-evaluation-utils.ts
3311
- var filterPredicateMap = /* @__PURE__ */ new Map();
3312
- var filterReject = () => false;
3313
- var getFilterPredicate = (columnMap, filterQuery) => {
3314
- let predicate = filterPredicateMap.get(filterQuery);
3315
- if (predicate) {
3316
- return predicate;
3317
- }
3318
- try {
3319
- const filter = parseFilter(filterQuery);
3320
- predicate = filterPredicate(columnMap, filter);
3321
- filterPredicateMap.set(filterQuery, predicate);
3322
- return predicate;
3323
- } catch (err) {
3324
- console.warn(
3325
- `filter-evaluation-utils, failed to parse filter "${filterQuery}"`
3326
- );
3327
- return filterReject;
3328
- }
3329
- };
3330
- function filterPredicate(columnMap, filter) {
3331
- switch (filter.op) {
3332
- case "in":
3333
- return testInclude(columnMap, filter);
3334
- case "=":
3335
- return testEQ(columnMap, filter);
3336
- case ">":
3337
- return testGT(columnMap, filter);
3338
- case ">=":
3339
- return testGE(columnMap, filter);
3340
- case "<":
3341
- return testLT(columnMap, filter);
3342
- case "<=":
3343
- return testLE(columnMap, filter);
3344
- case "starts":
3345
- return testSW(columnMap, filter);
3346
- case "and":
3347
- return testAND(columnMap, filter);
3348
- case "or":
3349
- return testOR(columnMap, filter);
3350
- default:
3351
- console.log(`unrecognized filter type ${filter.op}`);
3352
- return () => true;
3353
- }
3354
- }
3355
- var testInclude = (columnMap, filter) => {
3356
- return (row) => filter.values.indexOf(row[columnMap[filter.column]]) !== -1;
3357
- };
3358
- var testEQ = (columnMap, filter) => {
3359
- return (row) => row[columnMap[filter.column]] === filter.value;
3360
- };
3361
- var testGT = (columnMap, filter) => {
3362
- return (row) => row[columnMap[filter.column]] > filter.value;
3363
- };
3364
- var testGE = (columnMap, filter) => {
3365
- return (row) => row[columnMap[filter.column]] >= filter.value;
3366
- };
3367
- var testLT = (columnMap, filter) => {
3368
- return (row) => row[columnMap[filter.column]] < filter.value;
3369
- };
3370
- var testLE = (columnMap, filter) => {
3371
- return (row) => row[columnMap[filter.column]] <= filter.value;
3372
- };
3373
- var testSW = (columnMap, filter) => {
3374
- const filterValue = filter.value;
3375
- if (typeof filterValue !== "string") {
3376
- throw Error("string filter applied to value of wrong type");
3377
- }
3378
- return (row) => {
3379
- const rowValue = row[columnMap[filter.column]];
3380
- if (typeof rowValue !== "string") {
3381
- throw Error("string filter applied to value of wrong type");
3382
- }
3383
- return rowValue.toLowerCase().startsWith(filterValue.toLowerCase());
3384
- };
3385
- };
3386
- var testAND = (columnMap, filter) => {
3387
- const filters = filter.filters.map((f1) => filterPredicate(columnMap, f1));
3388
- return (row) => filters.every((fn) => fn(row));
3389
- };
3390
- function testOR(columnMap, filter) {
3391
- const filters = filter.filters.map((f1) => filterPredicate(columnMap, f1));
3392
- return (row) => filters.some((fn) => fn(row));
3393
- }
3394
-
3395
217
  // src/hooks/useVuuMenuActions.ts
218
+ import { getFilterPredicate } from "@vuu-ui/vuu-filter-parser";
3396
219
  import {
3397
220
  getRowRecord,
3398
221
  isGroupMenuItemDescriptor,
@@ -3430,14 +253,14 @@ var vuuContextCompatibleWithTableLocation = (uiLocation, vuuContext, selectedRow
3430
253
  };
3431
254
  var gridRowMeetsFilterCriteria = (context, row, selectedRows, filter, columnMap) => {
3432
255
  if (context === "cell" || context === "row") {
3433
- const filterPredicate2 = getFilterPredicate(columnMap, filter);
3434
- return filterPredicate2(row);
256
+ const filterPredicate = getFilterPredicate(columnMap, filter);
257
+ return filterPredicate(row);
3435
258
  } else if (context === "selected-rows") {
3436
259
  if (selectedRows.length === 0) {
3437
260
  return false;
3438
261
  } else {
3439
- const filterPredicate2 = getFilterPredicate(columnMap, filter);
3440
- return selectedRows.every(filterPredicate2);
262
+ const filterPredicate = getFilterPredicate(columnMap, filter);
263
+ return selectedRows.every(filterPredicate);
3441
264
  }
3442
265
  }
3443
266
  return true;