parseman 0.26.2 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -33,7 +33,7 @@ export type { CSTNode, CSTLeaf, CSTError, CSTTrivia, CSTChild, CSTRawChild, Node
33
33
  export { parseDoc } from './functional/doc.ts';
34
34
  export type { ParseDoc, ParseDocOptions, Registry, RuleFn } from './functional/doc.ts';
35
35
  export { run } from './functional/run.ts';
36
- export type { RunResult, RunOptions, Runnable } from './functional/run.ts';
36
+ export type { RunResult, RunOptions, RunProfile, RunProfilePass, Runnable } from './functional/run.ts';
37
37
  export { buildTriviaIndex } from './cst/trivia-index.ts';
38
38
  export type { TriviaIndex, TriviaToken, TriviaIndexOptions } from './cst/trivia-index.ts';
39
39
  export { walk, createVisitor } from './cst/walk.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,cAAc,EAAE,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,oBAAoB,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAE1P,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAA;AAClD,YAAY,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAE9D,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AAU9C,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAA;AACpE,YAAY,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAA;AACpD,OAAO,EAAE,MA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2217
2217
  return false;
2218
2218
  }
2219
2219
  }
2220
+ function parserHasTriviaSite(p, seen = /* @__PURE__ */ new Set()) {
2221
+ if (seen.has(p)) return true;
2222
+ seen.add(p);
2223
+ const d = p._def;
2224
+ switch (d.tag) {
2225
+ // Trivia is skipped between/around elements or iterations → a site.
2226
+ case "sequence":
2227
+ case "many":
2228
+ case "oneOrMore":
2229
+ case "sepBy":
2230
+ case "scanTo":
2231
+ case "recover":
2232
+ case "skip":
2233
+ return true;
2234
+ // Nested node manages its own trivia frame; none logs here.
2235
+ case "node":
2236
+ return false;
2237
+ // Pure terminals + trivia-suppressing token: no site.
2238
+ case "regex":
2239
+ case "literal":
2240
+ case "keywords":
2241
+ case "guard":
2242
+ case "token":
2243
+ return false;
2244
+ // Transparent single-child wrappers: recurse.
2245
+ case "optional":
2246
+ case "transform":
2247
+ case "trivia":
2248
+ case "label":
2249
+ case "expect":
2250
+ case "withCtx":
2251
+ case "not":
2252
+ case "field":
2253
+ return parserHasTriviaSite(d.parser, seen);
2254
+ case "choice":
2255
+ return d.parsers.some((x) => parserHasTriviaSite(x, seen));
2256
+ case "grammar":
2257
+ return parserHasTriviaSite(d.parser, seen);
2258
+ case "lazy": {
2259
+ try {
2260
+ return parserHasTriviaSite(d.thunk(), seen);
2261
+ } catch {
2262
+ return true;
2263
+ }
2264
+ }
2265
+ default:
2266
+ return true;
2267
+ }
2268
+ }
2220
2269
  function buildFieldMap(captures) {
2221
2270
  if (!captures?.length) return void 0;
2222
2271
  const out = {};
@@ -5208,32 +5257,49 @@ function emitNode(def, ctx, pos) {
5208
5257
  const smk = structural ? v(ctx, "_smk") : null;
5209
5258
  if (structural) ctx.needsHostReads = true;
5210
5259
  const hostTriviaGate = `_ctx.build !== undefined && (_ctx.build._parsemanCaptureTrivia !== undefined ? _ctx.build._parsemanCaptureTrivia(${JSON.stringify(def.type)}) : (_ctx._pmCapTL ??= _hostReads(_ctx.build, 5)))`;
5211
- const allocStmt = structural ? `${i}const ${capTLv} = ${hostTriviaGate}, ${capSTv} = _ctx._pmCapST ??= (_ctx.build === undefined || _hostReads(_ctx.build, 6))${capFv ? `, ${capFv} = _ctx.build !== undefined && _hostReads(_ctx.build, 2)` : ""}
5212
- ${i}const ${chV} = [], ${rawV} = [], ${tlV} = ${capTLv} ? [] : _EMPTY_TL` : capturesTrivia ? `${i}const ${chV} = [], ${rawV} = [], ${tlV} = []` : `${i}const ${chV} = [], ${rawV} = []`;
5260
+ const pmV = v(ctx, "_pm"), recV = v(ctx, "_rec"), capV = v(ctx, "_cap");
5261
+ const profHoist = `${i}const ${pmV} = _ctx._pmProfile, ${recV} = ${pmV}?.phase === 'recognizer', ${capV} = ${pmV}?.phase === 'capture'`;
5262
+ const profileRecognizer = recV;
5263
+ const profileCapture = capV;
5264
+ const allocStmt = structural ? `${i}const ${capTLv} = !(${profileRecognizer}) && (${profileCapture} || ${hostTriviaGate}), ${capSTv} = !(${profileRecognizer} || ${profileCapture}) && (_ctx._pmCapST ??= (_ctx.build === undefined || _hostReads(_ctx.build, 6)))${capFv ? `, ${capFv} = !(${profileRecognizer}) && (${profileCapture} || (_ctx.build !== undefined && _hostReads(_ctx.build, 2)))` : ""}
5265
+ ${i}const ${chV} = ${profileRecognizer} ? undefined : [], ${rawV} = ${profileRecognizer} ? undefined : [], ${tlV} = ${capTLv} ? [] : _EMPTY_TL` : capturesTrivia ? `${i}const ${chV} = ${profileRecognizer} ? undefined : [], ${rawV} = ${profileRecognizer} ? undefined : [], ${tlV} = ${profileRecognizer} ? undefined : []` : `${i}const ${chV} = ${profileRecognizer} ? undefined : [], ${rawV} = ${profileRecognizer} ? undefined : []`;
5213
5266
  const innerTl = structural ? `${capTLv} ? ${tlV} : undefined` : capturesTrivia ? tlV : "undefined";
5214
- const fieldsOn = structural ? capFv ?? "false" : capturesFields ? "true" : "false";
5267
+ const fieldsOn = structural ? capFv ?? "false" : `${profileRecognizer} ? false : ${capturesFields ? "true" : "false"}`;
5215
5268
  const sf = hasFields ? v(ctx, "_sf") : null;
5216
5269
  const fArr = hasFields ? v(ctx, "_fa") : null;
5217
5270
  const fObj = hasFields ? v(ctx, "_fields") : "undefined";
5271
+ const needsTriviaFrame = parserHasTriviaSite(def.parser);
5272
+ const saveTrivia = needsTriviaFrame ? `, ${st} = _ctx.captureTrivia, ${stl} = _ctx._cstTriviaLog${smk ? `, ${smk} = _ctx._triviaCaptureMask` : ""}` : "";
5273
+ const installTrivia = needsTriviaFrame ? `; _ctx.captureTrivia = true; _ctx._cstTriviaLog = ${innerTl}${smk ? `; _ctx._triviaCaptureMask = ${capTLv} && _ctx.build._parsemanTriviaKinds !== undefined ? _ctx.build._parsemanTriviaKinds(${JSON.stringify(def.type)}) : ${smk}` : ""}` : "";
5274
+ const restoreTrivia = needsTriviaFrame ? `; _ctx.captureTrivia = ${st}; _ctx._cstTriviaLog = ${stl}${smk ? `; _ctx._triviaCaptureMask = ${smk}` : ""}` : "";
5218
5275
  const stmts = [
5276
+ profHoist,
5219
5277
  allocStmt,
5220
- `${i}const ${sc} = _ctx._cstChildren, ${sl} = _ctx._cstLeaves, ${sr} = _ctx._cstRawChildren, ${st} = _ctx.captureTrivia, ${stl} = _ctx._cstTriviaLog${smk ? `, ${smk} = _ctx._triviaCaptureMask` : ""}${sf ? `, ${sf} = _ctx._fields` : ""}`,
5221
- `${i}_ctx._cstChildren = ${chV}; _ctx._cstLeaves = ${chV}; _ctx._cstRawChildren = ${rawV}; _ctx.captureTrivia = true; _ctx._cstTriviaLog = ${innerTl}${smk ? `; _ctx._triviaCaptureMask = ${capTLv} && _ctx.build._parsemanTriviaKinds !== undefined ? _ctx.build._parsemanTriviaKinds(${JSON.stringify(def.type)}) : ${smk}` : ""}${sf ? `; _ctx._fields = ${fieldsOn} ? [] : undefined` : ""}`
5278
+ `${i}const ${sc} = _ctx._cstChildren, ${sl} = _ctx._cstLeaves, ${sr} = _ctx._cstRawChildren${saveTrivia}${sf ? `, ${sf} = _ctx._fields` : ""}`,
5279
+ `${i}_ctx._cstChildren = ${chV}; _ctx._cstLeaves = ${chV}; _ctx._cstRawChildren = ${rawV}${installTrivia}${sf ? `; _ctx._fields = ${fieldsOn} ? [] : undefined` : ""}`
5222
5280
  ];
5223
5281
  const { stmts: innerStmts, okVar, endVar } = emitFallible(def.parser, ctx, pos);
5224
5282
  stmts.push(...innerStmts);
5225
5283
  if (sf && fArr) {
5226
5284
  stmts.push(`${i}const ${fArr} = _ctx._fields`);
5227
5285
  }
5228
- stmts.push(`${i}_ctx._cstChildren = ${sc}; _ctx._cstLeaves = ${sl}; _ctx._cstRawChildren = ${sr}; _ctx.captureTrivia = ${st}; _ctx._cstTriviaLog = ${stl}${smk ? `; _ctx._triviaCaptureMask = ${smk}` : ""}${sf ? `; _ctx._fields = ${sf}` : ""}`);
5286
+ stmts.push(`${i}_ctx._cstChildren = ${sc}; _ctx._cstLeaves = ${sl}; _ctx._cstRawChildren = ${sr}${restoreTrivia}${sf ? `; _ctx._fields = ${sf}` : ""}`);
5229
5287
  stmts.push(...emitIfFail(ctx, `!${okVar}`, propagateFailBody(ctx)));
5288
+ stmts.push(
5289
+ `${i}if (_ctx._pmProfile) {`,
5290
+ `${i} _ctx._pmProfile.nodes++`,
5291
+ `${i} if (${profileCapture}) {`,
5292
+ `${i} _ctx._pmProfile.childSlots += ${chV}.length; _ctx._pmProfile.rawSlots += ${rawV}.length; _ctx._pmProfile.triviaSlots += ${tlV}.length${fArr ? `; _ctx._pmProfile.fieldSlots += ${fArr} ? ${fArr}.length : 0` : ""}`,
5293
+ `${i} }`,
5294
+ `${i}}`
5295
+ );
5230
5296
  let stV = "undefined";
5231
5297
  if (structural) {
5232
5298
  stV = v(ctx, "_nst");
5233
5299
  stmts.push(`${i}const ${stV} = ${capSTv} && _ctx.state !== undefined ? Object.assign({}, _ctx.state) : undefined`);
5234
5300
  } else if (clonesState) {
5235
5301
  stV = v(ctx, "_nst");
5236
- stmts.push(`${i}const ${stV} = _ctx.state !== undefined ? Object.assign({}, _ctx.state) : undefined`);
5302
+ stmts.push(`${i}const ${stV} = !(${profileRecognizer} || ${profileCapture}) && _ctx.state !== undefined ? Object.assign({}, _ctx.state) : undefined`);
5237
5303
  }
5238
5304
  if (sf && fArr) {
5239
5305
  const fe = v(ctx, "_fe");
@@ -5253,15 +5319,17 @@ ${i}const ${chV} = [], ${rawV} = [], ${tlV} = ${capTLv} ? [] : _EMPTY_TL` : capt
5253
5319
  }
5254
5320
  const ndV = v(ctx, "_nd");
5255
5321
  const buildExpr = structural ? `{ _tag: 'node', type: ${JSON.stringify(def.type)}, span: { start: ${pos}, end: ${endVar} }, state: ${stV} ?? null, children: ${chV} }` : mkType ? emitInlineMkNodeExpr(mkType, chV, rawV, pos, endVar, tlV) : `${buildRef(ctx)}[${buildIdx}](${chV}, ${fObj}, { start: ${pos}, end: ${endVar} }, ${rawV}, ${tlV}, ${stV})`;
5256
- const ndExpr = ctx.ns || structural ? `_ctx.build !== undefined ? _ctx.build(${JSON.stringify(def.type)}, ${chV}, ${fObj}, { start: ${pos}, end: ${endVar} }, ${rawV}, ${tlV}, ${stV}) : (${buildExpr})` : buildExpr;
5322
+ const ndExpr = ctx.ns || structural ? `_ctx.build !== undefined ? (_ctx._pmProfile?.phase === 'host' && _ctx._pmProfile.hostCalls++, _ctx.build(${JSON.stringify(def.type)}, ${chV}, ${fObj}, { start: ${pos}, end: ${endVar} }, ${rawV}, ${tlV}, ${stV})) : (${buildExpr})` : buildExpr;
5257
5323
  const hostCollapseExpr = ctx.ns || structural ? `_ctx.build !== undefined && _ctx.build._parsemanCstCollapse !== undefined && ${chV}.length === 1 && ${rawV}.length === 1 && _ctx.build._parsemanCstCollapse(${JSON.stringify(def.type)}, ${chV}[0], ${chV}, ${rawV}) ? ${chV}[0] : (${ndExpr})` : ndExpr;
5258
5324
  const unwrapExpr = `${chV}.length === 1 ? (${chV}[0] !== null && typeof ${chV}[0] === 'object' && ${chV}[0]._tag === 'leaf' ? ${chV}[0].value : ${chV}[0]) : (${ndExpr})`;
5259
5325
  const collapseExpr = `${chV}.length === 1 ? ${chV}[0] : (${ndExpr})`;
5260
5326
  const finalExpr = def.unwrap ? unwrapExpr : def.collapse ? collapseExpr : hostCollapseExpr;
5261
5327
  stmts.push(
5262
- `${i}const ${ndV} = ${finalExpr}`,
5263
- `${i}if (${sc}) ${sc}.push(${ndV})`,
5264
- `${i}if (${sr}) ${sr}.push((typeof ${ndV} === 'object' && ${ndV} !== null && (${ndV}._tag === 'node' || ${ndV}._tag === 'leaf' || ${ndV}._tag === 'parseError')) ? ${ndV} : { _tag: 'leaf', value: typeof ${ndV} === 'string' ? ${ndV} : '', span: { start: ${pos}, end: ${endVar} } })`
5328
+ `${i}const ${ndV} = (${profileRecognizer} || ${profileCapture}) ? undefined : (${finalExpr})`,
5329
+ `${i}if (!(${profileRecognizer})) {`,
5330
+ `${i} if (${sc}) ${sc}.push(${ndV})`,
5331
+ `${i} if (${sr}) ${sr}.push((typeof ${ndV} === 'object' && ${ndV} !== null && (${ndV}._tag === 'node' || ${ndV}._tag === 'leaf' || ${ndV}._tag === 'parseError')) ? ${ndV} : { _tag: 'leaf', value: typeof ${ndV} === 'string' ? ${ndV} : '', span: { start: ${pos}, end: ${endVar} } })`,
5332
+ `${i}}`
5265
5333
  );
5266
5334
  return { stmts, valueVar: ndV, endVar };
5267
5335
  }
@@ -5547,7 +5615,7 @@ function emitDispatch(p, ctx, pos) {
5547
5615
  ctx.indent = 1;
5548
5616
  ctx.failLabel = "_pfail";
5549
5617
  ctx.recordFail = true;
5550
- const innerR = emit(innerParser, ctx, "_pos");
5618
+ const innerR = emitDispatch(innerParser, ctx, "_pos");
5551
5619
  ctx.indent = savedIndent;
5552
5620
  ctx.failLabel = savedFailLabel;
5553
5621
  ctx.recordFail = savedRecord;
@@ -6179,6 +6247,23 @@ function escapeClassChar(ch) {
6179
6247
  return ch.replace(/[\\\]^-]/g, "\\$&");
6180
6248
  }
6181
6249
 
6250
+ // src/combinators/withCtx.ts
6251
+ function withCtx(extra, combinator) {
6252
+ const meta = {
6253
+ firstSet: combinator._meta.firstSet,
6254
+ canMatchNewline: combinator._meta.canMatchNewline,
6255
+ isTrivia: false
6256
+ };
6257
+ return {
6258
+ _tag: "withCtx",
6259
+ _meta: meta,
6260
+ _def: { tag: "withCtx", extra, parser: combinator },
6261
+ parse(input, pos, ctx) {
6262
+ return combinator.parse(input, pos, { ...ctx, state: extra });
6263
+ }
6264
+ };
6265
+ }
6266
+
6182
6267
  // src/compiler/ir-serialize.ts
6183
6268
  function childrenOf2(def) {
6184
6269
  switch (def.tag) {
@@ -6195,6 +6280,7 @@ function childrenOf2(def) {
6195
6280
  case "field":
6196
6281
  case "not":
6197
6282
  case "node":
6283
+ case "withCtx":
6198
6284
  case "expect":
6199
6285
  return [def.parser];
6200
6286
  case "grammar":
@@ -6210,7 +6296,6 @@ function childrenOf2(def) {
6210
6296
  case "regex":
6211
6297
  case "keywords":
6212
6298
  case "guard":
6213
- case "withCtx":
6214
6299
  case "recover":
6215
6300
  case "unknown":
6216
6301
  return [];
@@ -6285,6 +6370,17 @@ function evalRuleMapIR(ir) {
6285
6370
  c._def.gateSrcs = gateSrcs;
6286
6371
  return c;
6287
6372
  };
6373
+ const _wc = (src, inner) => {
6374
+ let extra;
6375
+ try {
6376
+ extra = (0, eval)(`(${src})`);
6377
+ } catch {
6378
+ extra = void 0;
6379
+ }
6380
+ const w = withCtx(extra, inner);
6381
+ w._def.extraSrc = src;
6382
+ return w;
6383
+ };
6288
6384
  const fn = new Function(
6289
6385
  "rules",
6290
6386
  "ref",
@@ -6311,6 +6407,7 @@ function evalRuleMapIR(ir) {
6311
6407
  "_tf",
6312
6408
  "_nd",
6313
6409
  "_gch",
6410
+ "_wc",
6314
6411
  `return (${ir})`
6315
6412
  );
6316
6413
  const map = fn(
@@ -6338,7 +6435,8 @@ function evalRuleMapIR(ir) {
6338
6435
  expect,
6339
6436
  _tf,
6340
6437
  _nd,
6341
- _gch
6438
+ _gch,
6439
+ _wc
6342
6440
  );
6343
6441
  return Object.entries(map);
6344
6442
  }
@@ -6394,7 +6492,7 @@ ${body}
6394
6492
  this.analyze(target, active);
6395
6493
  return;
6396
6494
  }
6397
- if (def.tag === "guard" || def.tag === "withCtx" || def.tag === "recover" || def.tag === "unknown") {
6495
+ if (def.tag === "guard" || def.tag === "recover" || def.tag === "unknown") {
6398
6496
  throw new Unserializable(`unsupported tag ${def.tag}`);
6399
6497
  }
6400
6498
  this.counts.set(c, (this.counts.get(c) ?? 0) + 1);
@@ -6503,8 +6601,11 @@ ${body}
6503
6601
  const trivia2 = def.clearTrivia ? "null" : def.triviaParser ? kid(def.triviaParser) : "undefined";
6504
6602
  return `parser({ trivia: ${trivia2}${def.trackLines ? ", trackLines: true" : ""} }, ${kid(def.parser)})`;
6505
6603
  }
6604
+ case "withCtx": {
6605
+ if (def.extraSrc === void 0) throw new Unserializable("withCtx without extraSrc");
6606
+ return `_wc(${JSON.stringify(def.extraSrc)}, ${kid(def.parser)})`;
6607
+ }
6506
6608
  case "guard":
6507
- case "withCtx":
6508
6609
  case "recover":
6509
6610
  case "unknown":
6510
6611
  throw new Unserializable(`unsupported tag ${def.tag}`);
@@ -6678,23 +6779,6 @@ function guard(predicate) {
6678
6779
  };
6679
6780
  }
6680
6781
 
6681
- // src/combinators/withCtx.ts
6682
- function withCtx(extra, combinator) {
6683
- const meta = {
6684
- firstSet: combinator._meta.firstSet,
6685
- canMatchNewline: combinator._meta.canMatchNewline,
6686
- isTrivia: false
6687
- };
6688
- return {
6689
- _tag: "withCtx",
6690
- _meta: meta,
6691
- _def: { tag: "withCtx", extra, parser: combinator },
6692
- parse(input, pos, ctx) {
6693
- return combinator.parse(input, pos, { ...ctx, state: extra });
6694
- }
6695
- };
6696
- }
6697
-
6698
6782
  // src/combinators/completions.ts
6699
6783
  function completionsAt(target, input, offset, options = {}) {
6700
6784
  const probe = { offset, best: null };
@@ -7213,7 +7297,7 @@ function parseDoc(registry, rootRule, input, opts = {}) {
7213
7297
 
7214
7298
  // src/functional/run.ts
7215
7299
  var invoke = (r, input, pos, ctx) => typeof r === "function" ? r(input, pos, ctx) : r.parse(input, pos, ctx);
7216
- function run(entry, input, options = {}) {
7300
+ function runOnce(entry, input, options, phase, profileState) {
7217
7301
  if (typeof entry !== "function" && typeof entry?.parse !== "function") {
7218
7302
  throw new TypeError(
7219
7303
  `run(): start production is ${entry === null ? "null" : typeof entry}, not a rule \u2014 the requested grammar rule does not exist (check the rule name).`
@@ -7221,11 +7305,12 @@ function run(entry, input, options = {}) {
7221
7305
  }
7222
7306
  const triviaLog = [];
7223
7307
  const errors = [];
7308
+ const profile = profileState ?? (phase === void 0 ? void 0 : { phase, nodes: 0, childSlots: 0, rawSlots: 0, triviaSlots: 0, fieldSlots: 0, hostCalls: 0 });
7309
+ const skipGlobalSinks = phase === "recognizer" || phase === "capture";
7224
7310
  const grammarTrivia = typeof entry !== "function" ? entry._meta.grammarTrivia : void 0;
7225
7311
  const ctx = {
7226
7312
  trackLines: false,
7227
- _triviaLog: triviaLog,
7228
- _errors: errors,
7313
+ ...skipGlobalSinks ? { _pmProfile: profile } : { _triviaLog: triviaLog, _errors: errors, ...profile === void 0 ? {} : { _pmProfile: profile } },
7229
7314
  build: options.build,
7230
7315
  state: options.state,
7231
7316
  ...grammarTrivia !== void 0 ? { trivia: grammarTrivia, ...grammarTrivia._meta.triviaKindLabels ? { triviaKindLabels: grammarTrivia._meta.triviaKindLabels } : {} } : {},
@@ -7252,6 +7337,38 @@ function run(entry, input, options = {}) {
7252
7337
  unconsumedFrom
7253
7338
  };
7254
7339
  }
7340
+ function clonePassState(state) {
7341
+ if (state === null || typeof state !== "object") return state;
7342
+ return Array.isArray(state) ? [...state] : { ...state };
7343
+ }
7344
+ function profilePass(entry, input, options, phase) {
7345
+ const state = { phase, nodes: 0, childSlots: 0, rawSlots: 0, triviaSlots: 0, fieldSlots: 0, hostCalls: 0 };
7346
+ const passOptions = options.state === void 0 ? options : { ...options, state: clonePassState(options.state) };
7347
+ const start = performance.now();
7348
+ const result = runOnce(entry, input, passOptions, phase, state);
7349
+ const { phase: _phase, ...counts } = state;
7350
+ return { result, profile: { ms: performance.now() - start, ...counts } };
7351
+ }
7352
+ function run(entry, input, options = {}) {
7353
+ if (!options.profile) return runOnce(entry, input, options);
7354
+ if (typeof entry !== "function") {
7355
+ throw new TypeError("run({ profile: true }) requires a compiled parser entry");
7356
+ }
7357
+ const recognizer = profilePass(entry, input, options, "recognizer");
7358
+ const capture = profilePass(entry, input, options, "capture");
7359
+ const host = profilePass(entry, input, options, "host");
7360
+ if (recognizer.result.ok !== host.result.ok || capture.result.ok !== host.result.ok || recognizer.result.unconsumedFrom !== host.result.unconsumedFrom || capture.result.unconsumedFrom !== host.result.unconsumedFrom) {
7361
+ throw new Error("run({ profile: true }) changed recognition; the grammar is not profile-safe");
7362
+ }
7363
+ return {
7364
+ ...host.result,
7365
+ profile: {
7366
+ recognizer: recognizer.profile,
7367
+ structuralCapture: capture.profile,
7368
+ hostConstruction: host.profile
7369
+ }
7370
+ };
7371
+ }
7255
7372
 
7256
7373
  // src/cst/trivia-index.ts
7257
7374
  function merge(map, key, run2) {