index.es.js 62 KB

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