index.cjs 63 KB

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