@es-joy/jsoe 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/CHANGES.md +37 -0
  2. package/README.md +3 -1
  3. package/badges/coverage-badge.svg +1 -1
  4. package/badges/tests-badge.svg +1 -0
  5. package/dist/formats/schema.d.ts +11 -0
  6. package/dist/formats/schema.d.ts.map +1 -1
  7. package/dist/formats/structuredCloning.d.ts.map +1 -1
  8. package/dist/fundamentalTypes/arrayType.d.ts.map +1 -1
  9. package/dist/fundamentalTypes/stringType.d.ts.map +1 -1
  10. package/dist/index.js +2 -2
  11. package/dist/index.js.map +1 -1
  12. package/dist/typeChoices.d.ts +32 -2
  13. package/dist/typeChoices.d.ts.map +1 -1
  14. package/dist/types.d.ts +8 -2
  15. package/dist/types.d.ts.map +1 -1
  16. package/dist/utils/rawTypesonEditor.d.ts +110 -0
  17. package/dist/utils/rawTypesonEditor.d.ts.map +1 -0
  18. package/dist/vendor-imports.d.ts +4 -0
  19. package/docs/proposals/raw-typeson-edit-view.md +575 -0
  20. package/mmr.json +6 -0
  21. package/package.json +34 -12
  22. package/pnpm-workspace.yaml +32 -30
  23. package/src/formats/schema.js +10 -15
  24. package/src/formats/structuredCloning.js +24 -17
  25. package/src/fundamentalTypes/arrayType.js +119 -23
  26. package/src/fundamentalTypes/blobType.js +16 -16
  27. package/src/fundamentalTypes/fileType.js +13 -13
  28. package/src/fundamentalTypes/regexpType.js +1 -1
  29. package/src/fundamentalTypes/stringType.js +5 -0
  30. package/src/jsoe.css +12 -0
  31. package/src/subTypes/blobHTMLType.js +1 -1
  32. package/src/superTypes/dommatrixType.js +1 -1
  33. package/src/superTypes/errorsSpecialType.js +1 -1
  34. package/src/typeChoices.js +37 -10
  35. package/src/types.js +13 -8
  36. package/src/utils/media.js +3 -3
  37. package/src/utils/rawTypesonEditor.js +669 -0
  38. package/src/vendor-imports.js +12 -0
  39. package/tsconfig.json +1 -1
  40. package/typings/json-6.d.ts +12 -0
  41. package/vendor/@codemirror/autocomplete/dist/index.js +2125 -0
  42. package/vendor/@codemirror/commands/dist/index.js +1826 -0
  43. package/vendor/@codemirror/lang-javascript/dist/index.js +513 -0
  44. package/vendor/@codemirror/language/dist/index.js +2693 -0
  45. package/vendor/@codemirror/lint/dist/index.js +956 -0
  46. package/vendor/@codemirror/search/dist/index.js +1238 -0
  47. package/vendor/@codemirror/state/dist/index.js +3947 -0
  48. package/vendor/@codemirror/view/dist/index.js +11867 -0
  49. package/vendor/@lezer/common/dist/index.js +2202 -0
  50. package/vendor/@lezer/highlight/dist/index.js +927 -0
  51. package/vendor/@lezer/javascript/dist/index.js +192 -0
  52. package/vendor/@lezer/lr/dist/index.js +1889 -0
  53. package/vendor/@marijn/find-cluster-break/src/index.js +87 -0
  54. package/vendor/codemirror/dist/index.js +96 -0
  55. package/vendor/crelt/index.js +28 -0
  56. package/vendor/jamilih/dist/jml.mjs +898 -25
  57. package/vendor/json-6/dist/index.mjs +1783 -0
  58. package/vendor/style-mod/src/style-mod.js +172 -0
  59. package/vendor/w3c-keyname/index.js +119 -0
  60. package/vendor/zod/classic/checks.d.ts +1 -1
  61. package/vendor/zod/classic/checks.js +1 -1
  62. package/vendor/zod/classic/schemas.d.ts +2 -6
  63. package/vendor/zod/classic/schemas.js +9 -13
  64. package/vendor/zod/core/api.d.ts +8 -4
  65. package/vendor/zod/core/api.js +11 -23
  66. package/vendor/zod/core/checks.d.ts +16 -0
  67. package/vendor/zod/core/checks.js +31 -0
  68. package/vendor/zod/core/compile.js +20 -24
  69. package/vendor/zod/core/core.js +1 -1
  70. package/vendor/zod/core/json-schema-processors.d.ts +0 -1
  71. package/vendor/zod/core/json-schema-processors.js +8 -43
  72. package/vendor/zod/core/memoizer.js +2 -5
  73. package/vendor/zod/core/regexes.d.ts +1 -0
  74. package/vendor/zod/core/regexes.js +2 -0
  75. package/vendor/zod/core/schemas.d.ts +8 -23
  76. package/vendor/zod/core/schemas.js +39 -80
  77. package/vendor/zod/core/to-json-schema.d.ts +0 -3
  78. package/vendor/zod/core/to-json-schema.js +1 -1
  79. package/vendor/zod/core/util.js +0 -4
  80. package/vendor/zod/core/versions.js +1 -1
  81. package/vendor/zod/core/visit.js +0 -12
  82. package/vendor/zod/locales/ar.js +1 -0
  83. package/vendor/zod/locales/az.js +1 -0
  84. package/vendor/zod/locales/be.js +1 -0
  85. package/vendor/zod/locales/bg.js +1 -0
  86. package/vendor/zod/locales/bn.js +1 -0
  87. package/vendor/zod/locales/ca.js +1 -0
  88. package/vendor/zod/locales/ckb.js +1 -0
  89. package/vendor/zod/locales/cs.js +1 -0
  90. package/vendor/zod/locales/da.js +1 -0
  91. package/vendor/zod/locales/de.js +1 -0
  92. package/vendor/zod/locales/el.js +1 -0
  93. package/vendor/zod/locales/en.js +1 -0
  94. package/vendor/zod/locales/eo.js +1 -0
  95. package/vendor/zod/locales/es.js +1 -0
  96. package/vendor/zod/locales/fa.js +1 -0
  97. package/vendor/zod/locales/fi.js +1 -0
  98. package/vendor/zod/locales/fr-CA.js +1 -0
  99. package/vendor/zod/locales/fr.js +1 -0
  100. package/vendor/zod/locales/gu.js +1 -0
  101. package/vendor/zod/locales/he.js +1 -0
  102. package/vendor/zod/locales/hi.js +1 -0
  103. package/vendor/zod/locales/hr.js +1 -0
  104. package/vendor/zod/locales/hu.js +1 -0
  105. package/vendor/zod/locales/hy.js +1 -0
  106. package/vendor/zod/locales/id.js +1 -0
  107. package/vendor/zod/locales/is.js +1 -0
  108. package/vendor/zod/locales/it.js +1 -0
  109. package/vendor/zod/locales/ja.js +1 -0
  110. package/vendor/zod/locales/ka.js +1 -0
  111. package/vendor/zod/locales/km.js +1 -0
  112. package/vendor/zod/locales/kn.js +1 -0
  113. package/vendor/zod/locales/ko.js +1 -0
  114. package/vendor/zod/locales/lt.js +1 -0
  115. package/vendor/zod/locales/mk.js +1 -0
  116. package/vendor/zod/locales/ms.js +1 -0
  117. package/vendor/zod/locales/ne.js +1 -0
  118. package/vendor/zod/locales/nl.js +1 -0
  119. package/vendor/zod/locales/nn.js +1 -0
  120. package/vendor/zod/locales/no.js +1 -0
  121. package/vendor/zod/locales/ota.js +1 -0
  122. package/vendor/zod/locales/pl.js +1 -0
  123. package/vendor/zod/locales/ps.js +1 -0
  124. package/vendor/zod/locales/pt-BR.js +1 -0
  125. package/vendor/zod/locales/pt.js +1 -0
  126. package/vendor/zod/locales/ro.js +1 -0
  127. package/vendor/zod/locales/ru.js +1 -0
  128. package/vendor/zod/locales/sk.js +1 -0
  129. package/vendor/zod/locales/sl.js +1 -0
  130. package/vendor/zod/locales/sv.js +1 -0
  131. package/vendor/zod/locales/ta.js +1 -0
  132. package/vendor/zod/locales/tg.js +1 -0
  133. package/vendor/zod/locales/th.js +1 -0
  134. package/vendor/zod/locales/tk.js +1 -0
  135. package/vendor/zod/locales/tr.js +1 -0
  136. package/vendor/zod/locales/uk.js +1 -0
  137. package/vendor/zod/locales/ur.js +1 -0
  138. package/vendor/zod/locales/uz.js +1 -0
  139. package/vendor/zod/locales/vi.js +1 -0
  140. package/vendor/zod/locales/yo.js +1 -0
  141. package/vendor/zod/locales/zh-CN.js +1 -0
  142. package/vendor/zod/locales/zh-TW.js +1 -0
  143. package/vendor/zod/mini/checks.d.ts +1 -1
  144. package/vendor/zod/mini/checks.js +1 -1
  145. package/vendor/zod/mini/schemas.d.ts +2 -5
  146. package/vendor/zod/mini/schemas.js +9 -11
  147. package/vendor/zodexy/dist/esm/index.js +4 -33
  148. package/vendor/zodexy/dist/schema.zodexy.json +1 -17
@@ -0,0 +1,1889 @@
1
+ import { Parser, NodeProp, NodeSet, NodeType, DefaultBufferLength, Tree, IterMode } from '@lezer/common';
2
+
3
+ /**
4
+ A parse stack. These are used internally by the parser to track
5
+ parsing progress. They also provide some properties and methods
6
+ that external code such as a tokenizer can use to get information
7
+ about the parse state.
8
+ */
9
+ class Stack {
10
+ /**
11
+ @internal
12
+ */
13
+ constructor(
14
+ /**
15
+ The parse that this stack is part of @internal
16
+ */
17
+ p,
18
+ /**
19
+ Holds state, input pos, buffer index triplets for all but the
20
+ top state @internal
21
+ */
22
+ stack,
23
+ /**
24
+ The current parse state @internal
25
+ */
26
+ state,
27
+ // The position at which the next reduce should take place. This
28
+ // can be less than `this.pos` when skipped expressions have been
29
+ // added to the stack (which should be moved outside of the next
30
+ // reduction)
31
+ /**
32
+ @internal
33
+ */
34
+ reducePos,
35
+ /**
36
+ The input position up to which this stack has parsed.
37
+ */
38
+ pos,
39
+ /**
40
+ The dynamic score of the stack, including dynamic precedence
41
+ and error-recovery penalties
42
+ @internal
43
+ */
44
+ score,
45
+ // The output buffer. Holds (type, start, end, size) quads
46
+ // representing nodes created by the parser, where `size` is
47
+ // amount of buffer array entries covered by this node.
48
+ /**
49
+ @internal
50
+ */
51
+ buffer,
52
+ // The base offset of the buffer. When stacks are split, the split
53
+ // instance shared the buffer history with its parent up to
54
+ // `bufferBase`, which is the absolute offset (including the
55
+ // offset of previous splits) into the buffer at which this stack
56
+ // starts writing.
57
+ /**
58
+ @internal
59
+ */
60
+ bufferBase,
61
+ /**
62
+ @internal
63
+ */
64
+ curContext,
65
+ /**
66
+ @internal
67
+ */
68
+ lookAhead = 0,
69
+ // A parent stack from which this was split off, if any. This is
70
+ // set up so that it always points to a stack that has some
71
+ // additional buffer content, never to a stack with an equal
72
+ // `bufferBase`.
73
+ /**
74
+ @internal
75
+ */
76
+ parent) {
77
+ this.p = p;
78
+ this.stack = stack;
79
+ this.state = state;
80
+ this.reducePos = reducePos;
81
+ this.pos = pos;
82
+ this.score = score;
83
+ this.buffer = buffer;
84
+ this.bufferBase = bufferBase;
85
+ this.curContext = curContext;
86
+ this.lookAhead = lookAhead;
87
+ this.parent = parent;
88
+ }
89
+ /**
90
+ @internal
91
+ */
92
+ toString() {
93
+ return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
94
+ }
95
+ // Start an empty stack
96
+ /**
97
+ @internal
98
+ */
99
+ static start(p, state, pos = 0) {
100
+ let cx = p.parser.context;
101
+ return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
102
+ }
103
+ /**
104
+ The stack's current [context](#lr.ContextTracker) value, if
105
+ any. Its type will depend on the context tracker's type
106
+ parameter, or it will be `null` if there is no context
107
+ tracker.
108
+ */
109
+ get context() { return this.curContext ? this.curContext.context : null; }
110
+ // Push a state onto the stack, tracking its start position as well
111
+ // as the buffer base at that point.
112
+ /**
113
+ @internal
114
+ */
115
+ pushState(state, start) {
116
+ this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
117
+ this.state = state;
118
+ }
119
+ // Apply a reduce action
120
+ /**
121
+ @internal
122
+ */
123
+ reduce(action) {
124
+ var _a;
125
+ let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;
126
+ let { parser } = this.p;
127
+ let lookaheadRecord = this.reducePos < this.pos - 25 /* Lookahead.Margin */ && this.setLookAhead(this.pos);
128
+ let dPrec = parser.dynamicPrecedence(type);
129
+ if (dPrec)
130
+ this.score += dPrec;
131
+ if (depth == 0) {
132
+ if (type < parser.minRepeatTerm && this.reducePos < this.pos)
133
+ this.reducePos = this.pos;
134
+ this.pushState(parser.getGoto(this.state, type, true), this.reducePos);
135
+ // Zero-depth reductions are a special case—they add stuff to
136
+ // the stack without popping anything off.
137
+ if (type < parser.minRepeatTerm)
138
+ this.storeNode(type, this.reducePos, this.reducePos, lookaheadRecord ? 8 : 4, true);
139
+ this.reduceContext(type, this.reducePos);
140
+ return;
141
+ }
142
+ // Find the base index into `this.stack`, content after which will
143
+ // be dropped. Note that with `StayFlag` reductions we need to
144
+ // consume two extra frames (the dummy parent node for the skipped
145
+ // expression and the state that we'll be staying in, which should
146
+ // be moved to `this.state`).
147
+ let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);
148
+ let start = base ? this.stack[base - 2] : this.p.ranges[0].from;
149
+ if (type < parser.minRepeatTerm && start == this.reducePos && this.reducePos < this.pos)
150
+ this.reducePos = this.pos;
151
+ let size = this.reducePos - start;
152
+ // This is a kludge to try and detect overly deep left-associative
153
+ // trees, which will not increase the parse stack depth and thus
154
+ // won't be caught by the regular stack-depth limit check.
155
+ if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
156
+ if (start == this.p.lastBigReductionStart) {
157
+ this.p.bigReductionCount++;
158
+ this.p.lastBigReductionSize = size;
159
+ }
160
+ else if (this.p.lastBigReductionSize < size) {
161
+ this.p.bigReductionCount = 1;
162
+ this.p.lastBigReductionStart = start;
163
+ this.p.lastBigReductionSize = size;
164
+ }
165
+ }
166
+ let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
167
+ // Store normal terms or `R -> R R` repeat reductions
168
+ if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {
169
+ let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;
170
+ this.storeNode(type, start, pos, count + 4, true);
171
+ }
172
+ if (action & 262144 /* Action.StayFlag */) {
173
+ this.state = this.stack[base];
174
+ }
175
+ else {
176
+ let baseStateID = this.stack[base - 3];
177
+ this.state = parser.getGoto(baseStateID, type, true);
178
+ }
179
+ while (this.stack.length > base)
180
+ this.stack.pop();
181
+ this.reduceContext(type, start);
182
+ }
183
+ // Shift a value into the buffer
184
+ /**
185
+ @internal
186
+ */
187
+ storeNode(term, start, end, size = 4, mustSink = false) {
188
+ if (term == 0 /* Term.Err */ &&
189
+ (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
190
+ // Try to omit/merge adjacent error nodes
191
+ let top = this.buffer.length;
192
+ if (top > 0 && this.buffer[top - 4] == 0 /* Term.Err */ && this.buffer[top - 1] > -1) {
193
+ if (start == end)
194
+ return;
195
+ if (this.buffer[top - 2] >= start) {
196
+ this.buffer[top - 2] = end;
197
+ return;
198
+ }
199
+ }
200
+ }
201
+ if (!mustSink || this.pos == end) { // Simple case, just append
202
+ this.buffer.push(term, start, end, size);
203
+ }
204
+ else { // There may be skipped nodes that have to be moved forward
205
+ let index = this.buffer.length;
206
+ if (index > 0 && (this.buffer[index - 4] != 0 /* Term.Err */ || this.buffer[index - 1] < 0)) {
207
+ let mustMove = false;
208
+ for (let scan = index; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
209
+ if (this.buffer[scan - 1] >= 0) {
210
+ mustMove = true;
211
+ break;
212
+ }
213
+ }
214
+ if (mustMove)
215
+ while (index > 0 && this.buffer[index - 2] > end) {
216
+ // Move this record forward
217
+ this.buffer[index] = this.buffer[index - 4];
218
+ this.buffer[index + 1] = this.buffer[index - 3];
219
+ this.buffer[index + 2] = this.buffer[index - 2];
220
+ this.buffer[index + 3] = this.buffer[index - 1];
221
+ index -= 4;
222
+ if (size > 4)
223
+ size -= 4;
224
+ }
225
+ }
226
+ this.buffer[index] = term;
227
+ this.buffer[index + 1] = start;
228
+ this.buffer[index + 2] = end;
229
+ this.buffer[index + 3] = size;
230
+ }
231
+ }
232
+ // Apply a shift action
233
+ /**
234
+ @internal
235
+ */
236
+ shift(action, type, start, end) {
237
+ if (action & 131072 /* Action.GotoFlag */) {
238
+ this.pushState(action & 65535 /* Action.ValueMask */, this.pos);
239
+ }
240
+ else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift
241
+ let nextState = action, { parser } = this.p;
242
+ this.pos = end;
243
+ let skipped = parser.stateFlag(nextState, 1 /* StateFlag.Skipped */);
244
+ // Skipped or zero-length non-tree tokens don't move reducePos
245
+ if (!skipped && (end > start || type <= parser.maxNode))
246
+ this.reducePos = end;
247
+ this.pushState(nextState, skipped ? start : Math.min(start, this.reducePos));
248
+ this.shiftContext(type, start);
249
+ if (type <= parser.maxNode)
250
+ this.buffer.push(type, start, end, 4);
251
+ }
252
+ else { // Shift-and-stay, which means this is a skipped token
253
+ this.pos = end;
254
+ this.shiftContext(type, start);
255
+ if (type <= this.p.parser.maxNode)
256
+ this.buffer.push(type, start, end, 4);
257
+ }
258
+ }
259
+ // Apply an action
260
+ /**
261
+ @internal
262
+ */
263
+ apply(action, next, nextStart, nextEnd) {
264
+ if (action & 65536 /* Action.ReduceFlag */)
265
+ this.reduce(action);
266
+ else
267
+ this.shift(action, next, nextStart, nextEnd);
268
+ }
269
+ // Add a prebuilt (reused) node into the buffer.
270
+ /**
271
+ @internal
272
+ */
273
+ useNode(value, next) {
274
+ let index = this.p.reused.length - 1;
275
+ if (index < 0 || this.p.reused[index] != value) {
276
+ this.p.reused.push(value);
277
+ index++;
278
+ }
279
+ let start = this.pos;
280
+ this.reducePos = this.pos = start + value.length;
281
+ this.pushState(next, start);
282
+ this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);
283
+ if (this.curContext)
284
+ this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
285
+ }
286
+ // Split the stack. Due to the buffer sharing and the fact
287
+ // that `this.stack` tends to stay quite shallow, this isn't very
288
+ // expensive.
289
+ /**
290
+ @internal
291
+ */
292
+ split() {
293
+ let parent = this;
294
+ let off = parent.buffer.length;
295
+ // Leave off top error node, if there, because that might be
296
+ // merged with other nodes.
297
+ if (off && parent.buffer[off - 4] == 0 /* Term.Err */)
298
+ off -= 4;
299
+ // Because the top of the buffer (after this.pos) may be mutated
300
+ // to reorder reductions and skipped tokens, and shared buffers
301
+ // should be immutable, this copies any outstanding skipped tokens
302
+ // to the new buffer, and puts the base pointer before them.
303
+ while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
304
+ off -= 4;
305
+ let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
306
+ // Make sure parent points to an actual parent with content, if there is such a parent.
307
+ while (parent && base == parent.bufferBase)
308
+ parent = parent.parent;
309
+ return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
310
+ }
311
+ // Try to recover from an error by 'deleting' (ignoring) one token.
312
+ /**
313
+ @internal
314
+ */
315
+ recoverByDelete(next, nextEnd) {
316
+ let isNode = next <= this.p.parser.maxNode;
317
+ if (isNode)
318
+ this.storeNode(next, this.pos, nextEnd, 4);
319
+ this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);
320
+ this.pos = this.reducePos = nextEnd;
321
+ this.score -= 190 /* Recover.Delete */;
322
+ }
323
+ /**
324
+ Check if the given term would be able to be shifted (optionally
325
+ after some reductions) on this stack. This can be useful for
326
+ external tokenizers that want to make sure they only provide a
327
+ given token when it applies.
328
+ */
329
+ canShift(term) {
330
+ for (let sim = new SimulatedStack(this);;) {
331
+ let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);
332
+ if (action == 0)
333
+ return false;
334
+ if ((action & 65536 /* Action.ReduceFlag */) == 0)
335
+ return true;
336
+ sim.reduce(action);
337
+ }
338
+ }
339
+ // Apply up to Recover.MaxNext recovery actions that conceptually
340
+ // inserts some missing token or rule.
341
+ /**
342
+ @internal
343
+ */
344
+ recoverByInsert(next) {
345
+ if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)
346
+ return [];
347
+ let nextStates = this.p.parser.nextStates(this.state);
348
+ if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {
349
+ let best = [];
350
+ for (let i = 0, s; i < nextStates.length; i += 2) {
351
+ if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
352
+ best.push(nextStates[i], s);
353
+ }
354
+ if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)
355
+ for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {
356
+ let s = nextStates[i + 1];
357
+ if (!best.some((v, i) => (i & 1) && v == s))
358
+ best.push(nextStates[i], s);
359
+ }
360
+ nextStates = best;
361
+ }
362
+ let result = [];
363
+ for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {
364
+ let s = nextStates[i + 1];
365
+ if (s == this.state)
366
+ continue;
367
+ let stack = this.split();
368
+ stack.pushState(s, this.pos);
369
+ stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);
370
+ stack.shiftContext(nextStates[i], this.pos);
371
+ stack.reducePos = this.pos;
372
+ stack.score -= 200 /* Recover.Insert */;
373
+ result.push(stack);
374
+ }
375
+ return result;
376
+ }
377
+ // Force a reduce, if possible. Return false if that can't
378
+ // be done.
379
+ /**
380
+ @internal
381
+ */
382
+ forceReduce() {
383
+ let { parser } = this.p;
384
+ let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);
385
+ if ((reduce & 65536 /* Action.ReduceFlag */) == 0)
386
+ return false;
387
+ if (!parser.validAction(this.state, reduce)) {
388
+ let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;
389
+ let target = this.stack.length - depth * 3;
390
+ if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {
391
+ let backup = this.findForcedReduction();
392
+ if (backup == null)
393
+ return false;
394
+ reduce = backup;
395
+ }
396
+ this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
397
+ this.score -= 100 /* Recover.Reduce */;
398
+ }
399
+ this.reducePos = this.pos;
400
+ this.reduce(reduce);
401
+ return true;
402
+ }
403
+ /**
404
+ Try to scan through the automaton to find some kind of reduction
405
+ that can be applied. Used when the regular ForcedReduce field
406
+ isn't a valid action. @internal
407
+ */
408
+ findForcedReduction() {
409
+ let { parser } = this.p, seen = [];
410
+ let explore = (state, depth) => {
411
+ if (seen.includes(state))
412
+ return;
413
+ seen.push(state);
414
+ return parser.allActions(state, (action) => {
415
+ if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;
416
+ else if (action & 65536 /* Action.ReduceFlag */) {
417
+ let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;
418
+ if (rDepth > 1) {
419
+ let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;
420
+ if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)
421
+ return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;
422
+ }
423
+ }
424
+ else {
425
+ let found = explore(action, depth + 1);
426
+ if (found != null)
427
+ return found;
428
+ }
429
+ });
430
+ };
431
+ return explore(this.state, 0);
432
+ }
433
+ /**
434
+ @internal
435
+ */
436
+ forceAll() {
437
+ while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {
438
+ if (!this.forceReduce()) {
439
+ this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
440
+ break;
441
+ }
442
+ }
443
+ return this;
444
+ }
445
+ /**
446
+ Check whether this state has no further actions (assumed to be a direct descendant of the
447
+ top state, since any other states must be able to continue
448
+ somehow). @internal
449
+ */
450
+ get deadEnd() {
451
+ if (this.stack.length != 3)
452
+ return false;
453
+ let { parser } = this.p;
454
+ return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&
455
+ !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);
456
+ }
457
+ /**
458
+ Restart the stack (put it back in its start state). Only safe
459
+ when this.stack.length == 3 (state is directly below the top
460
+ state). @internal
461
+ */
462
+ restart() {
463
+ this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
464
+ this.state = this.stack[0];
465
+ this.stack.length = 0;
466
+ }
467
+ /**
468
+ @internal
469
+ */
470
+ sameState(other) {
471
+ if (this.state != other.state || this.stack.length != other.stack.length)
472
+ return false;
473
+ for (let i = 0; i < this.stack.length; i += 3)
474
+ if (this.stack[i] != other.stack[i])
475
+ return false;
476
+ return true;
477
+ }
478
+ /**
479
+ Get the parser used by this stack.
480
+ */
481
+ get parser() { return this.p.parser; }
482
+ /**
483
+ Test whether a given dialect (by numeric ID, as exported from
484
+ the terms file) is enabled.
485
+ */
486
+ dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }
487
+ shiftContext(term, start) {
488
+ if (this.curContext)
489
+ this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
490
+ }
491
+ reduceContext(term, start) {
492
+ if (this.curContext)
493
+ this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
494
+ }
495
+ /**
496
+ @internal
497
+ */
498
+ emitContext() {
499
+ let last = this.buffer.length - 1;
500
+ if (last < 0 || this.buffer[last] != -3)
501
+ this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
502
+ }
503
+ /**
504
+ @internal
505
+ */
506
+ emitLookAhead() {
507
+ let last = this.buffer.length - 1;
508
+ if (last < 0 || this.buffer[last] != -4)
509
+ this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
510
+ }
511
+ updateContext(context) {
512
+ if (context != this.curContext.context) {
513
+ let newCx = new StackContext(this.curContext.tracker, context);
514
+ if (newCx.hash != this.curContext.hash)
515
+ this.emitContext();
516
+ this.curContext = newCx;
517
+ }
518
+ }
519
+ /**
520
+ @internal
521
+ */
522
+ setLookAhead(lookAhead) {
523
+ if (lookAhead <= this.lookAhead)
524
+ return false;
525
+ this.emitLookAhead();
526
+ this.lookAhead = lookAhead;
527
+ return true;
528
+ }
529
+ /**
530
+ @internal
531
+ */
532
+ close() {
533
+ if (this.curContext && this.curContext.tracker.strict)
534
+ this.emitContext();
535
+ if (this.lookAhead > 0)
536
+ this.emitLookAhead();
537
+ }
538
+ }
539
+ class StackContext {
540
+ constructor(tracker, context) {
541
+ this.tracker = tracker;
542
+ this.context = context;
543
+ this.hash = tracker.strict ? tracker.hash(context) : 0;
544
+ }
545
+ }
546
+ // Used to cheaply run some reductions to scan ahead without mutating
547
+ // an entire stack
548
+ class SimulatedStack {
549
+ constructor(start) {
550
+ this.start = start;
551
+ this.state = start.state;
552
+ this.stack = start.stack;
553
+ this.base = this.stack.length;
554
+ }
555
+ reduce(action) {
556
+ let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;
557
+ if (depth == 0) {
558
+ if (this.stack == this.start.stack)
559
+ this.stack = this.stack.slice();
560
+ this.stack.push(this.state, 0, 0);
561
+ this.base += 3;
562
+ }
563
+ else {
564
+ this.base -= (depth - 1) * 3;
565
+ }
566
+ let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
567
+ this.state = goto;
568
+ }
569
+ }
570
+ // This is given to `Tree.build` to build a buffer, and encapsulates
571
+ // the parent-stack-walking necessary to read the nodes.
572
+ class StackBufferCursor {
573
+ constructor(stack, pos, index) {
574
+ this.stack = stack;
575
+ this.pos = pos;
576
+ this.index = index;
577
+ this.buffer = stack.buffer;
578
+ if (this.index == 0)
579
+ this.maybeNext();
580
+ }
581
+ static create(stack, pos = stack.bufferBase + stack.buffer.length) {
582
+ return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
583
+ }
584
+ maybeNext() {
585
+ let next = this.stack.parent;
586
+ if (next != null) {
587
+ this.index = this.stack.bufferBase - next.bufferBase;
588
+ this.stack = next;
589
+ this.buffer = next.buffer;
590
+ }
591
+ }
592
+ get id() { return this.buffer[this.index - 4]; }
593
+ get start() { return this.buffer[this.index - 3]; }
594
+ get end() { return this.buffer[this.index - 2]; }
595
+ get size() { return this.buffer[this.index - 1]; }
596
+ next() {
597
+ this.index -= 4;
598
+ this.pos -= 4;
599
+ if (this.index == 0)
600
+ this.maybeNext();
601
+ }
602
+ fork() {
603
+ return new StackBufferCursor(this.stack, this.pos, this.index);
604
+ }
605
+ }
606
+
607
+ // See lezer-generator/src/encode.ts for comments about the encoding
608
+ // used here
609
+ function decodeArray(input, Type = Uint16Array) {
610
+ if (typeof input != "string")
611
+ return input;
612
+ let array = null;
613
+ for (let pos = 0, out = 0; pos < input.length;) {
614
+ let value = 0;
615
+ for (;;) {
616
+ let next = input.charCodeAt(pos++), stop = false;
617
+ if (next == 126 /* Encode.BigValCode */) {
618
+ value = 65535 /* Encode.BigVal */;
619
+ break;
620
+ }
621
+ if (next >= 92 /* Encode.Gap2 */)
622
+ next--;
623
+ if (next >= 34 /* Encode.Gap1 */)
624
+ next--;
625
+ let digit = next - 32 /* Encode.Start */;
626
+ if (digit >= 46 /* Encode.Base */) {
627
+ digit -= 46 /* Encode.Base */;
628
+ stop = true;
629
+ }
630
+ value += digit;
631
+ if (stop)
632
+ break;
633
+ value *= 46 /* Encode.Base */;
634
+ }
635
+ if (array)
636
+ array[out++] = value;
637
+ else
638
+ array = new Type(value);
639
+ }
640
+ return array;
641
+ }
642
+
643
+ class CachedToken {
644
+ constructor() {
645
+ this.start = -1;
646
+ this.value = -1;
647
+ this.end = -1;
648
+ this.extended = -1;
649
+ this.lookAhead = 0;
650
+ this.mask = 0;
651
+ this.context = 0;
652
+ }
653
+ }
654
+ const nullToken = new CachedToken;
655
+ /**
656
+ [Tokenizers](#lr.ExternalTokenizer) interact with the input
657
+ through this interface. It presents the input as a stream of
658
+ characters, tracking lookahead and hiding the complexity of
659
+ [ranges](#common.Parser.parse^ranges) from tokenizer code.
660
+ */
661
+ class InputStream {
662
+ /**
663
+ @internal
664
+ */
665
+ constructor(
666
+ /**
667
+ @internal
668
+ */
669
+ input,
670
+ /**
671
+ @internal
672
+ */
673
+ ranges) {
674
+ this.input = input;
675
+ this.ranges = ranges;
676
+ /**
677
+ @internal
678
+ */
679
+ this.chunk = "";
680
+ /**
681
+ @internal
682
+ */
683
+ this.chunkOff = 0;
684
+ /**
685
+ Backup chunk
686
+ */
687
+ this.chunk2 = "";
688
+ this.chunk2Pos = 0;
689
+ /**
690
+ The character code of the next code unit in the input, or -1
691
+ when the stream is at the end of the input.
692
+ */
693
+ this.next = -1;
694
+ /**
695
+ @internal
696
+ */
697
+ this.token = nullToken;
698
+ this.rangeIndex = 0;
699
+ this.pos = this.chunkPos = ranges[0].from;
700
+ this.range = ranges[0];
701
+ this.end = ranges[ranges.length - 1].to;
702
+ this.readNext();
703
+ }
704
+ /**
705
+ @internal
706
+ */
707
+ resolveOffset(offset, assoc) {
708
+ let range = this.range, index = this.rangeIndex;
709
+ let pos = this.pos + offset;
710
+ while (pos < range.from) {
711
+ if (!index)
712
+ return null;
713
+ let next = this.ranges[--index];
714
+ pos -= range.from - next.to;
715
+ range = next;
716
+ }
717
+ while (assoc < 0 ? pos > range.to : pos >= range.to) {
718
+ if (index == this.ranges.length - 1)
719
+ return null;
720
+ let next = this.ranges[++index];
721
+ pos += next.from - range.to;
722
+ range = next;
723
+ }
724
+ return pos;
725
+ }
726
+ /**
727
+ @internal
728
+ */
729
+ clipPos(pos) {
730
+ if (pos >= this.range.from && pos < this.range.to)
731
+ return pos;
732
+ for (let range of this.ranges)
733
+ if (range.to > pos)
734
+ return Math.max(pos, range.from);
735
+ return this.end;
736
+ }
737
+ /**
738
+ Look at a code unit near the stream position. `.peek(0)` equals
739
+ `.next`, `.peek(-1)` gives you the previous character, and so
740
+ on.
741
+
742
+ Note that looking around during tokenizing creates dependencies
743
+ on potentially far-away content, which may reduce the
744
+ effectiveness incremental parsing—when looking forward—or even
745
+ cause invalid reparses when looking backward more than 25 code
746
+ units, since the library does not track lookbehind.
747
+ */
748
+ peek(offset) {
749
+ let idx = this.chunkOff + offset, pos, result;
750
+ if (idx >= 0 && idx < this.chunk.length) {
751
+ pos = this.pos + offset;
752
+ result = this.chunk.charCodeAt(idx);
753
+ }
754
+ else {
755
+ let resolved = this.resolveOffset(offset, 1);
756
+ if (resolved == null)
757
+ return -1;
758
+ pos = resolved;
759
+ if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
760
+ result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
761
+ }
762
+ else {
763
+ let i = this.rangeIndex, range = this.range;
764
+ while (range.to <= pos)
765
+ range = this.ranges[++i];
766
+ this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
767
+ if (pos + this.chunk2.length > range.to)
768
+ this.chunk2 = this.chunk2.slice(0, range.to - pos);
769
+ result = this.chunk2.charCodeAt(0);
770
+ }
771
+ }
772
+ if (pos >= this.token.lookAhead)
773
+ this.token.lookAhead = pos + 1;
774
+ return result;
775
+ }
776
+ /**
777
+ Accept a token. By default, the end of the token is set to the
778
+ current stream position, but you can pass an offset (relative to
779
+ the stream position) to change that.
780
+ */
781
+ acceptToken(token, endOffset = 0) {
782
+ let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
783
+ if (end == null || end < this.token.start)
784
+ throw new RangeError("Token end out of bounds");
785
+ this.token.value = token;
786
+ this.token.end = end;
787
+ }
788
+ /**
789
+ Accept a token ending at a specific given position.
790
+ */
791
+ acceptTokenTo(token, endPos) {
792
+ this.token.value = token;
793
+ this.token.end = endPos;
794
+ }
795
+ getChunk() {
796
+ if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
797
+ let { chunk, chunkPos } = this;
798
+ this.chunk = this.chunk2;
799
+ this.chunkPos = this.chunk2Pos;
800
+ this.chunk2 = chunk;
801
+ this.chunk2Pos = chunkPos;
802
+ this.chunkOff = this.pos - this.chunkPos;
803
+ }
804
+ else {
805
+ this.chunk2 = this.chunk;
806
+ this.chunk2Pos = this.chunkPos;
807
+ let nextChunk = this.input.chunk(this.pos);
808
+ let end = this.pos + nextChunk.length;
809
+ this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
810
+ this.chunkPos = this.pos;
811
+ this.chunkOff = 0;
812
+ }
813
+ }
814
+ readNext() {
815
+ if (this.chunkOff >= this.chunk.length) {
816
+ this.getChunk();
817
+ if (this.chunkOff == this.chunk.length)
818
+ return this.next = -1;
819
+ }
820
+ return this.next = this.chunk.charCodeAt(this.chunkOff);
821
+ }
822
+ /**
823
+ Move the stream forward N (defaults to 1) code units. Returns
824
+ the new value of [`next`](#lr.InputStream.next).
825
+ */
826
+ advance(n = 1) {
827
+ this.chunkOff += n;
828
+ while (this.pos + n >= this.range.to) {
829
+ if (this.rangeIndex == this.ranges.length - 1)
830
+ return this.setDone();
831
+ n -= this.range.to - this.pos;
832
+ this.range = this.ranges[++this.rangeIndex];
833
+ this.pos = this.range.from;
834
+ }
835
+ this.pos += n;
836
+ if (this.pos >= this.token.lookAhead)
837
+ this.token.lookAhead = this.pos + 1;
838
+ return this.readNext();
839
+ }
840
+ setDone() {
841
+ this.pos = this.chunkPos = this.end;
842
+ this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
843
+ this.chunk = "";
844
+ return this.next = -1;
845
+ }
846
+ /**
847
+ @internal
848
+ */
849
+ reset(pos, token) {
850
+ if (token) {
851
+ this.token = token;
852
+ token.start = pos;
853
+ token.lookAhead = pos + 1;
854
+ token.value = token.extended = -1;
855
+ }
856
+ else {
857
+ this.token = nullToken;
858
+ }
859
+ if (this.pos != pos) {
860
+ this.pos = pos;
861
+ if (pos == this.end) {
862
+ this.setDone();
863
+ return this;
864
+ }
865
+ while (pos < this.range.from)
866
+ this.range = this.ranges[--this.rangeIndex];
867
+ while (pos >= this.range.to)
868
+ this.range = this.ranges[++this.rangeIndex];
869
+ if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
870
+ this.chunkOff = pos - this.chunkPos;
871
+ }
872
+ else {
873
+ this.chunk = "";
874
+ this.chunkOff = 0;
875
+ }
876
+ this.readNext();
877
+ }
878
+ return this;
879
+ }
880
+ /**
881
+ @internal
882
+ */
883
+ read(from, to) {
884
+ if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
885
+ return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
886
+ if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
887
+ return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
888
+ if (from >= this.range.from && to <= this.range.to)
889
+ return this.input.read(from, to);
890
+ let result = "";
891
+ for (let r of this.ranges) {
892
+ if (r.from >= to)
893
+ break;
894
+ if (r.to > from)
895
+ result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
896
+ }
897
+ return result;
898
+ }
899
+ }
900
+ /**
901
+ @internal
902
+ */
903
+ class TokenGroup {
904
+ constructor(data, id) {
905
+ this.data = data;
906
+ this.id = id;
907
+ }
908
+ token(input, stack) {
909
+ let { parser } = stack.p;
910
+ readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);
911
+ }
912
+ }
913
+ TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
914
+ /**
915
+ @hide
916
+ */
917
+ class LocalTokenGroup {
918
+ constructor(data, precTable, elseToken) {
919
+ this.precTable = precTable;
920
+ this.elseToken = elseToken;
921
+ this.data = typeof data == "string" ? decodeArray(data) : data;
922
+ }
923
+ token(input, stack) {
924
+ let start = input.pos, skipped = 0;
925
+ for (;;) {
926
+ let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
927
+ readToken(this.data, input, stack, 0, this.data, this.precTable);
928
+ if (input.token.value > -1)
929
+ break;
930
+ if (this.elseToken == null)
931
+ return;
932
+ if (!atEof)
933
+ skipped++;
934
+ if (nextPos == null)
935
+ break;
936
+ input.reset(nextPos, input.token);
937
+ }
938
+ if (skipped) {
939
+ input.reset(start, input.token);
940
+ input.acceptToken(this.elseToken, skipped);
941
+ }
942
+ }
943
+ }
944
+ LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
945
+ /**
946
+ `@external tokens` declarations in the grammar should resolve to
947
+ an instance of this class.
948
+ */
949
+ class ExternalTokenizer {
950
+ /**
951
+ Create a tokenizer. The first argument is the function that,
952
+ given an input stream, scans for the types of tokens it
953
+ recognizes at the stream's position, and calls
954
+ [`acceptToken`](#lr.InputStream.acceptToken) when it finds
955
+ one.
956
+ */
957
+ constructor(
958
+ /**
959
+ @internal
960
+ */
961
+ token, options = {}) {
962
+ this.token = token;
963
+ this.contextual = !!options.contextual;
964
+ this.fallback = !!options.fallback;
965
+ this.extend = !!options.extend;
966
+ }
967
+ }
968
+ // Tokenizer data is stored a big uint16 array containing, for each
969
+ // state:
970
+ //
971
+ // - A group bitmask, indicating what token groups are reachable from
972
+ // this state, so that paths that can only lead to tokens not in
973
+ // any of the current groups can be cut off early.
974
+ //
975
+ // - The position of the end of the state's sequence of accepting
976
+ // tokens
977
+ //
978
+ // - The number of outgoing edges for the state
979
+ //
980
+ // - The accepting tokens, as (token id, group mask) pairs
981
+ //
982
+ // - The outgoing edges, as (start character, end character, state
983
+ // index) triples, with end character being exclusive
984
+ //
985
+ // This function interprets that data, running through a stream as
986
+ // long as new states with the a matching group mask can be reached,
987
+ // and updating `input.token` when it matches a token.
988
+ function readToken(data, input, stack, group, precTable, precOffset) {
989
+ let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
990
+ scan: for (;;) {
991
+ if ((groupMask & data[state]) == 0)
992
+ break;
993
+ let accEnd = data[state + 1];
994
+ // Check whether this state can lead to a token in the current group
995
+ // Accept tokens in this state, possibly overwriting
996
+ // lower-precedence / shorter tokens
997
+ for (let i = state + 3; i < accEnd; i += 2)
998
+ if ((data[i + 1] & groupMask) > 0) {
999
+ let term = data[i];
1000
+ if (dialect.allows(term) &&
1001
+ (input.token.value == -1 || input.token.value == term ||
1002
+ overrides(term, input.token.value, precTable, precOffset))) {
1003
+ input.acceptToken(term);
1004
+ break;
1005
+ }
1006
+ }
1007
+ let next = input.next, low = 0, high = data[state + 2];
1008
+ // Special case for EOF
1009
+ if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {
1010
+ state = data[accEnd + high * 3 - 1];
1011
+ continue scan;
1012
+ }
1013
+ // Do a binary search on the state's edges
1014
+ for (; low < high;) {
1015
+ let mid = (low + high) >> 1;
1016
+ let index = accEnd + mid + (mid << 1);
1017
+ let from = data[index], to = data[index + 1] || 0x10000;
1018
+ if (next < from)
1019
+ high = mid;
1020
+ else if (next >= to)
1021
+ low = mid + 1;
1022
+ else {
1023
+ state = data[index + 2];
1024
+ input.advance();
1025
+ continue scan;
1026
+ }
1027
+ }
1028
+ break;
1029
+ }
1030
+ }
1031
+ function findOffset(data, start, term) {
1032
+ for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)
1033
+ if (next == term)
1034
+ return i - start;
1035
+ return -1;
1036
+ }
1037
+ function overrides(token, prev, tableData, tableOffset) {
1038
+ let iPrev = findOffset(tableData, tableOffset, prev);
1039
+ return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
1040
+ }
1041
+
1042
+ // Environment variable used to control console output
1043
+ const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
1044
+ let stackIDs = null;
1045
+ function cutAt(tree, pos, side) {
1046
+ let cursor = tree.cursor(IterMode.IncludeAnonymous);
1047
+ cursor.moveTo(pos);
1048
+ for (;;) {
1049
+ if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
1050
+ for (;;) {
1051
+ if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
1052
+ return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Lookahead.Margin */))
1053
+ : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Lookahead.Margin */));
1054
+ if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
1055
+ break;
1056
+ if (!cursor.parent())
1057
+ return side < 0 ? 0 : tree.length;
1058
+ }
1059
+ }
1060
+ }
1061
+ class FragmentCursor {
1062
+ constructor(fragments, nodeSet) {
1063
+ this.fragments = fragments;
1064
+ this.nodeSet = nodeSet;
1065
+ this.i = 0;
1066
+ this.fragment = null;
1067
+ this.safeFrom = -1;
1068
+ this.safeTo = -1;
1069
+ this.trees = [];
1070
+ this.start = [];
1071
+ this.index = [];
1072
+ this.nextFragment();
1073
+ }
1074
+ nextFragment() {
1075
+ let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
1076
+ if (fr) {
1077
+ this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
1078
+ this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
1079
+ while (this.trees.length) {
1080
+ this.trees.pop();
1081
+ this.start.pop();
1082
+ this.index.pop();
1083
+ }
1084
+ this.trees.push(fr.tree);
1085
+ this.start.push(-fr.offset);
1086
+ this.index.push(0);
1087
+ this.nextStart = this.safeFrom;
1088
+ }
1089
+ else {
1090
+ this.nextStart = 1e9;
1091
+ }
1092
+ }
1093
+ // `pos` must be >= any previously given `pos` for this cursor
1094
+ nodeAt(pos) {
1095
+ if (pos < this.nextStart)
1096
+ return null;
1097
+ while (this.fragment && this.safeTo <= pos)
1098
+ this.nextFragment();
1099
+ if (!this.fragment)
1100
+ return null;
1101
+ for (;;) {
1102
+ let last = this.trees.length - 1;
1103
+ if (last < 0) { // End of tree
1104
+ this.nextFragment();
1105
+ return null;
1106
+ }
1107
+ let top = this.trees[last], index = this.index[last];
1108
+ if (index == top.children.length) {
1109
+ this.trees.pop();
1110
+ this.start.pop();
1111
+ this.index.pop();
1112
+ continue;
1113
+ }
1114
+ let next = top.children[index];
1115
+ let start = this.start[last] + top.positions[index];
1116
+ if (start > pos) {
1117
+ this.nextStart = start;
1118
+ return null;
1119
+ }
1120
+ if (next instanceof Tree) {
1121
+ if (start == pos) {
1122
+ if (start < this.safeFrom)
1123
+ return null;
1124
+ let end = start + next.length;
1125
+ if (end <= this.safeTo) {
1126
+ let lookAhead = next.prop(NodeProp.lookAhead);
1127
+ if (!lookAhead || end + lookAhead < this.fragment.to)
1128
+ return next;
1129
+ }
1130
+ }
1131
+ this.index[last]++;
1132
+ if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node
1133
+ this.trees.push(next);
1134
+ this.start.push(start);
1135
+ this.index.push(0);
1136
+ }
1137
+ }
1138
+ else {
1139
+ this.index[last]++;
1140
+ this.nextStart = start + next.length;
1141
+ }
1142
+ }
1143
+ }
1144
+ }
1145
+ class TokenCache {
1146
+ constructor(parser, stream) {
1147
+ this.stream = stream;
1148
+ this.tokens = [];
1149
+ this.mainToken = null;
1150
+ this.actions = [];
1151
+ this.tokens = parser.tokenizers.map(_ => new CachedToken);
1152
+ }
1153
+ getActions(stack) {
1154
+ let actionIndex = 0;
1155
+ let main = null;
1156
+ let { parser } = stack.p, { tokenizers } = parser;
1157
+ let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);
1158
+ let context = stack.curContext ? stack.curContext.hash : 0;
1159
+ let lookAhead = 0;
1160
+ for (let i = 0; i < tokenizers.length; i++) {
1161
+ if (((1 << i) & mask) == 0)
1162
+ continue;
1163
+ let tokenizer = tokenizers[i], token = this.tokens[i];
1164
+ if (main && !tokenizer.fallback)
1165
+ continue;
1166
+ if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
1167
+ this.updateCachedToken(token, tokenizer, stack);
1168
+ token.mask = mask;
1169
+ token.context = context;
1170
+ }
1171
+ if (token.lookAhead > token.end + 25 /* Lookahead.Margin */)
1172
+ lookAhead = Math.max(token.lookAhead, lookAhead);
1173
+ if (token.value != 0 /* Term.Err */) {
1174
+ let startIndex = actionIndex;
1175
+ if (token.extended > -1)
1176
+ actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
1177
+ actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
1178
+ if (!tokenizer.extend) {
1179
+ main = token;
1180
+ if (actionIndex > startIndex)
1181
+ break;
1182
+ }
1183
+ }
1184
+ }
1185
+ while (this.actions.length > actionIndex)
1186
+ this.actions.pop();
1187
+ if (lookAhead)
1188
+ stack.setLookAhead(lookAhead);
1189
+ if (!main && stack.pos == this.stream.end) {
1190
+ main = new CachedToken;
1191
+ main.value = stack.p.parser.eofTerm;
1192
+ main.start = main.end = stack.pos;
1193
+ actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
1194
+ }
1195
+ this.mainToken = main;
1196
+ return this.actions;
1197
+ }
1198
+ getMainToken(stack) {
1199
+ if (this.mainToken)
1200
+ return this.mainToken;
1201
+ let main = new CachedToken, { pos, p } = stack;
1202
+ main.start = pos;
1203
+ main.end = Math.min(pos + 1, p.stream.end);
1204
+ main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;
1205
+ return main;
1206
+ }
1207
+ updateCachedToken(token, tokenizer, stack) {
1208
+ let start = this.stream.clipPos(stack.pos);
1209
+ tokenizer.token(this.stream.reset(start, token), stack);
1210
+ if (token.value > -1) {
1211
+ let { parser } = stack.p;
1212
+ for (let i = 0; i < parser.specialized.length; i++)
1213
+ if (parser.specialized[i] == token.value) {
1214
+ let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);
1215
+ if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
1216
+ if ((result & 1) == 0 /* Specialize.Specialize */)
1217
+ token.value = result >> 1;
1218
+ else
1219
+ token.extended = result >> 1;
1220
+ break;
1221
+ }
1222
+ }
1223
+ }
1224
+ else {
1225
+ token.value = 0 /* Term.Err */;
1226
+ token.end = this.stream.clipPos(start + 1);
1227
+ }
1228
+ }
1229
+ putAction(action, token, end, index) {
1230
+ // Don't add duplicate actions
1231
+ for (let i = 0; i < index; i += 3)
1232
+ if (this.actions[i] == action)
1233
+ return index;
1234
+ this.actions[index++] = action;
1235
+ this.actions[index++] = token;
1236
+ this.actions[index++] = end;
1237
+ return index;
1238
+ }
1239
+ addActions(stack, token, end, index) {
1240
+ let { state } = stack, { parser } = stack.p, { data } = parser;
1241
+ for (let set = 0; set < 2; set++) {
1242
+ for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {
1243
+ if (data[i] == 65535 /* Seq.End */) {
1244
+ if (data[i + 1] == 1 /* Seq.Next */) {
1245
+ i = pair(data, i + 2);
1246
+ }
1247
+ else {
1248
+ if (index == 0 && data[i + 1] == 2 /* Seq.Other */)
1249
+ index = this.putAction(pair(data, i + 2), token, end, index);
1250
+ break;
1251
+ }
1252
+ }
1253
+ if (data[i] == token)
1254
+ index = this.putAction(pair(data, i + 1), token, end, index);
1255
+ }
1256
+ }
1257
+ return index;
1258
+ }
1259
+ }
1260
+ class Parse {
1261
+ constructor(parser, input, fragments, ranges) {
1262
+ this.parser = parser;
1263
+ this.input = input;
1264
+ this.ranges = ranges;
1265
+ this.recovering = 0;
1266
+ this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
1267
+ this.minStackPos = 0;
1268
+ this.reused = [];
1269
+ this.stoppedAt = null;
1270
+ this.lastBigReductionStart = -1;
1271
+ this.lastBigReductionSize = 0;
1272
+ this.bigReductionCount = 0;
1273
+ this.stream = new InputStream(input, ranges);
1274
+ this.tokens = new TokenCache(parser, this.stream);
1275
+ this.topTerm = parser.top[1];
1276
+ let { from } = ranges[0];
1277
+ this.stacks = [Stack.start(this, parser.top[0], from)];
1278
+ this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4
1279
+ ? new FragmentCursor(fragments, parser.nodeSet) : null;
1280
+ }
1281
+ get parsedPos() {
1282
+ return this.minStackPos;
1283
+ }
1284
+ // Move the parser forward. This will process all parse stacks at
1285
+ // `this.pos` and try to advance them to a further position. If no
1286
+ // stack for such a position is found, it'll start error-recovery.
1287
+ //
1288
+ // When the parse is finished, this will return a syntax tree. When
1289
+ // not, it returns `null`.
1290
+ advance() {
1291
+ let stacks = this.stacks, pos = this.minStackPos;
1292
+ // This will hold stacks beyond `pos`.
1293
+ let newStacks = this.stacks = [];
1294
+ let stopped, stoppedTokens;
1295
+ // If a large amount of reductions happened with the same start
1296
+ // position, force the stack out of that production in order to
1297
+ // avoid creating a tree too deep to recurse through.
1298
+ // (This is an ugly kludge, because unfortunately there is no
1299
+ // straightforward, cheap way to check for this happening, due to
1300
+ // the history of reductions only being available in an
1301
+ // expensive-to-access format in the stack buffers.)
1302
+ if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {
1303
+ let [s] = stacks;
1304
+ while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }
1305
+ this.bigReductionCount = this.lastBigReductionSize = 0;
1306
+ }
1307
+ // Keep advancing any stacks at `pos` until they either move
1308
+ // forward or can't be advanced. Gather stacks that can't be
1309
+ // advanced further in `stopped`.
1310
+ for (let i = 0; i < stacks.length; i++) {
1311
+ let stack = stacks[i];
1312
+ for (;;) {
1313
+ this.tokens.mainToken = null;
1314
+ if (stack.pos > pos) {
1315
+ newStacks.push(stack);
1316
+ }
1317
+ else if (this.advanceStack(stack, newStacks, stacks)) {
1318
+ continue;
1319
+ }
1320
+ else {
1321
+ if (!stopped) {
1322
+ stopped = [];
1323
+ stoppedTokens = [];
1324
+ }
1325
+ stopped.push(stack);
1326
+ let tok = this.tokens.getMainToken(stack);
1327
+ stoppedTokens.push(tok.value, tok.end);
1328
+ }
1329
+ break;
1330
+ }
1331
+ }
1332
+ if (!newStacks.length) {
1333
+ let finished = stopped && findFinished(stopped);
1334
+ if (finished) {
1335
+ if (verbose)
1336
+ console.log("Finish with " + this.stackID(finished));
1337
+ return this.stackToTree(finished);
1338
+ }
1339
+ if (this.parser.strict) {
1340
+ if (verbose && stopped)
1341
+ console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
1342
+ throw new SyntaxError("No parse at " + pos);
1343
+ }
1344
+ if (!this.recovering)
1345
+ this.recovering = 5 /* Rec.Distance */;
1346
+ }
1347
+ if (this.recovering && stopped) {
1348
+ let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]
1349
+ : this.runRecovery(stopped, stoppedTokens, newStacks);
1350
+ if (finished) {
1351
+ if (verbose)
1352
+ console.log("Force-finish " + this.stackID(finished));
1353
+ return this.stackToTree(finished.forceAll());
1354
+ }
1355
+ }
1356
+ if (this.recovering) {
1357
+ let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;
1358
+ if (newStacks.length > maxRemaining) {
1359
+ newStacks.sort((a, b) => b.score - a.score);
1360
+ while (newStacks.length > maxRemaining)
1361
+ newStacks.pop();
1362
+ }
1363
+ if (newStacks.some(s => s.reducePos > pos))
1364
+ this.recovering--;
1365
+ }
1366
+ else if (newStacks.length > 1) {
1367
+ // Prune stacks that are in the same state, or that have been
1368
+ // running without splitting for a while, to avoid getting stuck
1369
+ // with multiple successful stacks running endlessly on.
1370
+ outer: for (let i = 0; i < newStacks.length - 1; i++) {
1371
+ let stack = newStacks[i];
1372
+ for (let j = i + 1; j < newStacks.length; j++) {
1373
+ let other = newStacks[j];
1374
+ if (stack.sameState(other) ||
1375
+ stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {
1376
+ if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {
1377
+ newStacks.splice(j--, 1);
1378
+ }
1379
+ else {
1380
+ newStacks.splice(i--, 1);
1381
+ continue outer;
1382
+ }
1383
+ }
1384
+ }
1385
+ }
1386
+ if (newStacks.length > 12 /* Rec.MaxStackCount */) {
1387
+ newStacks.sort((a, b) => b.score - a.score);
1388
+ newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);
1389
+ }
1390
+ }
1391
+ this.minStackPos = newStacks[0].pos;
1392
+ for (let i = 1; i < newStacks.length; i++)
1393
+ if (newStacks[i].pos < this.minStackPos)
1394
+ this.minStackPos = newStacks[i].pos;
1395
+ return null;
1396
+ }
1397
+ stopAt(pos) {
1398
+ if (this.stoppedAt != null && this.stoppedAt < pos)
1399
+ throw new RangeError("Can't move stoppedAt forward");
1400
+ this.stoppedAt = pos;
1401
+ }
1402
+ // Returns an updated version of the given stack, or null if the
1403
+ // stack can't advance normally. When `split` and `stacks` are
1404
+ // given, stacks split off by ambiguous operations will be pushed to
1405
+ // `split`, or added to `stacks` if they move `pos` forward.
1406
+ advanceStack(stack, stacks, split) {
1407
+ let start = stack.pos, { parser } = this;
1408
+ let base = verbose ? this.stackID(stack) + " -> " : "";
1409
+ if (this.stoppedAt != null && start > this.stoppedAt)
1410
+ return stack.forceReduce() ? stack : null;
1411
+ if (this.fragments) {
1412
+ let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
1413
+ for (let cached = this.fragments.nodeAt(start); cached;) {
1414
+ let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;
1415
+ if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
1416
+ stack.useNode(cached, match);
1417
+ if (verbose)
1418
+ console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);
1419
+ return true;
1420
+ }
1421
+ if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
1422
+ break;
1423
+ let inner = cached.children[0];
1424
+ if (inner instanceof Tree && cached.positions[0] == 0)
1425
+ cached = inner;
1426
+ else
1427
+ break;
1428
+ }
1429
+ }
1430
+ let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);
1431
+ if (defaultReduce > 0) {
1432
+ stack.reduce(defaultReduce);
1433
+ if (verbose)
1434
+ console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);
1435
+ return true;
1436
+ }
1437
+ if (stack.stack.length >= 8400 /* Rec.CutDepth */) {
1438
+ while (stack.stack.length > 6000 /* Rec.CutTo */ && stack.forceReduce()) { }
1439
+ }
1440
+ let actions = this.tokens.getActions(stack);
1441
+ for (let i = 0; i < actions.length;) {
1442
+ let action = actions[i++], term = actions[i++], end = actions[i++];
1443
+ let last = i == actions.length || !split;
1444
+ let localStack = last ? stack : stack.split();
1445
+ let main = this.tokens.mainToken;
1446
+ localStack.apply(action, term, main ? main.start : localStack.pos, end);
1447
+ if (verbose)
1448
+ console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? "shift"
1449
+ : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
1450
+ if (last)
1451
+ return true;
1452
+ else if (localStack.pos > start)
1453
+ stacks.push(localStack);
1454
+ else
1455
+ split.push(localStack);
1456
+ }
1457
+ return false;
1458
+ }
1459
+ // Advance a given stack forward as far as it will go. Returns the
1460
+ // (possibly updated) stack if it got stuck, or null if it moved
1461
+ // forward and was given to `pushStackDedup`.
1462
+ advanceFully(stack, newStacks) {
1463
+ let pos = stack.pos;
1464
+ for (;;) {
1465
+ if (!this.advanceStack(stack, null, null))
1466
+ return false;
1467
+ if (stack.pos > pos) {
1468
+ pushStackDedup(stack, newStacks);
1469
+ return true;
1470
+ }
1471
+ }
1472
+ }
1473
+ runRecovery(stacks, tokens, newStacks) {
1474
+ let finished = null, restarted = false;
1475
+ for (let i = 0; i < stacks.length; i++) {
1476
+ let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
1477
+ let base = verbose ? this.stackID(stack) + " -> " : "";
1478
+ if (stack.deadEnd) {
1479
+ if (restarted)
1480
+ continue;
1481
+ restarted = true;
1482
+ stack.restart();
1483
+ if (verbose)
1484
+ console.log(base + this.stackID(stack) + " (restarted)");
1485
+ let done = this.advanceFully(stack, newStacks);
1486
+ if (done)
1487
+ continue;
1488
+ }
1489
+ let force = stack.split(), forceBase = base;
1490
+ for (let j = 0; j < 10 /* Rec.ForceReduceLimit */ && force.forceReduce(); j++) {
1491
+ if (verbose)
1492
+ console.log(forceBase + this.stackID(force) + " (via force-reduce)");
1493
+ let done = this.advanceFully(force, newStacks);
1494
+ if (done)
1495
+ break;
1496
+ if (verbose)
1497
+ forceBase = this.stackID(force) + " -> ";
1498
+ }
1499
+ for (let insert of stack.recoverByInsert(token)) {
1500
+ if (verbose)
1501
+ console.log(base + this.stackID(insert) + " (via recover-insert)");
1502
+ this.advanceFully(insert, newStacks);
1503
+ }
1504
+ if (this.stream.end > stack.pos) {
1505
+ if (tokenEnd == stack.pos) {
1506
+ tokenEnd++;
1507
+ token = 0 /* Term.Err */;
1508
+ }
1509
+ stack.recoverByDelete(token, tokenEnd);
1510
+ if (verbose)
1511
+ console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
1512
+ pushStackDedup(stack, newStacks);
1513
+ }
1514
+ else if (!finished || finished.score < force.score) {
1515
+ finished = force;
1516
+ }
1517
+ }
1518
+ return finished;
1519
+ }
1520
+ // Convert the stack's buffer to a syntax tree.
1521
+ stackToTree(stack) {
1522
+ stack.close();
1523
+ return Tree.build({ buffer: StackBufferCursor.create(stack),
1524
+ nodeSet: this.parser.nodeSet,
1525
+ topID: this.topTerm,
1526
+ maxBufferLength: this.parser.bufferLength,
1527
+ reused: this.reused,
1528
+ start: this.ranges[0].from,
1529
+ length: stack.pos - this.ranges[0].from,
1530
+ minRepeatType: this.parser.minRepeatTerm });
1531
+ }
1532
+ stackID(stack) {
1533
+ let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);
1534
+ if (!id)
1535
+ stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
1536
+ return id + stack;
1537
+ }
1538
+ }
1539
+ function pushStackDedup(stack, newStacks) {
1540
+ for (let i = 0; i < newStacks.length; i++) {
1541
+ let other = newStacks[i];
1542
+ if (other.pos == stack.pos && other.sameState(stack)) {
1543
+ if (newStacks[i].score < stack.score)
1544
+ newStacks[i] = stack;
1545
+ return;
1546
+ }
1547
+ }
1548
+ newStacks.push(stack);
1549
+ }
1550
+ class Dialect {
1551
+ constructor(source, flags, disabled) {
1552
+ this.source = source;
1553
+ this.flags = flags;
1554
+ this.disabled = disabled;
1555
+ }
1556
+ allows(term) { return !this.disabled || this.disabled[term] == 0; }
1557
+ }
1558
+ const id = x => x;
1559
+ /**
1560
+ Context trackers are used to track stateful context (such as
1561
+ indentation in the Python grammar, or parent elements in the XML
1562
+ grammar) needed by external tokenizers. You declare them in a
1563
+ grammar file as `@context exportName from "module"`.
1564
+
1565
+ Context values should be immutable, and can be updated (replaced)
1566
+ on shift or reduce actions.
1567
+
1568
+ The export used in a `@context` declaration should be of this
1569
+ type.
1570
+ */
1571
+ class ContextTracker {
1572
+ /**
1573
+ Define a context tracker.
1574
+ */
1575
+ constructor(spec) {
1576
+ this.start = spec.start;
1577
+ this.shift = spec.shift || id;
1578
+ this.reduce = spec.reduce || id;
1579
+ this.reuse = spec.reuse || id;
1580
+ this.hash = spec.hash || (() => 0);
1581
+ this.strict = spec.strict !== false;
1582
+ }
1583
+ }
1584
+ /**
1585
+ Holds the parse tables for a given grammar, as generated by
1586
+ `lezer-generator`, and provides [methods](#common.Parser) to parse
1587
+ content with.
1588
+ */
1589
+ class LRParser extends Parser {
1590
+ /**
1591
+ @internal
1592
+ */
1593
+ constructor(spec) {
1594
+ super();
1595
+ /**
1596
+ @internal
1597
+ */
1598
+ this.wrappers = [];
1599
+ if (spec.version != 14 /* File.Version */)
1600
+ throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);
1601
+ let nodeNames = spec.nodeNames.split(" ");
1602
+ this.minRepeatTerm = nodeNames.length;
1603
+ for (let i = 0; i < spec.repeatNodeCount; i++)
1604
+ nodeNames.push("");
1605
+ let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
1606
+ let nodeProps = [];
1607
+ for (let i = 0; i < nodeNames.length; i++)
1608
+ nodeProps.push([]);
1609
+ function setProp(nodeID, prop, value) {
1610
+ nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
1611
+ }
1612
+ if (spec.nodeProps)
1613
+ for (let propSpec of spec.nodeProps) {
1614
+ let prop = propSpec[0];
1615
+ if (typeof prop == "string")
1616
+ prop = NodeProp[prop];
1617
+ for (let i = 1; i < propSpec.length;) {
1618
+ let next = propSpec[i++];
1619
+ if (next >= 0) {
1620
+ setProp(next, prop, propSpec[i++]);
1621
+ }
1622
+ else {
1623
+ let value = propSpec[i + -next];
1624
+ for (let j = -next; j > 0; j--)
1625
+ setProp(propSpec[i++], prop, value);
1626
+ i++;
1627
+ }
1628
+ }
1629
+ }
1630
+ this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
1631
+ name: i >= this.minRepeatTerm ? undefined : name,
1632
+ id: i,
1633
+ props: nodeProps[i],
1634
+ top: topTerms.indexOf(i) > -1,
1635
+ error: i == 0,
1636
+ skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
1637
+ })));
1638
+ if (spec.propSources)
1639
+ this.nodeSet = this.nodeSet.extend(...spec.propSources);
1640
+ this.strict = false;
1641
+ this.bufferLength = DefaultBufferLength;
1642
+ let tokenArray = decodeArray(spec.tokenData);
1643
+ this.context = spec.context;
1644
+ this.specializerSpecs = spec.specialized || [];
1645
+ this.specialized = new Uint16Array(this.specializerSpecs.length);
1646
+ for (let i = 0; i < this.specializerSpecs.length; i++)
1647
+ this.specialized[i] = this.specializerSpecs[i].term;
1648
+ this.specializers = this.specializerSpecs.map(getSpecializer);
1649
+ this.states = decodeArray(spec.states, Uint32Array);
1650
+ this.data = decodeArray(spec.stateData);
1651
+ this.goto = decodeArray(spec.goto);
1652
+ this.maxTerm = spec.maxTerm;
1653
+ this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
1654
+ this.topRules = spec.topRules;
1655
+ this.dialects = spec.dialects || {};
1656
+ this.dynamicPrecedences = spec.dynamicPrecedences || null;
1657
+ this.tokenPrecTable = spec.tokenPrec;
1658
+ this.termNames = spec.termNames || null;
1659
+ this.maxNode = this.nodeSet.types.length - 1;
1660
+ this.dialect = this.parseDialect();
1661
+ this.top = this.topRules[Object.keys(this.topRules)[0]];
1662
+ }
1663
+ createParse(input, fragments, ranges) {
1664
+ let parse = new Parse(this, input, fragments, ranges);
1665
+ for (let w of this.wrappers)
1666
+ parse = w(parse, input, fragments, ranges);
1667
+ return parse;
1668
+ }
1669
+ /**
1670
+ Get a goto table entry @internal
1671
+ */
1672
+ getGoto(state, term, loose = false) {
1673
+ let table = this.goto;
1674
+ if (term >= table[0])
1675
+ return -1;
1676
+ for (let pos = table[term + 1];;) {
1677
+ let groupTag = table[pos++], last = groupTag & 1;
1678
+ let target = table[pos++];
1679
+ if (last && loose)
1680
+ return target;
1681
+ for (let end = pos + (groupTag >> 1); pos < end; pos++)
1682
+ if (table[pos] == state)
1683
+ return target;
1684
+ if (last)
1685
+ return -1;
1686
+ }
1687
+ }
1688
+ /**
1689
+ Check if this state has an action for a given terminal @internal
1690
+ */
1691
+ hasAction(state, terminal) {
1692
+ let data = this.data;
1693
+ for (let set = 0; set < 2; set++) {
1694
+ for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {
1695
+ if ((next = data[i]) == 65535 /* Seq.End */) {
1696
+ if (data[i + 1] == 1 /* Seq.Next */)
1697
+ next = data[i = pair(data, i + 2)];
1698
+ else if (data[i + 1] == 2 /* Seq.Other */)
1699
+ return pair(data, i + 2);
1700
+ else
1701
+ break;
1702
+ }
1703
+ if (next == terminal || next == 0 /* Term.Err */)
1704
+ return pair(data, i + 1);
1705
+ }
1706
+ }
1707
+ return 0;
1708
+ }
1709
+ /**
1710
+ @internal
1711
+ */
1712
+ stateSlot(state, slot) {
1713
+ return this.states[(state * 6 /* ParseState.Size */) + slot];
1714
+ }
1715
+ /**
1716
+ @internal
1717
+ */
1718
+ stateFlag(state, flag) {
1719
+ return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;
1720
+ }
1721
+ /**
1722
+ @internal
1723
+ */
1724
+ validAction(state, action) {
1725
+ return !!this.allActions(state, a => a == action ? true : null);
1726
+ }
1727
+ /**
1728
+ @internal
1729
+ */
1730
+ allActions(state, action) {
1731
+ let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);
1732
+ let result = deflt ? action(deflt) : undefined;
1733
+ for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {
1734
+ if (this.data[i] == 65535 /* Seq.End */) {
1735
+ if (this.data[i + 1] == 1 /* Seq.Next */)
1736
+ i = pair(this.data, i + 2);
1737
+ else
1738
+ break;
1739
+ }
1740
+ result = action(pair(this.data, i + 1));
1741
+ }
1742
+ return result;
1743
+ }
1744
+ /**
1745
+ Get the states that can follow this one through shift actions or
1746
+ goto jumps. @internal
1747
+ */
1748
+ nextStates(state) {
1749
+ let result = [];
1750
+ for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {
1751
+ if (this.data[i] == 65535 /* Seq.End */) {
1752
+ if (this.data[i + 1] == 1 /* Seq.Next */)
1753
+ i = pair(this.data, i + 2);
1754
+ else
1755
+ break;
1756
+ }
1757
+ if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {
1758
+ let value = this.data[i + 1];
1759
+ if (!result.some((v, i) => (i & 1) && v == value))
1760
+ result.push(this.data[i], value);
1761
+ }
1762
+ }
1763
+ return result;
1764
+ }
1765
+ /**
1766
+ Configure the parser. Returns a new parser instance that has the
1767
+ given settings modified. Settings not provided in `config` are
1768
+ kept from the original parser.
1769
+ */
1770
+ configure(config) {
1771
+ // Hideous reflection-based kludge to make it easy to create a
1772
+ // slightly modified copy of a parser.
1773
+ let copy = Object.assign(Object.create(LRParser.prototype), this);
1774
+ if (config.props)
1775
+ copy.nodeSet = this.nodeSet.extend(...config.props);
1776
+ if (config.top) {
1777
+ let info = this.topRules[config.top];
1778
+ if (!info)
1779
+ throw new RangeError(`Invalid top rule name ${config.top}`);
1780
+ copy.top = info;
1781
+ }
1782
+ if (config.tokenizers)
1783
+ copy.tokenizers = this.tokenizers.map(t => {
1784
+ let found = config.tokenizers.find(r => r.from == t);
1785
+ return found ? found.to : t;
1786
+ });
1787
+ if (config.specializers) {
1788
+ copy.specializers = this.specializers.slice();
1789
+ copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
1790
+ let found = config.specializers.find(r => r.from == s.external);
1791
+ if (!found)
1792
+ return s;
1793
+ let spec = Object.assign(Object.assign({}, s), { external: found.to });
1794
+ copy.specializers[i] = getSpecializer(spec);
1795
+ return spec;
1796
+ });
1797
+ }
1798
+ if (config.contextTracker)
1799
+ copy.context = config.contextTracker;
1800
+ if (config.dialect)
1801
+ copy.dialect = this.parseDialect(config.dialect);
1802
+ if (config.strict != null)
1803
+ copy.strict = config.strict;
1804
+ if (config.wrap)
1805
+ copy.wrappers = copy.wrappers.concat(config.wrap);
1806
+ if (config.bufferLength != null)
1807
+ copy.bufferLength = config.bufferLength;
1808
+ return copy;
1809
+ }
1810
+ /**
1811
+ Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
1812
+ are registered for this parser.
1813
+ */
1814
+ hasWrappers() {
1815
+ return this.wrappers.length > 0;
1816
+ }
1817
+ /**
1818
+ Returns the name associated with a given term. This will only
1819
+ work for all terms when the parser was generated with the
1820
+ `--names` option. By default, only the names of tagged terms are
1821
+ stored.
1822
+ */
1823
+ getName(term) {
1824
+ return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
1825
+ }
1826
+ /**
1827
+ The eof term id is always allocated directly after the node
1828
+ types. @internal
1829
+ */
1830
+ get eofTerm() { return this.maxNode + 1; }
1831
+ /**
1832
+ The type of top node produced by the parser.
1833
+ */
1834
+ get topNode() { return this.nodeSet.types[this.top[1]]; }
1835
+ /**
1836
+ @internal
1837
+ */
1838
+ dynamicPrecedence(term) {
1839
+ let prec = this.dynamicPrecedences;
1840
+ return prec == null ? 0 : prec[term] || 0;
1841
+ }
1842
+ /**
1843
+ @internal
1844
+ */
1845
+ parseDialect(dialect) {
1846
+ let values = Object.keys(this.dialects), flags = values.map(() => false);
1847
+ if (dialect)
1848
+ for (let part of dialect.split(" ")) {
1849
+ let id = values.indexOf(part);
1850
+ if (id >= 0)
1851
+ flags[id] = true;
1852
+ }
1853
+ let disabled = null;
1854
+ for (let i = 0; i < values.length; i++)
1855
+ if (!flags[i]) {
1856
+ for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)
1857
+ (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
1858
+ }
1859
+ return new Dialect(dialect, flags, disabled);
1860
+ }
1861
+ /**
1862
+ Used by the output of the parser generator. Not available to
1863
+ user code. @hide
1864
+ */
1865
+ static deserialize(spec) {
1866
+ return new LRParser(spec);
1867
+ }
1868
+ }
1869
+ function pair(data, off) { return data[off] | (data[off + 1] << 16); }
1870
+ function findFinished(stacks) {
1871
+ let best = null;
1872
+ for (let stack of stacks) {
1873
+ let stopped = stack.p.stoppedAt;
1874
+ if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&
1875
+ stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&
1876
+ (!best || best.score < stack.score))
1877
+ best = stack;
1878
+ }
1879
+ return best;
1880
+ }
1881
+ function getSpecializer(spec) {
1882
+ if (spec.external) {
1883
+ let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;
1884
+ return (value, stack) => (spec.external(value, stack) << 1) | mask;
1885
+ }
1886
+ return spec.get;
1887
+ }
1888
+
1889
+ export { ContextTracker, ExternalTokenizer, InputStream, LRParser, LocalTokenGroup, Stack };