@vuu-ui/vuu-data-local 0.8.33 → 0.8.34

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