@thomasfosterau/effect-parse 0.4.1 → 0.5.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/README.md +37 -13
- package/dist/Ascii.d.ts +11 -4
- package/dist/Ascii.d.ts.map +1 -1
- package/dist/Ascii.js +7 -1
- package/dist/Ascii.js.map +1 -1
- package/dist/Binary.d.ts.map +1 -1
- package/dist/Binary.js +64 -35
- package/dist/Binary.js.map +1 -1
- package/dist/Bits.d.ts.map +1 -1
- package/dist/Bits.js +7 -4
- package/dist/Bits.js.map +1 -1
- package/dist/Compiler.d.ts +74 -2
- package/dist/Compiler.d.ts.map +1 -1
- package/dist/Compiler.js +78 -1
- package/dist/Compiler.js.map +1 -1
- package/dist/Expression.d.ts.map +1 -1
- package/dist/Expression.js +86 -74
- package/dist/Expression.js.map +1 -1
- package/dist/Input.d.ts +37 -4
- package/dist/Input.d.ts.map +1 -1
- package/dist/Input.js +42 -0
- package/dist/Input.js.map +1 -1
- package/dist/Nom.d.ts +5 -15
- package/dist/Nom.d.ts.map +1 -1
- package/dist/Nom.js.map +1 -1
- package/dist/ParseError.d.ts.map +1 -1
- package/dist/ParseError.js.map +1 -1
- package/dist/Parser.d.ts +366 -26
- package/dist/Parser.d.ts.map +1 -1
- package/dist/Parser.js +390 -19
- package/dist/Parser.js.map +1 -1
- package/dist/ParserSchema.js +1 -1
- package/dist/ParserStream.d.ts +3 -2
- package/dist/ParserStream.d.ts.map +1 -1
- package/dist/ParserStream.js +13 -9
- package/dist/ParserStream.js.map +1 -1
- package/dist/Syntax.d.ts +23 -5
- package/dist/Syntax.d.ts.map +1 -1
- package/dist/Syntax.js.map +1 -1
- package/dist/Text.d.ts.map +1 -1
- package/dist/Text.js +9 -9
- package/dist/Text.js.map +1 -1
- package/dist/Token.d.ts +55 -10
- package/dist/Token.d.ts.map +1 -1
- package/dist/Token.js +59 -21
- package/dist/Token.js.map +1 -1
- package/dist/internal/compiler/closure.d.ts.map +1 -1
- package/dist/internal/compiler/closure.js +257 -97
- package/dist/internal/compiler/closure.js.map +1 -1
- package/dist/internal/compiler/entries.d.ts +3 -1
- package/dist/internal/compiler/entries.d.ts.map +1 -1
- package/dist/internal/compiler/entries.js +3 -2
- package/dist/internal/compiler/entries.js.map +1 -1
- package/dist/internal/compiler/first.d.ts.map +1 -1
- package/dist/internal/compiler/first.js +7 -1
- package/dist/internal/compiler/first.js.map +1 -1
- package/dist/internal/compiler/graph.d.ts +17 -0
- package/dist/internal/compiler/graph.d.ts.map +1 -0
- package/dist/internal/compiler/graph.js +56 -0
- package/dist/internal/compiler/graph.js.map +1 -0
- package/dist/internal/compiler/jit.d.ts +5 -0
- package/dist/internal/compiler/jit.d.ts.map +1 -1
- package/dist/internal/compiler/jit.js +185 -96
- package/dist/internal/compiler/jit.js.map +1 -1
- package/dist/internal/compiler/registry.d.ts +10 -2
- package/dist/internal/compiler/registry.d.ts.map +1 -1
- package/dist/internal/compiler/registry.js.map +1 -1
- package/dist/internal/compiler/search.d.ts +32 -0
- package/dist/internal/compiler/search.d.ts.map +1 -0
- package/dist/internal/compiler/search.js +68 -0
- package/dist/internal/compiler/search.js.map +1 -0
- package/dist/internal/compiler/sets.d.ts.map +1 -1
- package/dist/internal/compiler/sets.js +1 -1
- package/dist/internal/compiler/sets.js.map +1 -1
- package/dist/internal/compiler/wasm.d.ts +8 -0
- package/dist/internal/compiler/wasm.d.ts.map +1 -0
- package/dist/internal/compiler/wasm.js +2769 -0
- package/dist/internal/compiler/wasm.js.map +1 -0
- package/dist/internal/compiler/wasmAsm.d.ts +199 -0
- package/dist/internal/compiler/wasmAsm.d.ts.map +1 -0
- package/dist/internal/compiler/wasmAsm.js +427 -0
- package/dist/internal/compiler/wasmAsm.js.map +1 -0
- package/dist/internal/entries.d.ts +3 -1
- package/dist/internal/entries.d.ts.map +1 -1
- package/dist/internal/entries.js.map +1 -1
- package/dist/internal/node.d.ts +58 -2
- package/dist/internal/node.d.ts.map +1 -1
- package/dist/internal/node.js +13 -3
- package/dist/internal/node.js.map +1 -1
- package/dist/internal/numbers.d.ts.map +1 -1
- package/dist/internal/numbers.js.map +1 -1
- package/dist/internal/run.d.ts +12 -0
- package/dist/internal/run.d.ts.map +1 -1
- package/dist/internal/run.js +51 -11
- package/dist/internal/run.js.map +1 -1
- package/dist/internal/stack.d.ts +6 -0
- package/dist/internal/stack.d.ts.map +1 -1
- package/dist/internal/stack.js +8 -2
- package/dist/internal/stack.js.map +1 -1
- package/dist/internal/syntax.d.ts +4 -4
- package/dist/internal/syntax.d.ts.map +1 -1
- package/dist/internal/syntax.js +18 -10
- package/dist/internal/syntax.js.map +1 -1
- package/dist/internal/text.d.ts +32 -0
- package/dist/internal/text.d.ts.map +1 -1
- package/dist/internal/text.js +68 -14
- package/dist/internal/text.js.map +1 -1
- package/dist/internal/tokens.d.ts +13 -0
- package/dist/internal/tokens.d.ts.map +1 -1
- package/dist/internal/tokens.js +59 -39
- package/dist/internal/tokens.js.map +1 -1
- package/package.json +5 -4
- package/src/Ascii.ts +42 -9
- package/src/Binary.ts +151 -71
- package/src/Bits.ts +12 -6
- package/src/Compiler.ts +101 -10
- package/src/Expression.ts +94 -81
- package/src/Input.ts +65 -6
- package/src/Nom.ts +15 -5
- package/src/ParseError.ts +3 -0
- package/src/Parser.ts +678 -127
- package/src/ParserStream.ts +37 -18
- package/src/Syntax.ts +60 -36
- package/src/Text.ts +16 -15
- package/src/Token.ts +138 -29
- package/src/internal/compiler/closure.ts +362 -135
- package/src/internal/compiler/entries.ts +4 -2
- package/src/internal/compiler/first.ts +10 -0
- package/src/internal/compiler/graph.ts +68 -0
- package/src/internal/compiler/jit.ts +284 -154
- package/src/internal/compiler/registry.ts +10 -2
- package/src/internal/compiler/search.ts +68 -0
- package/src/internal/compiler/sets.ts +7 -3
- package/src/internal/compiler/wasm.ts +3203 -0
- package/src/internal/compiler/wasmAsm.ts +484 -0
- package/src/internal/entries.ts +8 -2
- package/src/internal/node.ts +54 -4
- package/src/internal/numbers.ts +3 -1
- package/src/internal/run.ts +71 -12
- package/src/internal/stack.ts +8 -1
- package/src/internal/syntax.ts +39 -18
- package/src/internal/text.ts +97 -9
- package/src/internal/tokens.ts +96 -14
package/dist/ParserSchema.js
CHANGED
|
@@ -8,10 +8,10 @@ import * as Arr from "effect/Array";
|
|
|
8
8
|
import * as Ascii from "./Ascii.js";
|
|
9
9
|
import * as Effect from "effect/Effect";
|
|
10
10
|
import { dual } from "effect/Function";
|
|
11
|
+
import * as Record from "effect/Record";
|
|
11
12
|
import * as Match from "effect/Match";
|
|
12
13
|
import * as MutableHashMap from "effect/MutableHashMap";
|
|
13
14
|
import * as Order from "effect/Order";
|
|
14
|
-
import * as Record from "effect/Record";
|
|
15
15
|
import * as Schema from "effect/Schema";
|
|
16
16
|
import * as SchemaAST from "effect/SchemaAST";
|
|
17
17
|
import * as SchemaIssue from "effect/SchemaIssue";
|
package/dist/ParserStream.d.ts
CHANGED
|
@@ -30,8 +30,9 @@ export interface ParseManyOptions<I> {
|
|
|
30
30
|
*
|
|
31
31
|
* A parser compiled with the `Compiler` module runs compiled, with the
|
|
32
32
|
* build that handles partial input (see `Parser.run`); a value that fails
|
|
33
|
-
*
|
|
34
|
-
* `Incomplete`
|
|
33
|
+
* is parsed again interpreted, so errors are the interpreter's. A value
|
|
34
|
+
* cut short by its chunk is not: compiled code reports `Incomplete` where
|
|
35
|
+
* the interpreter does.
|
|
35
36
|
*
|
|
36
37
|
* @since 0.1.0
|
|
37
38
|
* @category combinators
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ParserStream.d.ts","names":[],"sources":["../src/ParserStream.ts"],"mappings":";;;;;;;;;;;YA+CY,qBAAqB,aAAa;;;;;;;
|
|
1
|
+
{"version":3,"file":"ParserStream.d.ts","names":[],"sources":["../src/ParserStream.ts"],"mappings":";;;;;;;;;;;YA+CY,qBAAqB,aAAa;;;;;;;iBA0C7B,iBAAiB;;WAEvB,QAAQ,OAAO;;;;;;;;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GACL,QAAQ,OAAO,GAAG,GAAG,GAAG,eACtB,MAAM,aAAa,OAAO,OAAO,GAAG,WAAW,WAAW,KAAK,WAAW;GAC7E,GAAG,GAAG,GACL,MAAM,UACN,QAAQ,OAAO,GAAG,GAAG,GAAG,cACvB,OAAO,OAAO,GAAG,WAAW,WAAW,KAAK,WAAW"}
|
package/dist/ParserStream.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import * as Predicate from "effect/Predicate";
|
|
2
2
|
import { Fail, Failure, State, fromSource } from "./Input.js";
|
|
3
3
|
import * as Registry from "./internal/compiler/registry.js";
|
|
4
|
+
import * as Run from "./internal/run.js";
|
|
4
5
|
import { isEmptyUnits } from "./internal/text.js";
|
|
5
6
|
import * as Data from "effect/Data";
|
|
6
7
|
import * as Effect from "effect/Effect";
|
|
7
8
|
import { dual } from "effect/Function";
|
|
8
9
|
import * as ParseError from "./ParseError.js";
|
|
9
|
-
import * as Run from "./internal/run.js";
|
|
10
10
|
import * as Stack from "./internal/stack.js";
|
|
11
11
|
import * as Stream from "effect/Stream";
|
|
12
12
|
// src/ParserStream.ts
|
|
@@ -59,8 +59,9 @@ const noProgress = (input, offset) => ParseError.fromFailure(input, new Failure(
|
|
|
59
59
|
*
|
|
60
60
|
* A parser compiled with the `Compiler` module runs compiled, with the
|
|
61
61
|
* build that handles partial input (see `Parser.run`); a value that fails
|
|
62
|
-
*
|
|
63
|
-
* `Incomplete`
|
|
62
|
+
* is parsed again interpreted, so errors are the interpreter's. A value
|
|
63
|
+
* cut short by its chunk is not: compiled code reports `Incomplete` where
|
|
64
|
+
* the interpreter does.
|
|
64
65
|
*
|
|
65
66
|
* @since 0.1.0
|
|
66
67
|
* @category combinators
|
|
@@ -79,9 +80,14 @@ const parseMany = /*#__PURE__*/ dual((args) => Stream.isStream(args[0]), (self,
|
|
|
79
80
|
partial,
|
|
80
81
|
context
|
|
81
82
|
});
|
|
82
|
-
const a = Run.runOn(parser, step, state);
|
|
83
|
+
const a = Run.runOn(parser, step, state, false);
|
|
83
84
|
if (a === Fail) {
|
|
84
85
|
if (partial && state.mode === "Incomplete") break;
|
|
86
|
+
state.reset(offset, {
|
|
87
|
+
partial,
|
|
88
|
+
context
|
|
89
|
+
});
|
|
90
|
+
Run.runOn(parser, step, state);
|
|
85
91
|
return Effect.fail(ParseError.fromFailure(input, state.reportedFailure(), state.mode, state.encoding));
|
|
86
92
|
}
|
|
87
93
|
if (state.pos === offset) return Effect.fail(noProgress(input, offset));
|
|
@@ -148,11 +154,9 @@ var Incremental = class {
|
|
|
148
154
|
}
|
|
149
155
|
}
|
|
150
156
|
input() {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
default: return this.text;
|
|
155
|
-
}
|
|
157
|
+
if (this.kind === 1) return this.bytes.subarray(0, this.length);
|
|
158
|
+
if (this.kind === 2) return this.items;
|
|
159
|
+
return this.text;
|
|
156
160
|
}
|
|
157
161
|
push(chunk) {
|
|
158
162
|
if (isEmptyUnits(chunk)) return;
|
package/dist/ParserStream.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ParserStream.js","names":[],"sources":["../src/ParserStream.ts"],"sourcesContent":["/**\n * Running parsers over Effect `Stream`s of input chunks.\n *\n * This is where nom's and winnow's *partial* (streaming) parsing meets\n * Effect: chunks are buffered and the parser runs in partial mode, so a\n * value split across chunk boundaries is reported as `Incomplete` and\n * retried once more data arrives. When the stream ends, the leftover input\n * is parsed in complete mode.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n * import { Ascii, Parser, ParserStream, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const line = Parser.terminated(Ascii.decInt, Token.literal(\"\\n\"))\n *\n * const program = Stream.make(\"1\\n2\", \"3\\n\", \"4\\n\").pipe(\n * ParserStream.parseMany(line),\n * Stream.runCollect\n * )\n * // Effect.runSync(program) => [1, 23, 4]\n * ```\n *\n * @since 0.1.0\n */\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\nimport type { BinaryInput, Input, Source } from \"./Input.js\"\nimport { Fail, Failure, fromSource, State } from \"./Input.js\"\nimport * as ParseError from \"./ParseError.js\"\nimport * as Registry from \"./internal/compiler/registry.js\"\nimport type * as Resume from \"./internal/resume.js\"\nimport * as Run from \"./internal/run.js\"\nimport * as Stack from \"./internal/stack.js\"\nimport { isEmptyUnits } from \"./internal/text.js\"\nimport type { Parser } from \"./Parser.js\"\n\n/**\n * Input kinds that can be streamed in chunks.\n *\n * @since 0.1.0\n * @category models\n */\nexport type Chunkable = string | Uint8Array | ReadonlyArray<unknown>\n\nconst concat = <I extends Chunkable>(first: I, b: I): I => {\n // Widened so the checks below narrow it (a type parameter does not narrow).\n const a: Chunkable = first\n if (Predicate.isString(a)) return (a + (b as string)) as I\n if (a instanceof Uint8Array) {\n if (a.byteLength === 0) return b\n const out = new Uint8Array(a.length + (b as Uint8Array).length)\n out.set(a)\n out.set(b as Uint8Array, a.length)\n return out as I\n }\n return [...a, ...(b as ReadonlyArray<unknown>)] as unknown as I\n}\n\nconst sliceFrom = <I extends Chunkable>(input: I, offset: number): I =>\n (Predicate.isString(input) ? input.slice(offset) : input.slice(offset)) as I\n\nconst noProgress = (input: Input, offset: number) =>\n ParseError.fromFailure<never>(\n input,\n new Failure(offset, \"Assert\", [], [], false, undefined, \"`parseMany` parsers must always consume\", 0),\n \"Cut\"\n )\n\n/**\n * Options for {@link parseMany}.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface ParseManyOptions<I> {\n /** The empty input, used to initialise the buffer (inferred from the first chunk if omitted). */\n readonly empty?: Source<I> | undefined\n}\n\n/**\n * Transforms a stream of input chunks into a stream of parsed values by\n * applying `parser` repeatedly. Each application must consume input.\n *\n * Services required by the parser are taken from the stream's context.\n * Error offsets are relative to the internal buffer of unconsumed input,\n * which is also the `input` of the reported `ParseError`.\n *\n * A parser compiled with the `Compiler` module runs compiled, with the\n * build that handles partial input (see `Parser.run`); a value that fails\n * or needs more input is parsed again interpreted, so errors and\n * `Incomplete` are the interpreter's.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseMany: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Stream.suspend(() => {\n const step = parser.step\n let buffer: I | undefined = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n\n const drain = (context: any, partial: boolean): Effect.Effect<Array<A>, ParseError.ParseError<E>> => {\n const out: Array<A> = []\n if (buffer === undefined) return Effect.succeed(out)\n const input = buffer\n // One state for the whole buffer, reset before each value\n const state = new State(input)\n let offset = 0\n while (offset < input.length) {\n state.reset(offset, { partial, context })\n const a = Run.runOn(parser, step, state)\n if (a === Fail) {\n if (partial && state.mode === \"Incomplete\") break\n return Effect.fail(ParseError.fromFailure<E>(input, state.reportedFailure(), state.mode, state.encoding))\n }\n if (state.pos === offset) return Effect.fail(noProgress(input, offset))\n out.push(a)\n offset = state.pos\n }\n buffer = sliceFrom(input, offset)\n return Effect.succeed(out)\n }\n\n const feed = (source: Source<I>) =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const chunk = fromSource<I>(source)\n buffer = buffer === undefined ? chunk : concat(buffer, chunk)\n return drain(context, true)\n })\n )\n\n const finish = Effect.flatMap(Effect.context<R>(), (context) => Effect.suspend(() => drain(context, false)))\n\n return self.pipe(\n Stream.mapEffect(feed),\n Stream.flattenIterable,\n Stream.concat(Stream.unwrap(Effect.map(finish, Stream.fromIterable)))\n )\n })\n)\n\n/**\n * Parses a stream of chunks incrementally, as one input. Chunks are parsed\n * as they arrive, in partial mode; when the parser runs out of input, its\n * repetitions keep checkpoints (see `internal/resume.ts`), so the next\n * attempt carries on from where the last one stopped instead of starting\n * over.\n */\nclass Incremental<A, E, I extends Chunkable> {\n private kind: 0 | 1 | 2 | undefined\n private text = \"\"\n private bytes = new Uint8Array(0)\n private items: Array<unknown> = []\n private length = 0\n private readonly resume: Resume.Checkpoints = new Map()\n /** The input length at the last attempt, and where that attempt ran out of input. */\n private attempted = 0\n private restart = 0\n private pushed = 0\n /** Set once an attempt settles: a success (with its end offset) or a definite failure. */\n private settled: { readonly value: A; readonly pos: number } | \"failed\" | undefined\n\n constructor(\n private readonly parser: Parser<A, E, any, I>,\n private readonly context: Context.Context<never>,\n empty: I | undefined\n ) {\n if (empty !== undefined) this.append(empty)\n }\n\n private append(chunk: I): void {\n if (Predicate.isString(chunk)) {\n this.kind ??= 0\n this.text += chunk\n this.length += chunk.length\n } else if (chunk instanceof Uint8Array) {\n this.kind ??= 1\n const needed = this.length + chunk.length\n if (needed > this.bytes.length) {\n // Grow geometrically, so appending costs amortized constant time per byte\n const grown = new Uint8Array(Math.max(needed, this.bytes.length * 2, 4096))\n grown.set(this.bytes.subarray(0, this.length))\n this.bytes = grown\n }\n this.bytes.set(chunk, this.length)\n this.length = needed\n } else {\n this.kind ??= 2\n for (let i = 0; i < chunk.length; i++) this.items.push(chunk[i])\n this.length = this.items.length\n }\n }\n\n private input(): I {\n switch (this.kind) {\n case 1:\n return this.bytes.subarray(0, this.length) as I\n case 2:\n // Items are only appended between attempts, after each state has read its `end`\n return this.items as unknown as I\n default:\n return this.text as I\n }\n }\n\n push(chunk: I): void {\n if (isEmptyUnits(chunk)) return\n this.append(chunk)\n if (this.settled !== undefined) return\n // The first attempt waits for a second chunk: an input that arrives in\n // one chunk (most small responses) is parsed once, by `finish`, instead\n // of once in partial mode and again in complete mode, since a repetition\n // that completes without resuming keeps no checkpoint\n if (++this.pushed === 1) return\n // An attempt re-reads what the last one could not finish, from `restart`;\n // waiting until at least half as much new input has arrived keeps the\n // total work linear in the input. Strings are also copied when they are\n // flattened, so they wait for a fraction of the whole input too.\n const added = this.length - this.attempted\n if (added < (this.attempted - this.restart) / 2) return\n if (this.kind === 0 && added < this.attempted / 8) return\n this.attempt()\n }\n\n /**\n * The step attempts run: the parser's compiled code if it was compiled\n * (the resumable build, unless `resumable` is false), else the interpreter.\n */\n private step(state: State<I>, resumable = true): unknown {\n return Stack.run(Registry.stepFor(this.parser, state, resumable) ?? this.parser.step, state)\n }\n\n private attempt(): void {\n const state = new State(this.input(), { partial: true, context: this.context })\n state.resume = this.resume\n const a = this.step(state)\n this.attempted = this.length\n if (a !== Fail) {\n this.settled = { value: a as A, pos: state.pos }\n } else if (state.mode === \"Incomplete\") {\n this.restart = state.failure.offset\n } else {\n this.settled = \"failed\"\n }\n }\n\n finish(): Effect.Effect<A, ParseError.ParseError<E>> {\n const settled = this.settled\n if (settled !== undefined && settled !== \"failed\") {\n if (settled.pos === this.length) return Effect.succeed(settled.value)\n } else if (settled === undefined) {\n // The last attempt, in complete mode, resumes from the checkpoints too;\n // with no attempt before it, it is an ordinary parse\n const state = new State(this.input(), { context: this.context })\n const resumable = this.attempted > 0\n if (resumable) state.resume = this.resume\n const a = this.step(state, resumable)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a as A)\n }\n // The error comes from an ordinary parse of the whole input, so it is the\n // same as if the input had been parsed in one go\n const all = this.input()\n const state = new State(all, { context: this.context })\n const a = Stack.run(this.parser.step, state)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a)\n if (a !== Fail) state.backtrack(\"Eof\", [\"end of input\"])\n return Effect.fail(ParseError.fromFailure<E>(all, state.reportedFailure(), state.mode, state.encoding))\n }\n}\n\n/**\n * Parses an entire stream of chunks as a single complete input.\n *\n * Parsing does not wait for the stream to end: each chunk is parsed as it\n * arrives, in partial mode, and when the parser runs out of input its\n * repetitions (`repeat`, `separated`, `fold`, `escaped`, ...) remember how\n * far they got, so that the next attempt resumes there rather than starting\n * over. A large document, such as the body of a `fetch` response, is\n * therefore parsed while it downloads, and is ready soon after its last\n * byte. Use {@link parseReadable} or {@link parseResponse} for web streams.\n *\n * The result and any `ParseError` are those of parsing the whole input at\n * once: errors are reported once the stream has ended, by an ordinary\n * interpreted parse of the whole input. A parser compiled with the\n * `Compiler` module streams compiled too (with a build that handles partial\n * input), which is several times faster. As with compiled parsers,\n * callbacks should be pure: the elements parsed before a checkpoint are\n * not parsed again, and on failure everything is parsed again.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseAll: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const empty = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n const incremental = new Incremental(parser, context as Context.Context<never>, empty)\n return Effect.flatMap(\n Stream.runForEach(self, (chunk) => Effect.sync(() => incremental.push(fromSource<I>(chunk)))),\n () => Effect.suspend(() => incremental.finish())\n )\n })\n )\n)\n\n/**\n * An error reading a `ReadableStream` given to {@link parseReadable} or\n * {@link parseResponse}.\n *\n * @since 0.1.0\n * @category errors\n */\nexport class ReadError extends /*#__PURE__*/ Data.TaggedError(\"ReadError\")<{ readonly cause: unknown }> {}\n\n/**\n * Parses a web `ReadableStream` of bytes, such as the body of a `fetch`\n * response, incrementally (see {@link parseAll}): the bytes are parsed as\n * they arrive, without waiting for the end of the stream or decoding them\n * first. Use a byte parser, e.g. one built from `Text.utf8`.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const csvLine = Parser.separated(Text.utf8.takeTill(\",\\n\"), Text.utf8.literal(\",\"))\n * const csv = Parser.separated(csvLine, Text.utf8.literal(\"\\n\"))\n *\n * const response = await fetch(\"https://example.com/data.csv\")\n * const rows = await Effect.runPromise(ParserStream.parseReadable(response.body!, csv))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseReadable: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: ReadableStream<BinaryInput>) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseAll(\n Stream.fromReadableStream({ evaluate: () => self, onError: (cause) => new ReadError({ cause }) }),\n parser,\n { empty: new Uint8Array(0) }\n )\n)\n\n/**\n * Parses the body of a `fetch` `Response` incrementally, as it downloads\n * (see {@link parseReadable}). A response without a body is parsed as empty\n * input. The status is not checked.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const lines = Parser.separated(Text.utf8.tillLineEnding, Text.utf8.lineEnding)\n *\n * const response = await fetch(\"https://example.com/log.txt\")\n * const value = await Effect.runPromise(ParserStream.parseResponse(response, lines))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseResponse: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: Response) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseReadable(self.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() }), parser)\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,UAA+B,OAAU,MAAY;CAEzD,MAAM,IAAe;CACrB,IAAI,UAAU,SAAS,CAAC,GAAG,OAAQ,IAAK;CACxC,IAAI,aAAa,YAAY;EAC3B,IAAI,EAAE,eAAe,GAAG,OAAO;EAC/B,MAAM,MAAM,IAAI,WAAW,EAAE,SAAU,EAAiB,MAAM;EAC9D,IAAI,IAAI,CAAC;EACT,IAAI,IAAI,GAAiB,EAAE,MAAM;EACjC,OAAO;CACT;CACA,OAAO,CAAC,GAAG,GAAG,GAAI,CAA4B;AAChD;AAEA,MAAM,aAAkC,OAAU,WAC/C,UAAU,SAAS,KAAK,IAAI,MAAM,MAAM,MAAM,IAAI,MAAM,MAAM,MAAM;AAEvE,MAAM,cAAc,OAAc,WAChC,WAAW,YACT,OACA,IAAI,QAAQ,QAAQ,UAAU,CAAC,GAAG,CAAC,GAAG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c,KAAK,QAAQ,IAAI,eAA2B,EAAE,QAAQ,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAClG"}
|
|
1
|
+
{"version":3,"file":"ParserStream.js","names":[],"sources":["../src/ParserStream.ts"],"sourcesContent":["/**\n * Running parsers over Effect `Stream`s of input chunks.\n *\n * This is where nom's and winnow's *partial* (streaming) parsing meets\n * Effect: chunks are buffered and the parser runs in partial mode, so a\n * value split across chunk boundaries is reported as `Incomplete` and\n * retried once more data arrives. When the stream ends, the leftover input\n * is parsed in complete mode.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n * import { Ascii, Parser, ParserStream, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const line = Parser.terminated(Ascii.decInt, Token.literal(\"\\n\"))\n *\n * const program = Stream.make(\"1\\n2\", \"3\\n\", \"4\\n\").pipe(\n * ParserStream.parseMany(line),\n * Stream.runCollect\n * )\n * // Effect.runSync(program) => [1, 23, 4]\n * ```\n *\n * @since 0.1.0\n */\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\nimport type { BinaryInput, Input, Source } from \"./Input.js\"\nimport { Fail, Failure, fromSource, State } from \"./Input.js\"\nimport * as ParseError from \"./ParseError.js\"\nimport * as Registry from \"./internal/compiler/registry.js\"\nimport type * as Resume from \"./internal/resume.js\"\nimport * as Run from \"./internal/run.js\"\nimport * as Stack from \"./internal/stack.js\"\nimport { isEmptyUnits } from \"./internal/text.js\"\nimport type { Parser } from \"./Parser.js\"\n\n/**\n * Input kinds that can be streamed in chunks.\n *\n * @since 0.1.0\n * @category models\n */\nexport type Chunkable = string | Uint8Array | ReadonlyArray<unknown>\n\nconst concat = <I extends Chunkable>(first: I, b: I): I => {\n // Widened so the checks below narrow it (a type parameter does not narrow).\n const a: Chunkable = first\n if (Predicate.isString(a)) {\n // SAFETY: both are chunks of one stream of `I`, so `b` is a string when `a` is, and so is their concatenation\n return (a + (b as string)) as I\n }\n if (a instanceof Uint8Array) {\n if (a.byteLength === 0) return b\n // SAFETY: both are chunks of one stream of `I`, so `b` is a `Uint8Array` when `a` is\n const out = new Uint8Array(a.length + (b as Uint8Array).length)\n out.set(a)\n // SAFETY: both are chunks of one stream of `I`, so `b` is a `Uint8Array` when `a` is\n out.set(b as Uint8Array, a.length)\n // SAFETY: `I` is `a`'s type, a `Uint8Array` here, and `out` is a new `Uint8Array`\n return out as I\n }\n // SAFETY: both are chunks of one stream of `I`, so `b` is an array when `a` is\n const joined: Chunkable = [...a, ...(b as ReadonlyArray<unknown>)]\n // SAFETY: `I` is `a`'s type, an array here, and `joined` is a new array of both chunks' elements\n return joined as I\n}\n\nconst sliceFrom = <I extends Chunkable>(input: I, offset: number): I =>\n // SAFETY: slicing a string, `Uint8Array` or array returns a value of the same kind\n (Predicate.isString(input) ? input.slice(offset) : input.slice(offset)) as I\n\nconst noProgress = (input: Input, offset: number) =>\n ParseError.fromFailure<never>(\n input,\n new Failure(offset, \"Assert\", [], [], false, undefined, \"`parseMany` parsers must always consume\", 0),\n \"Cut\"\n )\n\n/**\n * Options for {@link parseMany}.\n *\n * @since 0.1.0\n * @category models\n */\nexport interface ParseManyOptions<I> {\n /** The empty input, used to initialise the buffer (inferred from the first chunk if omitted). */\n readonly empty?: Source<I> | undefined\n}\n\n/**\n * Transforms a stream of input chunks into a stream of parsed values by\n * applying `parser` repeatedly. Each application must consume input.\n *\n * Services required by the parser are taken from the stream's context.\n * Error offsets are relative to the internal buffer of unconsumed input,\n * which is also the `input` of the reported `ParseError`.\n *\n * A parser compiled with the `Compiler` module runs compiled, with the\n * build that handles partial input (see `Parser.run`); a value that fails\n * is parsed again interpreted, so errors are the interpreter's. A value\n * cut short by its chunk is not: compiled code reports `Incomplete` where\n * the interpreter does.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseMany: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Stream.Stream<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Stream.suspend(() => {\n const step = parser.step\n let buffer: I | undefined = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n\n const drain = (context: any, partial: boolean): Effect.Effect<Array<A>, ParseError.ParseError<E>> => {\n const out: Array<A> = []\n if (buffer === undefined) return Effect.succeed(out)\n const input = buffer\n // One state for the whole buffer, reset before each value\n const state = new State(input)\n let offset = 0\n while (offset < input.length) {\n state.reset(offset, { partial, context })\n // A compiled `Incomplete` is the interpreter's: only an error needs the interpreted run\n const a = Run.runOn(parser, step, state, false)\n if (a === Fail) {\n if (partial && state.mode === \"Incomplete\") break\n state.reset(offset, { partial, context })\n Run.runOn(parser, step, state)\n return Effect.fail(ParseError.fromFailure<E>(input, state.reportedFailure(), state.mode, state.encoding))\n }\n if (state.pos === offset) return Effect.fail(noProgress(input, offset))\n out.push(a)\n offset = state.pos\n }\n buffer = sliceFrom(input, offset)\n return Effect.succeed(out)\n }\n\n const feed = (source: Source<I>) =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const chunk = fromSource<I>(source)\n buffer = buffer === undefined ? chunk : concat(buffer, chunk)\n return drain(context, true)\n })\n )\n\n const finish = Effect.flatMap(Effect.context<R>(), (context) => Effect.suspend(() => drain(context, false)))\n\n return self.pipe(\n Stream.mapEffect(feed),\n Stream.flattenIterable,\n Stream.concat(Stream.unwrap(Effect.map(finish, Stream.fromIterable)))\n )\n })\n)\n\n/**\n * Parses a stream of chunks incrementally, as one input. Chunks are parsed\n * as they arrive, in partial mode; when the parser runs out of input, its\n * repetitions keep checkpoints (see `internal/resume.ts`), so the next\n * attempt carries on from where the last one stopped instead of starting\n * over.\n */\nclass Incremental<A, E, I extends Chunkable> {\n private kind: 0 | 1 | 2 | undefined\n private text = \"\"\n private bytes = new Uint8Array(0)\n private items: Array<unknown> = []\n private length = 0\n private readonly resume: Resume.Checkpoints = new Map()\n /** The input length at the last attempt, and where that attempt ran out of input. */\n private attempted = 0\n private restart = 0\n private pushed = 0\n /** Set once an attempt settles: a success (with its end offset) or a definite failure. */\n private settled: { readonly value: A; readonly pos: number } | \"failed\" | undefined\n\n constructor(\n private readonly parser: Parser<A, E, any, I>,\n private readonly context: Context.Context<never>,\n empty: I | undefined\n ) {\n if (empty !== undefined) this.append(empty)\n }\n\n private append(chunk: I): void {\n if (Predicate.isString(chunk)) {\n this.kind ??= 0\n this.text += chunk\n this.length += chunk.length\n } else if (chunk instanceof Uint8Array) {\n this.kind ??= 1\n const needed = this.length + chunk.length\n if (needed > this.bytes.length) {\n // Grow geometrically, so appending costs amortized constant time per byte\n const grown = new Uint8Array(Math.max(needed, this.bytes.length * 2, 4096))\n grown.set(this.bytes.subarray(0, this.length))\n this.bytes = grown\n }\n this.bytes.set(chunk, this.length)\n this.length = needed\n } else {\n this.kind ??= 2\n for (let i = 0; i < chunk.length; i++) this.items.push(chunk[i])\n this.length = this.items.length\n }\n }\n\n private input(): I {\n if (this.kind === 1) {\n // SAFETY: `kind` 1 is set by the first chunk being a `Uint8Array`, so `I` is `Uint8Array`\n return this.bytes.subarray(0, this.length) as I\n }\n if (this.kind === 2) {\n // Items are only appended between attempts, after each state has read its `end`\n const items: Chunkable = this.items\n // SAFETY: `kind` 2 is set by the first chunk being an array, so `I` is an array of the items' type\n return items as I\n }\n // SAFETY: `kind` 0 means the first chunk was a string, so `I` is `string`; while `kind` is unset (no\n // chunk arrived) `I` is unknown and the empty string stands for the empty input\n return this.text as I\n }\n\n push(chunk: I): void {\n if (isEmptyUnits(chunk)) return\n this.append(chunk)\n if (this.settled !== undefined) return\n // The first attempt waits for a second chunk: an input that arrives in\n // one chunk (most small responses) is parsed once, by `finish`, instead\n // of once in partial mode and again in complete mode, since a repetition\n // that completes without resuming keeps no checkpoint\n if (++this.pushed === 1) return\n // An attempt re-reads what the last one could not finish, from `restart`;\n // waiting until at least half as much new input has arrived keeps the\n // total work linear in the input. Strings are also copied when they are\n // flattened, so they wait for a fraction of the whole input too.\n const added = this.length - this.attempted\n if (added < (this.attempted - this.restart) / 2) return\n if (this.kind === 0 && added < this.attempted / 8) return\n this.attempt()\n }\n\n /**\n * The step attempts run: the parser's compiled code if it was compiled\n * (the resumable build, unless `resumable` is false), else the interpreter.\n */\n private step(state: State<I>, resumable = true): A | Fail {\n // SAFETY: a compiled step (typed `any` by the compilers) returns what the parser's own step returns\n return Stack.run(Registry.stepFor(this.parser, state, resumable) ?? this.parser.step, state) as A | Fail\n }\n\n private attempt(): void {\n const state = new State(this.input(), { partial: true, context: this.context })\n state.resume = this.resume\n const a = this.step(state)\n this.attempted = this.length\n if (a !== Fail) {\n this.settled = { value: a, pos: state.pos }\n } else if (state.mode === \"Incomplete\") {\n this.restart = state.failure.offset\n } else {\n this.settled = \"failed\"\n }\n }\n\n finish(): Effect.Effect<A, ParseError.ParseError<E>> {\n const settled = this.settled\n if (settled !== undefined && settled !== \"failed\") {\n if (settled.pos === this.length) return Effect.succeed(settled.value)\n } else if (settled === undefined) {\n // The last attempt, in complete mode, resumes from the checkpoints too;\n // with no attempt before it, it is an ordinary parse\n const state = new State(this.input(), { context: this.context })\n const resumable = this.attempted > 0\n if (resumable) state.resume = this.resume\n const a = this.step(state, resumable)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a)\n }\n // The error comes from an ordinary parse of the whole input, so it is the\n // same as if the input had been parsed in one go\n const all = this.input()\n const state = new State(all, { context: this.context })\n const a = Stack.run(this.parser.step, state)\n if (a !== Fail && state.pos === state.end) return Effect.succeed(a)\n if (a !== Fail) state.backtrack(\"Eof\", [\"end of input\"])\n return Effect.fail(ParseError.fromFailure<E>(all, state.reportedFailure(), state.mode, state.encoding))\n }\n}\n\n/**\n * Parses an entire stream of chunks as a single complete input.\n *\n * Parsing does not wait for the stream to end: each chunk is parsed as it\n * arrives, in partial mode, and when the parser runs out of input its\n * repetitions (`repeat`, `separated`, `fold`, `escaped`, ...) remember how\n * far they got, so that the next attempt resumes there rather than starting\n * over. A large document, such as the body of a `fetch` response, is\n * therefore parsed while it downloads, and is ready soon after its last\n * byte. Use {@link parseReadable} or {@link parseResponse} for web streams.\n *\n * The result and any `ParseError` are those of parsing the whole input at\n * once: errors are reported once the stream has ended, by an ordinary\n * interpreted parse of the whole input. A parser compiled with the\n * `Compiler` module streams compiled too (with a build that handles partial\n * input), which is several times faster. As with compiled parsers,\n * callbacks should be pure: the elements parsed before a checkpoint are\n * not parsed again, and on failure everything is parsed again.\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseAll: {\n <A, E, R, I extends Chunkable>(\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): <E0, R0>(self: Stream.Stream<Source<I>, E0, R0>) => Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<NoInfer<I>>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R>\n} = /*#__PURE__*/ dual(\n (args) => Stream.isStream(args[0]),\n <I extends Chunkable, E0, R0, A, E, R>(\n self: Stream.Stream<Source<I>, E0, R0>,\n parser: Parser<A, E, R, I>,\n options?: ParseManyOptions<I>\n ): Effect.Effect<A, E0 | ParseError.ParseError<E>, R0 | R> =>\n Effect.flatMap(Effect.context<R>(), (context) =>\n Effect.suspend(() => {\n const empty = options?.empty === undefined ? undefined : fromSource<I>(options.empty)\n const incremental = new Incremental(parser, context, empty)\n return Effect.flatMap(\n Stream.runForEach(self, (chunk) => Effect.sync(() => incremental.push(fromSource<I>(chunk)))),\n () => Effect.suspend(() => incremental.finish())\n )\n })\n )\n)\n\n/**\n * An error reading a `ReadableStream` given to {@link parseReadable} or\n * {@link parseResponse}.\n *\n * @since 0.1.0\n * @category errors\n */\nexport class ReadError extends /*#__PURE__*/ Data.TaggedError(\"ReadError\")<{ readonly cause: unknown }> {}\n\n/**\n * Parses a web `ReadableStream` of bytes, such as the body of a `fetch`\n * response, incrementally (see {@link parseAll}): the bytes are parsed as\n * they arrive, without waiting for the end of the stream or decoding them\n * first. Use a byte parser, e.g. one built from `Text.utf8`.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const csvLine = Parser.separated(Text.utf8.takeTill(\",\\n\"), Text.utf8.literal(\",\"))\n * const csv = Parser.separated(csvLine, Text.utf8.literal(\"\\n\"))\n *\n * const response = await fetch(\"https://example.com/data.csv\")\n * const rows = await Effect.runPromise(ParserStream.parseReadable(response.body!, csv))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseReadable: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: ReadableStream<BinaryInput>) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: ReadableStream<BinaryInput>,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseAll(\n Stream.fromReadableStream({ evaluate: () => self, onError: (cause) => new ReadError({ cause }) }),\n parser,\n { empty: new Uint8Array(0) }\n )\n)\n\n/**\n * Parses the body of a `fetch` `Response` incrementally, as it downloads\n * (see {@link parseReadable}). A response without a body is parsed as empty\n * input. The status is not checked.\n *\n * @example\n * ```ts\n * import { Effect } from \"effect\"\n * import { Parser, ParserStream, Text } from \"@thomasfosterau/effect-parse\"\n *\n * const lines = Parser.separated(Text.utf8.tillLineEnding, Text.utf8.lineEnding)\n *\n * const response = await fetch(\"https://example.com/log.txt\")\n * const value = await Effect.runPromise(ParserStream.parseResponse(response, lines))\n * ```\n *\n * @since 0.1.0\n * @category combinators\n */\nexport const parseResponse: {\n <A, E, R>(\n parser: Parser<A, E, R, Uint8Array>\n ): (self: Response) => Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R>(\n self: Response,\n parser: Parser<A, E, R, Uint8Array>\n ): Effect.Effect<A, ParseError.ParseError<E> | ReadError, R> =>\n parseReadable(self.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() }), parser)\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,UAA+B,OAAU,MAAY;CAEzD,MAAM,IAAe;CACrB,IAAI,UAAU,SAAS,CAAC,GAEtB,OAAQ,IAAK;CAEf,IAAI,aAAa,YAAY;EAC3B,IAAI,EAAE,eAAe,GAAG,OAAO;EAE/B,MAAM,MAAM,IAAI,WAAW,EAAE,SAAU,EAAiB,MAAM;EAC9D,IAAI,IAAI,CAAC;EAET,IAAI,IAAI,GAAiB,EAAE,MAAM;EAEjC,OAAO;CACT;CAIA,OAAO,CAFoB,GAAG,GAAG,GAAI,CAEzB;AACd;AAEA,MAAM,aAAkC,OAAU,WAE/C,UAAU,SAAS,KAAK,IAAI,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A,WAEA,SACE,OAAO,mBAAmB;CAAE,gBAAgB;CAAM,UAAU,UAAU,IAAI,UAAU,EAAE,MAAM,CAAC;AAAE,CAAC,GAChG,QACA,EAAE,uBAAO,IAAI,WAAW,CAAC,EAAE,CAC7B,CACJ;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAQK,mBAChB,IAEE,MACA,WAEA,cAAc,KAAK,QAAQ,IAAI,eAA2B,EAAE,QAAQ,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAClG"}
|
package/dist/Syntax.d.ts
CHANGED
|
@@ -193,6 +193,17 @@ export declare class Tree<out A, out E = never, I extends Input = string> {
|
|
|
193
193
|
/** @internal */
|
|
194
194
|
toError(error: ErrorInfo, start: number): ParseError.ParseError<E>;
|
|
195
195
|
}
|
|
196
|
+
/**
|
|
197
|
+
* What `JSON.stringify` writes for a {@link SyntaxNode}: its kind and span.
|
|
198
|
+
*
|
|
199
|
+
* @since 0.5.0
|
|
200
|
+
* @category models
|
|
201
|
+
*/
|
|
202
|
+
export interface SyntaxNodeJson {
|
|
203
|
+
readonly kind: string;
|
|
204
|
+
readonly start: number;
|
|
205
|
+
readonly end: number;
|
|
206
|
+
}
|
|
196
207
|
/**
|
|
197
208
|
* A node of a syntax tree: its kind, span and value, and its place in the
|
|
198
209
|
* tree. Nodes are views built on demand; two views of the same node are
|
|
@@ -295,7 +306,7 @@ export declare class SyntaxNode<I extends Input = string> {
|
|
|
295
306
|
* names, as Tree-sitter prints it: `(pair key: (name) value: (number))`.
|
|
296
307
|
*/
|
|
297
308
|
toString(): string;
|
|
298
|
-
toJSON():
|
|
309
|
+
toJSON(): SyntaxNodeJson;
|
|
299
310
|
private makeChild;
|
|
300
311
|
}
|
|
301
312
|
/**
|
|
@@ -332,6 +343,16 @@ export declare class TreeCursor<I extends Input = string> {
|
|
|
332
343
|
reset(node: SyntaxNode<I>): void;
|
|
333
344
|
private goto;
|
|
334
345
|
}
|
|
346
|
+
/**
|
|
347
|
+
* The overloads of {@link parse}.
|
|
348
|
+
*
|
|
349
|
+
* @since 0.5.0
|
|
350
|
+
* @category parsing
|
|
351
|
+
*/
|
|
352
|
+
export interface ParseFn {
|
|
353
|
+
<A, E, I extends Input>(grammar: Parser<A, E, never, I>, input: NoInfer<Source<I>>, options?: ParseOptions): Tree<A, E, I>;
|
|
354
|
+
<A, E, R, I extends Input>(grammar: Parser<A, E, R, I>, input: NoInfer<Source<I>>, options: ParseOptionsWithContext<R>): Tree<A, E, I>;
|
|
355
|
+
}
|
|
335
356
|
/**
|
|
336
357
|
* Parses an input into a syntax {@link Tree}. The grammar's output is the
|
|
337
358
|
* tree's `value`, and its {@link node}s are the tree's nodes. When the
|
|
@@ -345,10 +366,7 @@ export declare class TreeCursor<I extends Input = string> {
|
|
|
345
366
|
* @since 0.2.0
|
|
346
367
|
* @category parsing
|
|
347
368
|
*/
|
|
348
|
-
export declare const parse:
|
|
349
|
-
<A, E, I extends Input>(grammar: Parser<A, E, never, I>, input: NoInfer<Source<I>>, options?: ParseOptions): Tree<A, E, I>;
|
|
350
|
-
<A, E, R, I extends Input>(grammar: Parser<A, E, R, I>, input: NoInfer<Source<I>>, options: ParseOptionsWithContext<R>): Tree<A, E, I>;
|
|
351
|
-
};
|
|
369
|
+
export declare const parse: ParseFn;
|
|
352
370
|
/**
|
|
353
371
|
* Parses the new version of a tree's input, reusing the nodes of the tree
|
|
354
372
|
* that the edits leave unchanged (Tree-sitter's `ts_tree_edit` followed by
|
package/dist/Syntax.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Syntax.d.ts","names":[],"sources":["../src/Syntax.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"Syntax.d.ts","names":[],"sources":["../src/Syntax.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;qBAwGa;GACV,gBAAgB,GAAG,GAAG,GAAG,UAAU,OAAO,MAAM,OAAO,GAAG,GAAG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O,GAAG,GAAG,GAAG,IACzB,OAAO,QAAQ,OAAO,KACtB,SAAS,wBAAwB,KAChC,KAAK,GAAG,GAAG;;;;;;;;;;;;;;;qBAgBH,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8CP,UAAW,GAAG,GAAG,UAAU,OACtC,MAAM,KAAK,GAAG,GAAG,IACjB,OAAO,QAAQ,OAAO,KACtB,QAAQ,OAAO,cAAc,UAC5B,KAAK,GAAG,GAAG;;;;;;;;qBAsBD,UAAW,GAAG,GACzB,MAAM,KAAK,GAAG,YACd,eACA,aACA,iBACC,KAAK,GAAG;;;;;;;;qBAmBE,OAAQ,UAAU,OAAO,QAAQ,GAAG,OAAO,MAAI"}
|
package/dist/Syntax.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Syntax.js","names":[],"sources":["../src/Syntax.ts"],"sourcesContent":["/**\n * Concrete syntax trees and incremental parsing, in the spirit of\n * [Tree-sitter](https://tree-sitter.github.io).\n *\n * Mark the rules of a grammar that should appear in the tree with\n * {@link node} (and, optionally, {@link token} and {@link field}). Outside\n * this module the marks change nothing: `Parser.parse` returns the same\n * values, and compiled parsers compile them away. {@link parse} runs the\n * grammar and returns a {@link Tree}: a tree of {@link SyntaxNode}s with\n * spans, parents and siblings, to search by position (`descendantAt`) or walk\n * with a {@link TreeCursor}. Each node also carries the value its parser\n * returned.\n *\n * Like Tree-sitter, a syntax parse always produces a tree. Failures handled\n * by `Parser.resumeAfter` and `Parser.retryAfter` become `ERROR` nodes over\n * the input they skipped, and so does any input after a fatal failure.\n *\n * After an edit, {@link reparse} (or {@link replace}) parses the new input\n * reusing every node of the old tree whose input is unchanged: only the\n * nodes that enclose the edit, or looked at the edited input, are parsed\n * again, and each reused node is stepped over whole.\n *\n * @example\n * ```ts\n * import { Ascii, Parser, Syntax, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const ws = Ascii.multispace0\n * const number = Syntax.node(Ascii.decInt, \"number\")\n * const list = Syntax.node(\n * Parser.delimited(\n * Token.literal(\"[\"),\n * Parser.separated(Parser.delimited(ws, number, ws), Token.literal(\",\")),\n * Token.literal(\"]\")\n * ),\n * \"list\"\n * )\n *\n * const tree = Syntax.parse(list, \"[1, 2, 3]\")\n * String(tree.root) // \"(list (number) (number) (number))\"\n * tree.root.descendantAt(4)?.text // \"2\"\n *\n * const edited = Syntax.replace(tree, 4, 5, \"20\") // \"[1, 20, 3]\"\n * edited.root.namedChild(1)?.value // 20\n * edited.reused // 2: only \"20\" was parsed again\n * ```\n *\n * @since 0.2.0\n */\nimport * as Str from \"effect/String\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Context from \"effect/Context\"\nimport { dual } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport type { Input, Slice, Source } from \"./Input.js\"\nimport { Fail, fromSource, State } from \"./Input.js\"\nimport * as ParseError from \"./ParseError.js\"\nimport { nodeOf } from \"./internal/node.js\"\nimport { Key } from \"./internal/key.js\"\nimport * as Stack from \"./internal/stack.js\"\nimport type { ErrorInfo, Green, Previous, Segment } from \"./internal/syntax.js\"\nimport { absolute, errorKind, SyntaxBuilder } from \"./internal/syntax.js\"\nimport type { Parser } from \"./Parser.js\"\nimport { described, isParser } from \"./Parser.js\"\n\n// -----------------------------------------------------------------------------\n// Grammar annotations\n// -----------------------------------------------------------------------------\n\nconst syntaxNode = (self: Parser.Any, kind: string, named: boolean): Parser.Any => {\n const step = self.step\n // Identifies the nodes this parser builds, so a reparse can reuse them\n const key = new Key()\n return described<unknown, unknown, unknown, Input>(\n (state) => {\n const builder = state.syntax\n return builder === undefined ? step(state) : builder.node(state, step, key, kind, named)\n },\n self.name,\n { _tag: \"Syntax\", self, kind, named }\n )\n}\n\n/**\n * Marks a parser as a rule of the syntax tree: in a {@link parse}, each\n * match becomes a named node of the given kind, spanning the input it\n * consumed, with the nodes built inside it as children and its output as\n * its `value`. Outside {@link parse}, the parser is unchanged.\n *\n * A match that consumes nothing adds no node (as in Tree-sitter, where rules\n * can't match the empty string).\n *\n * For {@link reparse} to reuse a node, its parser's output must depend only\n * on the input from where the node starts: not on services, on state kept\n * in closures, or on absolute offsets (`Parser.location`, `Parser.span`),\n * which are not updated when the node moves. Use the node's `start` and\n * `end` instead.\n *\n * @since 0.2.0\n * @category annotations\n */\nexport const node: {\n (kind: string): <A, E, R, I extends Input>(self: Parser<A, E, R, I>) => Parser<A, E, R, I>\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind: string): Parser<A, E, R, I>\n} = /*#__PURE__*/ dual(\n 2,\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind: string): Parser<A, E, R, I> =>\n syntaxNode(self, kind, true) as Parser<A, E, R, I>\n)\n\n/**\n * Like {@link node}, but builds an *anonymous* node, Tree-sitter's name for\n * punctuation and keywords: anonymous nodes are left out of\n * `namedChildren` and of the tree's printed form. The kind defaults to the\n * literal for a `Token.literal` of a string, and to the parser's name\n * otherwise.\n *\n * @example\n * ```ts\n * import { Syntax, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const comma = Syntax.token(Token.literal(\",\")) // kind \",\"\n * ```\n *\n * @since 0.2.0\n * @category annotations\n */\nexport const token: {\n (kind?: string): <A, E, R, I extends Input>(self: Parser<A, E, R, I>) => Parser<A, E, R, I>\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind?: string): Parser<A, E, R, I>\n} = /*#__PURE__*/ dual(\n (args) => isParser(args[0]),\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind?: string): Parser<A, E, R, I> =>\n syntaxNode(self, kind ?? defaultTokenKind(self), false) as Parser<A, E, R, I>\n)\n\nconst defaultTokenKind = (self: Parser.Any): string => {\n const n = nodeOf(self)\n if (Predicate.isTagged(n, \"Literal\") && Predicate.isString(n.literal) && !n.caseless) return n.literal\n return self.name ?? \"token\"\n}\n\n/**\n * Gives the nodes built by a parser a field name in their parent, like\n * Tree-sitter's `field(name, rule)`: find them with `childByField` and\n * `childrenByField`. Outside {@link parse}, the parser is unchanged.\n *\n * @example\n * ```ts\n * import { Ascii, Parser, Syntax, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const name = Syntax.node(Ascii.alpha1, \"name\")\n * const number = Syntax.node(Ascii.decInt, \"number\")\n * const pair = Syntax.node(\n * Parser.separatedPair(Syntax.field(name, \"key\"), Token.literal(\"=\"), Syntax.field(number, \"value\")),\n * \"pair\"\n * )\n * Syntax.parse(pair, \"x=1\").root.childByField(\"value\")?.value // 1\n * ```\n *\n * @since 0.2.0\n * @category annotations\n */\nexport const field: {\n (name: string): <A, E, R, I extends Input>(self: Parser<A, E, R, I>) => Parser<A, E, R, I>\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, name: string): Parser<A, E, R, I>\n} = /*#__PURE__*/ dual(2, <A, E, R, I extends Input>(self: Parser<A, E, R, I>, name: string): Parser<A, E, R, I> => {\n const step = self.step\n return described<A, E, R, I>(\n (state) => {\n const builder = state.syntax\n return (builder === undefined ? step(state) : builder.field(state, step, name)) as A | typeof Fail\n },\n self.name,\n { _tag: \"Syntax\", self, kind: undefined, named: false }\n )\n})\n\n// -----------------------------------------------------------------------------\n// Trees\n// -----------------------------------------------------------------------------\n\n/**\n * The kind of the nodes that stand for input that could not be parsed.\n *\n * @since 0.2.0\n * @category models\n */\nexport const ERROR: \"ERROR\" = errorKind\n\n/**\n * An edit to an input, as Tree-sitter's `TSInputEdit`: the input\n * `[start, oldEnd)` was replaced by `[start, newEnd)`. Offsets are in the\n * input's units (UTF-16 code units for strings, bytes, elements).\n *\n * @since 0.2.0\n * @category models\n */\nexport interface Edit {\n readonly start: number\n readonly oldEnd: number\n readonly newEnd: number\n}\n\n/**\n * Options for {@link parse}.\n *\n * @since 0.2.0\n * @category models\n */\nexport interface ParseOptions {\n /**\n * The kind of the root node, when the grammar itself is not a\n * {@link node}. Defaults to `\"document\"`.\n */\n readonly kind?: string | undefined\n /**\n * For {@link reparse}: how many input units custom parsers may read past\n * the furthest position they move the cursor to or record a failure at,\n * besides one token there. Defaults to 0, which is right for the built-in\n * parsers, and for custom parsers (`Parser.make`) that only read past\n * where they stop to see that the token there doesn't match.\n *\n * A node is reused only when the input its parse looked at is unchanged.\n * Built-in parsers that read further, such as a literal that fails part\n * way or `Token.takeUntil`, record how far they read.\n */\n readonly lookahead?: number | undefined\n}\n\n/**\n * Options for {@link parse} with a parser that requires services.\n *\n * @since 0.2.0\n * @category models\n */\nexport interface ParseOptionsWithContext<R> extends ParseOptions {\n readonly context: Context.Context<R>\n}\n\ninterface Config {\n readonly kind: string\n readonly inner: Parser.Any\n readonly lookahead: number\n readonly context: Context.Context<never> | undefined\n}\n\n/**\n * The result of a {@link parse}: a syntax tree over the whole input, the\n * grammar's output, and the errors met on the way.\n *\n * @since 0.2.0\n * @category models\n */\nexport class Tree<out A, out E = never, I extends Input = string> {\n /** The root node. It always spans the whole input. */\n readonly root: SyntaxNode<I>\n private lines: Array<number> | undefined\n private errorList: ReadonlyArray<ParseError.ParseError<E>> | undefined\n\n /** @internal */\n constructor(\n /** The input the tree was parsed from. */\n readonly input: I,\n /** The grammar's output: `none` when the parse failed. */\n readonly value: Option.Option<A>,\n /** How many nodes were reused from the previous tree by {@link reparse}. */\n readonly reused: number,\n /** @internal */\n readonly green: Green,\n /** @internal */\n readonly config: Config,\n /** @internal */\n readonly encoding: ParseError.ParseError<never>[\"encoding\"]\n ) {\n this.root = new SyntaxNode(this, green, 0, undefined, 0)\n }\n\n /**\n * Every error of the parse, in input order: the failures recovered by\n * `Parser.resumeAfter` and `Parser.retryAfter`, then the fatal one, if\n * the parse failed. Each one belongs to an `ERROR` node.\n */\n get errors(): ReadonlyArray<ParseError.ParseError<E>> {\n if (this.errorList === undefined) {\n const out: Array<ParseError.ParseError<E>> = []\n const visit = (green: Green, start: number) => {\n if (!green.hasError) return\n if (green.error !== undefined) out.push(this.toError(green.error, start))\n for (let i = 0; i < green.children.length; i++) visit(green.children[i], start + green.offsets[i])\n }\n visit(this.green, 0)\n this.errorList = out\n }\n return this.errorList\n }\n\n /** Whether the tree has any `ERROR` node. */\n get hasErrors(): boolean {\n return this.green.hasError\n }\n\n /** The smallest node containing `[start, end)` (see {@link SyntaxNode.descendantAt}). */\n descendantAt(start: number, end?: number): SyntaxNode<I> {\n return this.root.descendantAt(start, end)\n }\n\n /** A cursor at the root. */\n walk(): TreeCursor<I> {\n return new TreeCursor(this.root)\n }\n\n /**\n * The 1-based line and column (in code points) of an offset, as in\n * `ParseError`. Lines of a string input are indexed once, so lookups take\n * logarithmic time.\n */\n lineColumn(offset: number): ParseError.LineColumn {\n const input = this.input\n if (!Predicate.isString(input)) return ParseError.lineColumn(input, offset, this.encoding)\n let lines = this.lines\n if (lines === undefined) {\n lines = [0]\n for (let i = input.indexOf(\"\\n\"); i >= 0; i = input.indexOf(\"\\n\", i + 1)) lines.push(i + 1)\n this.lines = lines\n }\n const at = Math.max(0, Math.min(offset, input.length))\n let lo = 0\n let hi = lines.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (lines[mid] <= at) lo = mid\n else hi = mid - 1\n }\n const lineStart = lines[lo]\n return { line: lo + 1, column: ParseError.lineColumn(input.slice(lineStart, at), at - lineStart).column }\n }\n\n /** The root's S-expression (see {@link SyntaxNode.toString}). */\n toString(): string {\n return this.root.toString()\n }\n\n /** @internal */\n toError(error: ErrorInfo, start: number): ParseError.ParseError<E> {\n return ParseError.fromFailure<E>(this.input, absolute(error.failure, start), error.mode, this.encoding)\n }\n}\n\n/**\n * A node of a syntax tree: its kind, span and value, and its place in the\n * tree. Nodes are views built on demand; two views of the same node are\n * different objects but have the same `start`, `end` and `kind`.\n *\n * @since 0.2.0\n * @category models\n */\nexport class SyntaxNode<I extends Input = string> {\n private childList: ReadonlyArray<SyntaxNode<I>> | undefined\n\n /** @internal */\n constructor(\n /** The tree this node belongs to. */\n readonly tree: Tree<unknown, unknown, I>,\n /** @internal */\n readonly green: Green,\n /** The offset where the node starts. */\n readonly start: number,\n /** The parent node; `undefined` for the root. */\n readonly parent: SyntaxNode<I> | undefined,\n /** The node's index among its parent's children. */\n readonly index: number\n ) {}\n\n /** The node's kind: the name given to {@link node} or {@link token}, or `\"ERROR\"`. */\n get kind(): string {\n return this.green.kind\n }\n\n /** `false` for the anonymous nodes built by {@link token}. */\n get named(): boolean {\n return this.green.named\n }\n\n /** The field name given by {@link field}, if any. */\n get field(): string | undefined {\n return this.parent?.green.fields?.[this.index]\n }\n\n /** The offset where the node ends (exclusive). */\n get end(): number {\n return this.start + this.green.width\n }\n\n /** The number of input units the node spans. */\n get length(): number {\n return this.green.width\n }\n\n /** The output of the node's parser (`undefined` for `ERROR` nodes, and for a root that failed). */\n get value(): unknown {\n return this.green.value\n }\n\n /** The input the node spans. */\n get text(): Slice<I> {\n const input = this.tree.input as any\n return input instanceof Uint8Array\n ? (input.subarray(this.start, this.end) as any)\n : input.slice(this.start, this.end)\n }\n\n /** Whether this is an `ERROR` node. */\n get isError(): boolean {\n return this.green.error !== undefined\n }\n\n /** Whether this node or a descendant is an `ERROR` node. */\n get hasError(): boolean {\n return this.green.hasError\n }\n\n /** For an `ERROR` node, the error it stands for. */\n get error(): ParseError.ParseError<unknown> | undefined {\n const error = this.green.error\n return error === undefined ? undefined : this.tree.toError(error, this.start)\n }\n\n /** The child nodes, named and anonymous, in input order. */\n get children(): ReadonlyArray<SyntaxNode<I>> {\n if (this.childList === undefined) {\n const green = this.green\n const out = new Array<SyntaxNode<I>>(green.children.length)\n for (let i = 0; i < out.length; i++) out[i] = this.makeChild(i)\n this.childList = out\n }\n return this.childList\n }\n\n /** The number of children. */\n get childCount(): number {\n return this.green.children.length\n }\n\n /** The child at `index` (negative indices count from the end). */\n child(index: number): SyntaxNode<I> | undefined {\n const n = this.green.children.length\n const i = index < 0 ? n + index : index\n return i >= 0 && i < n ? this.children[i] : undefined\n }\n\n /** The named children. */\n get namedChildren(): ReadonlyArray<SyntaxNode<I>> {\n return this.children.filter((c) => c.named)\n }\n\n /** The named child at `index`. */\n namedChild(index: number): SyntaxNode<I> | undefined {\n return this.namedChildren[index]\n }\n\n /** The first child with the given field name. */\n childByField(name: string): SyntaxNode<I> | undefined {\n const fields = this.green.fields\n if (fields === undefined) return undefined\n const i = fields.indexOf(name)\n return i < 0 ? undefined : this.children[i]\n }\n\n /** The children with the given field name. */\n childrenByField(name: string): ReadonlyArray<SyntaxNode<I>> {\n const fields = this.green.fields\n if (fields === undefined) return []\n return this.children.filter((_, i) => fields[i] === name)\n }\n\n /** The next sibling, named or anonymous. */\n get nextSibling(): SyntaxNode<I> | undefined {\n return this.parent?.children[this.index + 1]\n }\n\n /** The previous sibling, named or anonymous. */\n get previousSibling(): SyntaxNode<I> | undefined {\n return this.index > 0 ? this.parent?.children[this.index - 1] : undefined\n }\n\n /** The next named sibling. */\n get nextNamedSibling(): SyntaxNode<I> | undefined {\n const siblings = this.parent?.children\n if (siblings === undefined) return undefined\n for (let i = this.index + 1; i < siblings.length; i++) if (siblings[i].named) return siblings[i]\n return undefined\n }\n\n /** The previous named sibling. */\n get previousNamedSibling(): SyntaxNode<I> | undefined {\n const siblings = this.parent?.children\n if (siblings === undefined) return undefined\n for (let i = this.index - 1; i >= 0; i--) if (siblings[i].named) return siblings[i]\n return undefined\n }\n\n /**\n * The index of the child containing the input unit at `offset`, or -1.\n * Takes logarithmic time.\n */\n childIndexAt(offset: number): number {\n const green = this.green\n const offsets = green.offsets\n const rel = offset - this.start\n let lo = 0\n let hi = offsets.length - 1\n let found = -1\n while (lo <= hi) {\n const mid = (lo + hi) >> 1\n if (offsets[mid] <= rel) {\n found = mid\n lo = mid + 1\n } else {\n hi = mid - 1\n }\n }\n // Skip back over empty `ERROR` nodes at `offset`\n while (found >= 0 && green.children[found].width === 0 && offsets[found] === rel) found--\n return found >= 0 && rel < offsets[found] + green.children[found].width ? found : -1\n }\n\n /** The child containing the input unit at `offset`. */\n childAt(offset: number): SyntaxNode<I> | undefined {\n const i = this.childIndexAt(offset)\n return i < 0 ? undefined : this.children[i]\n }\n\n /**\n * The smallest node, this one or a descendant, that contains\n * `[start, end)` (Tree-sitter's `descendant_for_byte_range`). With only\n * `start`, the deepest node containing the input unit at `start`. Takes\n * time proportional to the depth of the tree times the logarithm of the\n * number of children.\n */\n descendantAt(start: number, end: number = start + 1): SyntaxNode<I> {\n return descendantOf(this, start, end)\n }\n\n /** Like {@link descendantAt}, but only stops at named nodes. */\n namedDescendantAt(start: number, end: number = start + 1): SyntaxNode<I> {\n let node: SyntaxNode<I> = this.descendantAt(start, end)\n // Every node below `this` has a parent, so the walk stops at `this` at the latest\n while (!node.named && node !== this) node = node.parent ?? this\n return node\n }\n\n /** This node and its descendants, in pre-order. */\n *descendants(): Generator<SyntaxNode<I>, void, undefined> {\n const cursor = this.walk()\n while (true) {\n yield cursor.node\n if (cursor.gotoFirstChild()) continue\n while (!cursor.gotoNextSibling()) {\n if (!cursor.gotoParent()) return\n }\n }\n }\n\n /** The descendants of the given kind, in pre-order. */\n *descendantsOfKind(kind: string): Generator<SyntaxNode<I>, void, undefined> {\n for (const n of this.descendants()) if (n.kind === kind) yield n\n }\n\n /** A cursor at this node, which cannot move above it. */\n walk(): TreeCursor<I> {\n return new TreeCursor(this)\n }\n\n /**\n * The node as an S-expression of its named descendants, with field\n * names, as Tree-sitter prints it: `(pair key: (name) value: (number))`.\n */\n toString(): string {\n let out = \"\"\n const visit = (green: Green, field: string | undefined) => {\n if (green.named || green === this.green) {\n if (Str.isNonEmpty(out)) out += \" \"\n if (field !== undefined) out += `${field}: `\n out += `(${green.kind}`\n for (let i = 0; i < green.children.length; i++) visit(green.children[i], green.fields?.[i])\n out += \")\"\n } else {\n for (let i = 0; i < green.children.length; i++) visit(green.children[i], green.fields?.[i])\n }\n }\n visit(this.green, this.field)\n return out\n }\n\n toJSON(): unknown {\n return { kind: this.kind, start: this.start, end: this.end }\n }\n\n private makeChild(i: number): SyntaxNode<I> {\n const green = this.green\n return new SyntaxNode(this.tree, green.children[i], this.start + green.offsets[i], this, i)\n }\n}\n\n/** The smallest node, `root` or a descendant, that contains `[start, end)` (see `SyntaxNode.descendantAt`). */\nconst descendantOf = <I extends Input>(root: SyntaxNode<I>, start: number, end: number): SyntaxNode<I> => {\n let node = root\n while (true) {\n const i = node.childIndexAt(start)\n if (i < 0) return node\n const child = node.children[i]\n if (end > child.end) return node\n node = child\n }\n}\n\n/**\n * A cursor for walking a tree, as Tree-sitter's `TreeCursor`. It starts at\n * a node and cannot move above it.\n *\n * @since 0.2.0\n * @category models\n */\nexport class TreeCursor<I extends Input = string> {\n private current: SyntaxNode<I>\n private depth = 0\n\n /** @internal */\n constructor(node: SyntaxNode<I>) {\n this.current = node\n }\n\n /** The node at the cursor. */\n get node(): SyntaxNode<I> {\n return this.current\n }\n\n /** The field name of the node at the cursor, if any. */\n get field(): string | undefined {\n return this.depth === 0 ? undefined : this.current.field\n }\n\n /** Moves to the first child; `false` if there is none. */\n gotoFirstChild(): boolean {\n return this.goto(this.current.child(0))\n }\n\n /** Moves to the last child; `false` if there is none. */\n gotoLastChild(): boolean {\n return this.goto(this.current.child(-1))\n }\n\n /** Moves to the child containing the input unit at `offset`; `false` if there is none. */\n gotoFirstChildForOffset(offset: number): boolean {\n return this.goto(this.current.childAt(offset))\n }\n\n /** Moves to the next sibling; `false` if there is none. */\n gotoNextSibling(): boolean {\n if (this.depth === 0) return false\n const next = this.current.nextSibling\n if (next === undefined) return false\n this.current = next\n return true\n }\n\n /** Moves to the previous sibling; `false` if there is none. */\n gotoPreviousSibling(): boolean {\n if (this.depth === 0) return false\n const previous = this.current.previousSibling\n if (previous === undefined) return false\n this.current = previous\n return true\n }\n\n /** Moves to the parent; `false` at the node the cursor started at. */\n gotoParent(): boolean {\n const parent = this.current.parent\n if (this.depth === 0 || parent === undefined) return false\n this.current = parent\n this.depth--\n return true\n }\n\n /** Moves to the deepest node containing the input unit at `offset`. */\n gotoDescendantAt(offset: number): void {\n while (this.gotoFirstChildForOffset(offset)) {\n // descend\n }\n }\n\n /** Starts again at `node`. */\n reset(node: SyntaxNode<I>): void {\n this.current = node\n this.depth = 0\n }\n\n private goto(node: SyntaxNode<I> | undefined): boolean {\n if (node === undefined) return false\n this.current = node\n this.depth++\n return true\n }\n}\n\n// -----------------------------------------------------------------------------\n// Parsing\n// -----------------------------------------------------------------------------\n\nconst expectedEof = [\"end of input\"]\n\nconst run = <A, E, I extends Input>(config: Config, input: I, previous: Previous | undefined): Tree<A, E, I> => {\n const state = new State<I>(input, { context: config.context })\n const builder = new SyntaxBuilder(state, previous)\n const a = Stack.run(config.inner.step, state)\n // Text parsers record the encoding when they fail, which they may have done inside reused nodes\n if (state.encoding === undefined && previous !== undefined) state.encoding = previous.encoding\n let fatal: ErrorInfo | undefined\n let value: Option.Option<A> = Option.none()\n if (a === Fail) {\n fatal = { failure: state.reportedFailure(), mode: state.mode }\n } else if (state.pos < state.end) {\n state.backtrack(\"Eof\", expectedEof)\n fatal = { failure: state.reportedFailure(), mode: \"Backtrack\" }\n } else {\n value = Option.some(a as A)\n }\n const green = builder.finish(config.kind, Option.getOrUndefined(value), fatal, state.pos)\n return new Tree<A, E, I>(input, value, builder.reused, green, config, state.encoding)\n}\n\n/**\n * Parses an input into a syntax {@link Tree}. The grammar's output is the\n * tree's `value`, and its {@link node}s are the tree's nodes. When the\n * grammar is itself a {@link node}, that node is the root; otherwise the\n * root is a node of kind `options.kind` (by default `\"document\"`).\n *\n * The parse never fails: recovered failures (see `Parser.resumeAfter`), a\n * fatal failure and unparsed input at the end all become `ERROR` nodes, and\n * are listed in `tree.errors`. The parse is interpreted, never compiled.\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const parse: {\n <A, E, I extends Input>(\n grammar: Parser<A, E, never, I>,\n input: NoInfer<Source<I>>,\n options?: ParseOptions\n ): Tree<A, E, I>\n <A, E, R, I extends Input>(\n grammar: Parser<A, E, R, I>,\n input: NoInfer<Source<I>>,\n options: ParseOptionsWithContext<R>\n ): Tree<A, E, I>\n} = <A, E, R, I extends Input>(\n grammar: Parser<A, E, R, I>,\n input: I | Source<I>,\n options?: ParseOptions & { readonly context?: Context.Context<R> }\n): Tree<A, E, I> => {\n const n = nodeOf(grammar)\n const isRoot = Predicate.isTagged(n, \"Syntax\") && n.kind !== undefined && n.named\n const config: Config = {\n kind: isRoot ? n.kind : (options?.kind ?? \"document\"),\n inner: isRoot ? (n.self as Parser.Any) : grammar,\n lookahead: options?.lookahead ?? 0,\n context: options?.context as Context.Context<never> | undefined\n }\n return run(config, fromSource(input as Input) as I, undefined)\n}\n\n/**\n * Parses the new version of a tree's input, reusing the nodes of the tree\n * that the edits leave unchanged (Tree-sitter's `ts_tree_edit` followed by\n * `ts_parser_parse` with the old tree). The result is the tree a fresh\n * {@link parse} of `input` would build, but only the parts of the tree\n * around the edits are parsed again. `tree.reused` says how many nodes were\n * reused.\n *\n * `edits` describe how the old input became the new one, applied in order,\n * each in the coordinates of the input as the previous edits left it. When\n * they are omitted, the edit is found by comparing the inputs (their common\n * prefix and suffix), which takes time linear in their length but much less\n * than parsing.\n *\n * Errors in the new tree are those a fresh parse reports, except that an\n * error just after a reused node may list fewer expected alternatives.\n *\n * @example\n * ```ts\n * import { Ascii, Syntax } from \"@thomasfosterau/effect-parse\"\n *\n * const number = Syntax.node(Ascii.decInt, \"number\")\n * const tree = Syntax.parse(number, \"12\")\n * Syntax.reparse(tree, \"123\", [{ start: 2, oldEnd: 2, newEnd: 3 }]).root.value // 123\n * ```\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const reparse = <A, E, I extends Input>(\n tree: Tree<A, E, I>,\n input: NoInfer<Source<I>>,\n edits?: Edit | ReadonlyArray<Edit>\n): Tree<A, E, I> => {\n const next = fromSource(input as Input) as I\n const list =\n edits === undefined\n ? diffList(tree.input, next)\n : \"start\" in edits\n ? [edits as Edit]\n : (edits as ReadonlyArray<Edit>)\n const previous: Previous = {\n root: tree.green,\n oldLength: tree.input.length,\n newLength: next.length,\n segments: segmentsOf(tree.input.length, next.length, list),\n input: tree.input,\n extra: tree.config.lookahead,\n encoding: tree.encoding\n }\n return run(tree.config, next, previous)\n}\n\n/**\n * Replaces `[start, end)` of a tree's string input with `text` and parses\n * the result incrementally (see {@link reparse}).\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const replace = <A, E>(\n tree: Tree<A, E, string>,\n start: number,\n end: number,\n text: string\n): Tree<A, E, string> => {\n const input = tree.input\n if (start < 0 || end < start || end > input.length) {\n throw new RangeError(`invalid range [${start}, ${end}) of an input of length ${input.length}`)\n }\n return reparse(tree, input.slice(0, start) + text + input.slice(end), {\n start,\n oldEnd: end,\n newEnd: start + text.length\n })\n}\n\n/**\n * Finds the edit that turns `before` into `after`: the part between their\n * longest common prefix and suffix. `undefined` when they are equal.\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const diff = <I extends Input>(before: I, after: I): Edit | undefined => {\n const a = before as any\n const b = after as any\n const at = Predicate.isString(a) ? (s: string, i: number) => s.charCodeAt(i) : (s: any, i: number) => s[i]\n const max = Math.min(a.length, b.length)\n let prefix = 0\n while (prefix < max && at(a, prefix) === at(b, prefix)) prefix++\n if (prefix === a.length && prefix === b.length) return undefined\n let suffix = 0\n while (suffix < max - prefix && at(a, a.length - 1 - suffix) === at(b, b.length - 1 - suffix)) suffix++\n return { start: prefix, oldEnd: a.length - suffix, newEnd: b.length - suffix }\n}\n\nconst diffList = (before: Input, after: Input): ReadonlyArray<Edit> => {\n const edit = diff(before, after)\n return edit === undefined ? [] : [edit]\n}\n\n/** The stretches of the new input copied unchanged from the old one. */\nconst segmentsOf = (oldLength: number, newLength: number, edits: ReadonlyArray<Edit>): Array<Segment> => {\n let segments: Array<Segment> = oldLength > 0 ? [{ newStart: 0, oldStart: 0, length: oldLength }] : []\n let length = oldLength\n for (const { newEnd, oldEnd, start } of edits) {\n if (!(start >= 0 && oldEnd >= start && oldEnd <= length && newEnd >= start)) {\n throw new RangeError(\n `invalid edit { start: ${start}, oldEnd: ${oldEnd}, newEnd: ${newEnd} } of an input of length ${length}`\n )\n }\n const delta = newEnd - oldEnd\n const out: Array<Segment> = []\n for (const s of segments) {\n const end = s.newStart + s.length\n if (s.newStart < start) {\n out.push({ newStart: s.newStart, oldStart: s.oldStart, length: Math.min(end, start) - s.newStart })\n }\n if (end > oldEnd) {\n const from = Math.max(s.newStart, oldEnd)\n out.push({ newStart: from + delta, oldStart: s.oldStart + (from - s.newStart), length: end - from })\n }\n }\n segments = out\n length += delta\n }\n if (length !== newLength) {\n throw new RangeError(`the edits give an input of length ${length}, but the new input has length ${newLength}`)\n }\n return segments\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,MAAM,cAAc,MAAkB,MAAc,UAA+B;CACjF,MAAM,OAAO,KAAK;CAElB,MAAM,MAAM,IAAI,IAAI;CACpB,OAAO,WACJ,UAAU;EACT,MAAM,UAAU,MAAM;EACtB,OAAO,YAAY,KAAA,IAAY,KAAK,KAAK,IAAI,QAAQ,KAAK,OAAO,MAAM,KAAK,MAAM,KAAK;CACzF,GACA,KAAK,MACL;EAAE,MAAM;EAAU;EAAM;EAAM;CAAM,CACtC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,OAGK,mBAChB,IAC2B,MAA0B,SACnD,WAAW,MAAM,MAAM,IAAI,CAC/B;;;;;;;;;;;;;;;;;;AAmBA,MAAa,QAGK,oBACf,SAAS,SAAS,KAAK,EAAE,IACC,MAA0B,SACnD,WAAW,MAAM,QAAQ,iBAAiB,IAAI,GAAG,KAAK,CAC1D;AAEA,MAAM,oBAAoB,SAA6B;CACrD,MAAM,IAAI,OAAO,IAAI;CACrB,IAAI,UAAU,SAAS,GAAG,SAAS,KAAK,UAAU,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,UAAU,OAAO,EAAE;CAC/F,OAAO,KAAK,QAAQ;AACtB;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,QAGK,mBAAK,IAA8B,MAA0B,SAAqC;CAClH,MAAM,OAAO,KAAK;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MAAM,MAAM,EAAE,WAAW,EAAE;GAC3B,IAAI,EAAE,WAAW,OACf,IAAI,KAAK;IAAE,UAAU,EAAE;IAAU,UAAU,EAAE;IAAU,QAAQ,KAAK,IAAI,KAAK,KAAK,IAAI,EAAE;GAAS,CAAC;GAEpG,IAAI,MAAM,QAAQ;IAChB,MAAM,OAAO,KAAK,IAAI,EAAE,UAAU,MAAM;IACxC,IAAI,KAAK;KAAE,UAAU,OAAO;KAAO,UAAU,EAAE,YAAY,OAAO,EAAE;KAAW,QAAQ,MAAM;IAAK,CAAC;GACrG;EACF;EACA,WAAW;EACX,UAAU;CACZ;CACA,IAAI,WAAW,WACb,MAAM,IAAI,WAAW,qCAAqC,OAAO,iCAAiC,WAAW;CAE/G,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"Syntax.js","names":[],"sources":["../src/Syntax.ts"],"sourcesContent":["/**\n * Concrete syntax trees and incremental parsing, in the spirit of\n * [Tree-sitter](https://tree-sitter.github.io).\n *\n * Mark the rules of a grammar that should appear in the tree with\n * {@link node} (and, optionally, {@link token} and {@link field}). Outside\n * this module the marks change nothing: `Parser.parse` returns the same\n * values, and compiled parsers compile them away. {@link parse} runs the\n * grammar and returns a {@link Tree}: a tree of {@link SyntaxNode}s with\n * spans, parents and siblings, to search by position (`descendantAt`) or walk\n * with a {@link TreeCursor}. Each node also carries the value its parser\n * returned.\n *\n * Like Tree-sitter, a syntax parse always produces a tree. Failures handled\n * by `Parser.resumeAfter` and `Parser.retryAfter` become `ERROR` nodes over\n * the input they skipped, and so does any input after a fatal failure.\n *\n * After an edit, {@link reparse} (or {@link replace}) parses the new input\n * reusing every node of the old tree whose input is unchanged: only the\n * nodes that enclose the edit, or looked at the edited input, are parsed\n * again, and each reused node is stepped over whole.\n *\n * @example\n * ```ts\n * import { Ascii, Parser, Syntax, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const ws = Ascii.multispace0\n * const number = Syntax.node(Ascii.decInt, \"number\")\n * const list = Syntax.node(\n * Parser.delimited(\n * Token.literal(\"[\"),\n * Parser.separated(Parser.delimited(ws, number, ws), Token.literal(\",\")),\n * Token.literal(\"]\")\n * ),\n * \"list\"\n * )\n *\n * const tree = Syntax.parse(list, \"[1, 2, 3]\")\n * String(tree.root) // \"(list (number) (number) (number))\"\n * tree.root.descendantAt(4)?.text // \"2\"\n *\n * const edited = Syntax.replace(tree, 4, 5, \"20\") // \"[1, 20, 3]\"\n * edited.root.namedChild(1)?.value // 20\n * edited.reused // 2: only \"20\" was parsed again\n * ```\n *\n * @since 0.2.0\n */\nimport * as Str from \"effect/String\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Context from \"effect/Context\"\nimport { dual } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport type { Input, Slice, Source } from \"./Input.js\"\nimport { Fail, fromSource, State } from \"./Input.js\"\nimport * as ParseError from \"./ParseError.js\"\nimport { nodeOf } from \"./internal/node.js\"\nimport { Key } from \"./internal/key.js\"\nimport * as Stack from \"./internal/stack.js\"\nimport type { ErrorInfo, Green, Previous, Segment } from \"./internal/syntax.js\"\nimport { absolute, errorKind, SyntaxBuilder } from \"./internal/syntax.js\"\nimport type { Parser } from \"./Parser.js\"\nimport { described, isParser } from \"./Parser.js\"\n\n// -----------------------------------------------------------------------------\n// Grammar annotations\n// -----------------------------------------------------------------------------\n\nconst syntaxNode = <A, E, R, I extends Input>(\n self: Parser<A, E, R, I>,\n kind: string,\n named: boolean\n): Parser<A, E, R, I> => {\n const step = self.step\n // Identifies the nodes this parser builds, so a reparse can reuse them\n const key = new Key()\n return described<A, E, R, I>(\n (state) => {\n const builder = state.syntax\n return builder === undefined ? step(state) : builder.node(state, step, key, kind, named)\n },\n self.name,\n { _tag: \"Syntax\", self, kind, named }\n )\n}\n\n/**\n * Marks a parser as a rule of the syntax tree: in a {@link parse}, each\n * match becomes a named node of the given kind, spanning the input it\n * consumed, with the nodes built inside it as children and its output as\n * its `value`. Outside {@link parse}, the parser is unchanged.\n *\n * A match that consumes nothing adds no node (as in Tree-sitter, where rules\n * can't match the empty string).\n *\n * For {@link reparse} to reuse a node, its parser's output must depend only\n * on the input from where the node starts: not on services, on state kept\n * in closures, or on absolute offsets (`Parser.location`, `Parser.span`),\n * which are not updated when the node moves. Use the node's `start` and\n * `end` instead.\n *\n * @since 0.2.0\n * @category annotations\n */\nexport const node: {\n (kind: string): <A, E, R, I extends Input>(self: Parser<A, E, R, I>) => Parser<A, E, R, I>\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind: string): Parser<A, E, R, I>\n} = /*#__PURE__*/ dual(2, <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind: string): Parser<A, E, R, I> =>\n syntaxNode(self, kind, true)\n)\n\n/**\n * Like {@link node}, but builds an *anonymous* node, Tree-sitter's name for\n * punctuation and keywords: anonymous nodes are left out of\n * `namedChildren` and of the tree's printed form. The kind defaults to the\n * literal for a `Token.literal` of a string, and to the parser's name\n * otherwise.\n *\n * @example\n * ```ts\n * import { Syntax, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const comma = Syntax.token(Token.literal(\",\")) // kind \",\"\n * ```\n *\n * @since 0.2.0\n * @category annotations\n */\nexport const token: {\n (kind?: string): <A, E, R, I extends Input>(self: Parser<A, E, R, I>) => Parser<A, E, R, I>\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind?: string): Parser<A, E, R, I>\n} = /*#__PURE__*/ dual(\n (args) => isParser(args[0]),\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, kind?: string): Parser<A, E, R, I> =>\n syntaxNode(self, kind ?? defaultTokenKind(self), false)\n)\n\nconst defaultTokenKind = (self: Parser.Any): string => {\n const n = nodeOf(self)\n if (Predicate.isTagged(n, \"Literal\") && Predicate.isString(n.literal) && !n.caseless) return n.literal\n return self.name ?? \"token\"\n}\n\n/**\n * Gives the nodes built by a parser a field name in their parent, like\n * Tree-sitter's `field(name, rule)`: find them with `childByField` and\n * `childrenByField`. Outside {@link parse}, the parser is unchanged.\n *\n * @example\n * ```ts\n * import { Ascii, Parser, Syntax, Token } from \"@thomasfosterau/effect-parse\"\n *\n * const name = Syntax.node(Ascii.alpha1, \"name\")\n * const number = Syntax.node(Ascii.decInt, \"number\")\n * const pair = Syntax.node(\n * Parser.separatedPair(Syntax.field(name, \"key\"), Token.literal(\"=\"), Syntax.field(number, \"value\")),\n * \"pair\"\n * )\n * Syntax.parse(pair, \"x=1\").root.childByField(\"value\")?.value // 1\n * ```\n *\n * @since 0.2.0\n * @category annotations\n */\nexport const field: {\n (name: string): <A, E, R, I extends Input>(self: Parser<A, E, R, I>) => Parser<A, E, R, I>\n <A, E, R, I extends Input>(self: Parser<A, E, R, I>, name: string): Parser<A, E, R, I>\n} = /*#__PURE__*/ dual(2, <A, E, R, I extends Input>(self: Parser<A, E, R, I>, name: string): Parser<A, E, R, I> => {\n const step = self.step\n return described<A, E, R, I>(\n (state) => {\n const builder = state.syntax\n return builder === undefined ? step(state) : builder.field(state, step, name)\n },\n self.name,\n { _tag: \"Syntax\", self, kind: undefined, named: false }\n )\n})\n\n// -----------------------------------------------------------------------------\n// Trees\n// -----------------------------------------------------------------------------\n\n/**\n * The kind of the nodes that stand for input that could not be parsed.\n *\n * @since 0.2.0\n * @category models\n */\nexport const ERROR: \"ERROR\" = errorKind\n\n/**\n * An edit to an input, as Tree-sitter's `TSInputEdit`: the input\n * `[start, oldEnd)` was replaced by `[start, newEnd)`. Offsets are in the\n * input's units (UTF-16 code units for strings, bytes, elements).\n *\n * @since 0.2.0\n * @category models\n */\nexport interface Edit {\n readonly start: number\n readonly oldEnd: number\n readonly newEnd: number\n}\n\n/**\n * Options for {@link parse}.\n *\n * @since 0.2.0\n * @category models\n */\nexport interface ParseOptions {\n /**\n * The kind of the root node, when the grammar itself is not a\n * {@link node}. Defaults to `\"document\"`.\n */\n readonly kind?: string | undefined\n /**\n * For {@link reparse}: how many input units custom parsers may read past\n * the furthest position they move the cursor to or record a failure at,\n * besides one token there. Defaults to 0, which is right for the built-in\n * parsers, and for custom parsers (`Parser.make`) that only read past\n * where they stop to see that the token there doesn't match.\n *\n * A node is reused only when the input its parse looked at is unchanged.\n * Built-in parsers that read further, such as a literal that fails part\n * way or `Token.takeUntil`, record how far they read.\n */\n readonly lookahead?: number | undefined\n}\n\n/**\n * Options for {@link parse} with a parser that requires services.\n *\n * @since 0.2.0\n * @category models\n */\nexport interface ParseOptionsWithContext<R> extends ParseOptions {\n readonly context: Context.Context<R>\n}\n\ninterface Config {\n readonly kind: string\n readonly inner: Parser.Any\n readonly lookahead: number\n readonly context: Context.Context<never> | undefined\n}\n\n/**\n * The result of a {@link parse}: a syntax tree over the whole input, the\n * grammar's output, and the errors met on the way.\n *\n * @since 0.2.0\n * @category models\n */\nexport class Tree<out A, out E = never, I extends Input = string> {\n /** The root node. It always spans the whole input. */\n readonly root: SyntaxNode<I>\n private lines: Array<number> | undefined\n private errorList: ReadonlyArray<ParseError.ParseError<E>> | undefined\n\n /** @internal */\n constructor(\n /** The input the tree was parsed from. */\n readonly input: I,\n /** The grammar's output: `none` when the parse failed. */\n readonly value: Option.Option<A>,\n /** How many nodes were reused from the previous tree by {@link reparse}. */\n readonly reused: number,\n /** @internal */\n readonly green: Green,\n /** @internal */\n readonly config: Config,\n /** @internal */\n readonly encoding: ParseError.ParseError<never>[\"encoding\"]\n ) {\n this.root = new SyntaxNode(this, green, 0, undefined, 0)\n }\n\n /**\n * Every error of the parse, in input order: the failures recovered by\n * `Parser.resumeAfter` and `Parser.retryAfter`, then the fatal one, if\n * the parse failed. Each one belongs to an `ERROR` node.\n */\n get errors(): ReadonlyArray<ParseError.ParseError<E>> {\n if (this.errorList === undefined) {\n const out: Array<ParseError.ParseError<E>> = []\n const visit = (green: Green, start: number) => {\n if (!green.hasError) return\n if (green.error !== undefined) out.push(this.toError(green.error, start))\n for (let i = 0; i < green.children.length; i++) visit(green.children[i], start + green.offsets[i])\n }\n visit(this.green, 0)\n this.errorList = out\n }\n return this.errorList\n }\n\n /** Whether the tree has any `ERROR` node. */\n get hasErrors(): boolean {\n return this.green.hasError\n }\n\n /** The smallest node containing `[start, end)` (see {@link SyntaxNode.descendantAt}). */\n descendantAt(start: number, end?: number): SyntaxNode<I> {\n return this.root.descendantAt(start, end)\n }\n\n /** A cursor at the root. */\n walk(): TreeCursor<I> {\n return new TreeCursor(this.root)\n }\n\n /**\n * The 1-based line and column (in code points) of an offset, as in\n * `ParseError`. Lines of a string input are indexed once, so lookups take\n * logarithmic time.\n */\n lineColumn(offset: number): ParseError.LineColumn {\n const input = this.input\n if (!Predicate.isString(input)) return ParseError.lineColumn(input, offset, this.encoding)\n let lines = this.lines\n if (lines === undefined) {\n lines = [0]\n for (let i = input.indexOf(\"\\n\"); i >= 0; i = input.indexOf(\"\\n\", i + 1)) lines.push(i + 1)\n this.lines = lines\n }\n const at = Math.max(0, Math.min(offset, input.length))\n let lo = 0\n let hi = lines.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (lines[mid] <= at) lo = mid\n else hi = mid - 1\n }\n const lineStart = lines[lo]\n return { line: lo + 1, column: ParseError.lineColumn(input.slice(lineStart, at), at - lineStart).column }\n }\n\n /** The root's S-expression (see {@link SyntaxNode.toString}). */\n toString(): string {\n return this.root.toString()\n }\n\n /** @internal */\n toError(error: ErrorInfo, start: number): ParseError.ParseError<E> {\n return ParseError.fromFailure<E>(this.input, absolute(error.failure, start), error.mode, this.encoding)\n }\n}\n\n/**\n * What `JSON.stringify` writes for a {@link SyntaxNode}: its kind and span.\n *\n * @since 0.5.0\n * @category models\n */\nexport interface SyntaxNodeJson {\n readonly kind: string\n readonly start: number\n readonly end: number\n}\n\n/**\n * A node of a syntax tree: its kind, span and value, and its place in the\n * tree. Nodes are views built on demand; two views of the same node are\n * different objects but have the same `start`, `end` and `kind`.\n *\n * @since 0.2.0\n * @category models\n */\nexport class SyntaxNode<I extends Input = string> {\n private childList: ReadonlyArray<SyntaxNode<I>> | undefined\n\n /** @internal */\n constructor(\n /** The tree this node belongs to. */\n readonly tree: Tree<unknown, unknown, I>,\n /** @internal */\n readonly green: Green,\n /** The offset where the node starts. */\n readonly start: number,\n /** The parent node; `undefined` for the root. */\n readonly parent: SyntaxNode<I> | undefined,\n /** The node's index among its parent's children. */\n readonly index: number\n ) {}\n\n /** The node's kind: the name given to {@link node} or {@link token}, or `\"ERROR\"`. */\n get kind(): string {\n return this.green.kind\n }\n\n /** `false` for the anonymous nodes built by {@link token}. */\n get named(): boolean {\n return this.green.named\n }\n\n /** The field name given by {@link field}, if any. */\n get field(): string | undefined {\n return this.parent?.green.fields?.[this.index]\n }\n\n /** The offset where the node ends (exclusive). */\n get end(): number {\n return this.start + this.green.width\n }\n\n /** The number of input units the node spans. */\n get length(): number {\n return this.green.width\n }\n\n /** The output of the node's parser (`undefined` for `ERROR` nodes, and for a root that failed). */\n get value(): unknown {\n return this.green.value\n }\n\n /** The input the node spans. */\n get text(): Slice<I> {\n const input: Input = this.tree.input\n // SAFETY: a `subarray` of a `Uint8Array`, or a `slice` of a string or array, has the input's own kind, `Slice<I>`\n return (\n input instanceof Uint8Array ? input.subarray(this.start, this.end) : input.slice(this.start, this.end)\n ) as Slice<I>\n }\n\n /** Whether this is an `ERROR` node. */\n get isError(): boolean {\n return this.green.error !== undefined\n }\n\n /** Whether this node or a descendant is an `ERROR` node. */\n get hasError(): boolean {\n return this.green.hasError\n }\n\n /** For an `ERROR` node, the error it stands for. */\n get error(): ParseError.ParseError<unknown> | undefined {\n const error = this.green.error\n return error === undefined ? undefined : this.tree.toError(error, this.start)\n }\n\n /** The child nodes, named and anonymous, in input order. */\n get children(): ReadonlyArray<SyntaxNode<I>> {\n if (this.childList === undefined) {\n const green = this.green\n const out = new Array<SyntaxNode<I>>(green.children.length)\n for (let i = 0; i < out.length; i++) out[i] = this.makeChild(i)\n this.childList = out\n }\n return this.childList\n }\n\n /** The number of children. */\n get childCount(): number {\n return this.green.children.length\n }\n\n /** The child at `index` (negative indices count from the end). */\n child(index: number): SyntaxNode<I> | undefined {\n const n = this.green.children.length\n const i = index < 0 ? n + index : index\n return i >= 0 && i < n ? this.children[i] : undefined\n }\n\n /** The named children. */\n get namedChildren(): ReadonlyArray<SyntaxNode<I>> {\n return this.children.filter((c) => c.named)\n }\n\n /** The named child at `index`. */\n namedChild(index: number): SyntaxNode<I> | undefined {\n return this.namedChildren[index]\n }\n\n /** The first child with the given field name. */\n childByField(name: string): SyntaxNode<I> | undefined {\n const fields = this.green.fields\n if (fields === undefined) return undefined\n const i = fields.indexOf(name)\n return i < 0 ? undefined : this.children[i]\n }\n\n /** The children with the given field name. */\n childrenByField(name: string): ReadonlyArray<SyntaxNode<I>> {\n const fields = this.green.fields\n if (fields === undefined) return []\n return this.children.filter((_, i) => fields[i] === name)\n }\n\n /** The next sibling, named or anonymous. */\n get nextSibling(): SyntaxNode<I> | undefined {\n return this.parent?.children[this.index + 1]\n }\n\n /** The previous sibling, named or anonymous. */\n get previousSibling(): SyntaxNode<I> | undefined {\n return this.index > 0 ? this.parent?.children[this.index - 1] : undefined\n }\n\n /** The next named sibling. */\n get nextNamedSibling(): SyntaxNode<I> | undefined {\n const siblings = this.parent?.children\n if (siblings === undefined) return undefined\n for (let i = this.index + 1; i < siblings.length; i++) if (siblings[i].named) return siblings[i]\n return undefined\n }\n\n /** The previous named sibling. */\n get previousNamedSibling(): SyntaxNode<I> | undefined {\n const siblings = this.parent?.children\n if (siblings === undefined) return undefined\n for (let i = this.index - 1; i >= 0; i--) if (siblings[i].named) return siblings[i]\n return undefined\n }\n\n /**\n * The index of the child containing the input unit at `offset`, or -1.\n * Takes logarithmic time.\n */\n childIndexAt(offset: number): number {\n const green = this.green\n const offsets = green.offsets\n const rel = offset - this.start\n let lo = 0\n let hi = offsets.length - 1\n let found = -1\n while (lo <= hi) {\n const mid = (lo + hi) >> 1\n if (offsets[mid] <= rel) {\n found = mid\n lo = mid + 1\n } else {\n hi = mid - 1\n }\n }\n // Skip back over empty `ERROR` nodes at `offset`\n while (found >= 0 && green.children[found].width === 0 && offsets[found] === rel) found--\n return found >= 0 && rel < offsets[found] + green.children[found].width ? found : -1\n }\n\n /** The child containing the input unit at `offset`. */\n childAt(offset: number): SyntaxNode<I> | undefined {\n const i = this.childIndexAt(offset)\n return i < 0 ? undefined : this.children[i]\n }\n\n /**\n * The smallest node, this one or a descendant, that contains\n * `[start, end)` (Tree-sitter's `descendant_for_byte_range`). With only\n * `start`, the deepest node containing the input unit at `start`. Takes\n * time proportional to the depth of the tree times the logarithm of the\n * number of children.\n */\n descendantAt(start: number, end: number = start + 1): SyntaxNode<I> {\n return descendantOf(this, start, end)\n }\n\n /** Like {@link descendantAt}, but only stops at named nodes. */\n namedDescendantAt(start: number, end: number = start + 1): SyntaxNode<I> {\n let node: SyntaxNode<I> = this.descendantAt(start, end)\n // Every node below `this` has a parent, so the walk stops at `this` at the latest\n while (!node.named && node !== this) node = node.parent ?? this\n return node\n }\n\n /** This node and its descendants, in pre-order. */\n *descendants(): Generator<SyntaxNode<I>, void, undefined> {\n const cursor = this.walk()\n while (true) {\n yield cursor.node\n if (cursor.gotoFirstChild()) continue\n while (!cursor.gotoNextSibling()) {\n if (!cursor.gotoParent()) return\n }\n }\n }\n\n /** The descendants of the given kind, in pre-order. */\n *descendantsOfKind(kind: string): Generator<SyntaxNode<I>, void, undefined> {\n for (const n of this.descendants()) if (n.kind === kind) yield n\n }\n\n /** A cursor at this node, which cannot move above it. */\n walk(): TreeCursor<I> {\n return new TreeCursor(this)\n }\n\n /**\n * The node as an S-expression of its named descendants, with field\n * names, as Tree-sitter prints it: `(pair key: (name) value: (number))`.\n */\n toString(): string {\n let out = \"\"\n const visit = (green: Green, field: string | undefined) => {\n if (green.named || green === this.green) {\n if (Str.isNonEmpty(out)) out += \" \"\n if (field !== undefined) out += `${field}: `\n out += `(${green.kind}`\n for (let i = 0; i < green.children.length; i++) visit(green.children[i], green.fields?.[i])\n out += \")\"\n } else {\n for (let i = 0; i < green.children.length; i++) visit(green.children[i], green.fields?.[i])\n }\n }\n visit(this.green, this.field)\n return out\n }\n\n toJSON(): SyntaxNodeJson {\n return { kind: this.kind, start: this.start, end: this.end }\n }\n\n private makeChild(i: number): SyntaxNode<I> {\n const green = this.green\n return new SyntaxNode(this.tree, green.children[i], this.start + green.offsets[i], this, i)\n }\n}\n\n/** The smallest node, `root` or a descendant, that contains `[start, end)` (see `SyntaxNode.descendantAt`). */\nconst descendantOf = <I extends Input>(root: SyntaxNode<I>, start: number, end: number): SyntaxNode<I> => {\n let node = root\n while (true) {\n const i = node.childIndexAt(start)\n if (i < 0) return node\n const child = node.children[i]\n if (end > child.end) return node\n node = child\n }\n}\n\n/**\n * A cursor for walking a tree, as Tree-sitter's `TreeCursor`. It starts at\n * a node and cannot move above it.\n *\n * @since 0.2.0\n * @category models\n */\nexport class TreeCursor<I extends Input = string> {\n private current: SyntaxNode<I>\n private depth = 0\n\n /** @internal */\n constructor(node: SyntaxNode<I>) {\n this.current = node\n }\n\n /** The node at the cursor. */\n get node(): SyntaxNode<I> {\n return this.current\n }\n\n /** The field name of the node at the cursor, if any. */\n get field(): string | undefined {\n return this.depth === 0 ? undefined : this.current.field\n }\n\n /** Moves to the first child; `false` if there is none. */\n gotoFirstChild(): boolean {\n return this.goto(this.current.child(0))\n }\n\n /** Moves to the last child; `false` if there is none. */\n gotoLastChild(): boolean {\n return this.goto(this.current.child(-1))\n }\n\n /** Moves to the child containing the input unit at `offset`; `false` if there is none. */\n gotoFirstChildForOffset(offset: number): boolean {\n return this.goto(this.current.childAt(offset))\n }\n\n /** Moves to the next sibling; `false` if there is none. */\n gotoNextSibling(): boolean {\n if (this.depth === 0) return false\n const next = this.current.nextSibling\n if (next === undefined) return false\n this.current = next\n return true\n }\n\n /** Moves to the previous sibling; `false` if there is none. */\n gotoPreviousSibling(): boolean {\n if (this.depth === 0) return false\n const previous = this.current.previousSibling\n if (previous === undefined) return false\n this.current = previous\n return true\n }\n\n /** Moves to the parent; `false` at the node the cursor started at. */\n gotoParent(): boolean {\n const parent = this.current.parent\n if (this.depth === 0 || parent === undefined) return false\n this.current = parent\n this.depth--\n return true\n }\n\n /** Moves to the deepest node containing the input unit at `offset`. */\n gotoDescendantAt(offset: number): void {\n while (this.gotoFirstChildForOffset(offset)) {\n // descend\n }\n }\n\n /** Starts again at `node`. */\n reset(node: SyntaxNode<I>): void {\n this.current = node\n this.depth = 0\n }\n\n private goto(node: SyntaxNode<I> | undefined): boolean {\n if (node === undefined) return false\n this.current = node\n this.depth++\n return true\n }\n}\n\n// -----------------------------------------------------------------------------\n// Parsing\n// -----------------------------------------------------------------------------\n\nconst expectedEof = [\"end of input\"]\n\nconst run = <A, E, I extends Input>(config: Config, input: I, previous: Previous | undefined): Tree<A, E, I> => {\n const state = new State<I>(input, { context: config.context })\n const builder = new SyntaxBuilder(state, previous)\n const a = Stack.run(config.inner.step, state)\n // Text parsers record the encoding when they fail, which they may have done inside reused nodes\n if (state.encoding === undefined && previous !== undefined) state.encoding = previous.encoding\n let fatal: ErrorInfo | undefined\n let value: Option.Option<A> = Option.none()\n if (a === Fail) {\n fatal = { failure: state.reportedFailure(), mode: state.mode }\n } else if (state.pos < state.end) {\n state.backtrack(\"Eof\", expectedEof)\n fatal = { failure: state.reportedFailure(), mode: \"Backtrack\" }\n } else {\n // SAFETY: `config.inner` is the `Parser<A, ...>` given to `parse` or the parser its root `node` wraps, which returns\n // the same `A` (a `reparse` reuses the tree's config)\n value = Option.some(a as A)\n }\n const green = builder.finish(config.kind, Option.getOrUndefined(value), fatal, state.pos)\n return new Tree<A, E, I>(input, value, builder.reused, green, config, state.encoding)\n}\n\n/**\n * The overloads of {@link parse}.\n *\n * @since 0.5.0\n * @category parsing\n */\nexport interface ParseFn {\n <A, E, I extends Input>(\n grammar: Parser<A, E, never, I>,\n input: NoInfer<Source<I>>,\n options?: ParseOptions\n ): Tree<A, E, I>\n <A, E, R, I extends Input>(\n grammar: Parser<A, E, R, I>,\n input: NoInfer<Source<I>>,\n options: ParseOptionsWithContext<R>\n ): Tree<A, E, I>\n}\n\n/**\n * Parses an input into a syntax {@link Tree}. The grammar's output is the\n * tree's `value`, and its {@link node}s are the tree's nodes. When the\n * grammar is itself a {@link node}, that node is the root; otherwise the\n * root is a node of kind `options.kind` (by default `\"document\"`).\n *\n * The parse never fails: recovered failures (see `Parser.resumeAfter`), a\n * fatal failure and unparsed input at the end all become `ERROR` nodes, and\n * are listed in `tree.errors`. The parse is interpreted, never compiled.\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const parse: ParseFn = <A, E, R, I extends Input>(\n grammar: Parser<A, E, R, I>,\n input: I | Source<I>,\n options?: ParseOptions & { readonly context?: Context.Context<R> }\n): Tree<A, E, I> => {\n const n = nodeOf(grammar)\n const isRoot = Predicate.isTagged(n, \"Syntax\") && n.kind !== undefined && n.named\n const config: Config = {\n kind: isRoot ? n.kind : (options?.kind ?? \"document\"),\n // SAFETY: a `Syntax` node's `self` is the parser that `node` wrapped, a parser built by this library\n inner: isRoot ? (n.self as Parser.Any) : grammar,\n lookahead: options?.lookahead ?? 0,\n context: options?.context\n }\n return run(config, fromSource<I>(input), undefined)\n}\n\n/**\n * Parses the new version of a tree's input, reusing the nodes of the tree\n * that the edits leave unchanged (Tree-sitter's `ts_tree_edit` followed by\n * `ts_parser_parse` with the old tree). The result is the tree a fresh\n * {@link parse} of `input` would build, but only the parts of the tree\n * around the edits are parsed again. `tree.reused` says how many nodes were\n * reused.\n *\n * `edits` describe how the old input became the new one, applied in order,\n * each in the coordinates of the input as the previous edits left it. When\n * they are omitted, the edit is found by comparing the inputs (their common\n * prefix and suffix), which takes time linear in their length but much less\n * than parsing.\n *\n * Errors in the new tree are those a fresh parse reports, except that an\n * error just after a reused node may list fewer expected alternatives.\n *\n * @example\n * ```ts\n * import { Ascii, Syntax } from \"@thomasfosterau/effect-parse\"\n *\n * const number = Syntax.node(Ascii.decInt, \"number\")\n * const tree = Syntax.parse(number, \"12\")\n * Syntax.reparse(tree, \"123\", [{ start: 2, oldEnd: 2, newEnd: 3 }]).root.value // 123\n * ```\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const reparse = <A, E, I extends Input>(\n tree: Tree<A, E, I>,\n input: NoInfer<Source<I>>,\n edits?: Edit | ReadonlyArray<Edit>\n): Tree<A, E, I> => {\n const next = fromSource<I>(input)\n const list = edits === undefined ? diffList(tree.input, next) : \"start\" in edits ? [edits] : edits\n const previous: Previous = {\n root: tree.green,\n oldLength: tree.input.length,\n newLength: next.length,\n segments: segmentsOf(tree.input.length, next.length, list),\n input: tree.input,\n extra: tree.config.lookahead,\n encoding: tree.encoding\n }\n return run(tree.config, next, previous)\n}\n\n/**\n * Replaces `[start, end)` of a tree's string input with `text` and parses\n * the result incrementally (see {@link reparse}).\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const replace = <A, E>(\n tree: Tree<A, E, string>,\n start: number,\n end: number,\n text: string\n): Tree<A, E, string> => {\n const input = tree.input\n if (start < 0 || end < start || end > input.length) {\n throw new RangeError(`invalid range [${start}, ${end}) of an input of length ${input.length}`)\n }\n return reparse(tree, input.slice(0, start) + text + input.slice(end), {\n start,\n oldEnd: end,\n newEnd: start + text.length\n })\n}\n\n/**\n * Finds the edit that turns `before` into `after`: the part between their\n * longest common prefix and suffix. `undefined` when they are equal.\n *\n * @since 0.2.0\n * @category parsing\n */\nexport const diff = <I extends Input>(before: I, after: I): Edit | undefined => {\n const a: Input = before\n const b: Input = after\n // SAFETY: the string reader is chosen only when `a` is a string, and `b` has the same type `I`\n const at = Predicate.isString(a)\n ? (s: Input, i: number) => (s as string).charCodeAt(i)\n : (s: Input, i: number) => s[i]\n const max = Math.min(a.length, b.length)\n let prefix = 0\n while (prefix < max && at(a, prefix) === at(b, prefix)) prefix++\n if (prefix === a.length && prefix === b.length) return undefined\n let suffix = 0\n while (suffix < max - prefix && at(a, a.length - 1 - suffix) === at(b, b.length - 1 - suffix)) suffix++\n return { start: prefix, oldEnd: a.length - suffix, newEnd: b.length - suffix }\n}\n\nconst diffList = (before: Input, after: Input): ReadonlyArray<Edit> => {\n const edit = diff(before, after)\n return edit === undefined ? [] : [edit]\n}\n\n/** The stretches of the new input copied unchanged from the old one. */\nconst segmentsOf = (oldLength: number, newLength: number, edits: ReadonlyArray<Edit>): Array<Segment> => {\n let segments: Array<Segment> = oldLength > 0 ? [{ newStart: 0, oldStart: 0, length: oldLength }] : []\n let length = oldLength\n for (const { newEnd, oldEnd, start } of edits) {\n if (!(start >= 0 && oldEnd >= start && oldEnd <= length && newEnd >= start)) {\n throw new RangeError(\n `invalid edit { start: ${start}, oldEnd: ${oldEnd}, newEnd: ${newEnd} } of an input of length ${length}`\n )\n }\n const delta = newEnd - oldEnd\n const out: Array<Segment> = []\n for (const s of segments) {\n const end = s.newStart + s.length\n if (s.newStart < start) {\n out.push({ newStart: s.newStart, oldStart: s.oldStart, length: Math.min(end, start) - s.newStart })\n }\n if (end > oldEnd) {\n const from = Math.max(s.newStart, oldEnd)\n out.push({ newStart: from + delta, oldStart: s.oldStart + (from - s.newStart), length: end - from })\n }\n }\n segments = out\n length += delta\n }\n if (length !== newLength) {\n throw new RangeError(`the edits give an input of length ${length}, but the new input has length ${newLength}`)\n }\n return segments\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,MAAM,cACJ,MACA,MACA,UACuB;CACvB,MAAM,OAAO,KAAK;CAElB,MAAM,MAAM,IAAI,IAAI;CACpB,OAAO,WACJ,UAAU;EACT,MAAM,UAAU,MAAM;EACtB,OAAO,YAAY,KAAA,IAAY,KAAK,KAAK,IAAI,QAAQ,KAAK,OAAO,MAAM,KAAK,MAAM,KAAK;CACzF,GACA,KAAK,MACL;EAAE,MAAM;EAAU;EAAM;EAAM;CAAM,CACtC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,OAGK,mBAAK,IAA8B,MAA0B,SAC7E,WAAW,MAAM,MAAM,IAAI,CAC7B;;;;;;;;;;;;;;;;;;AAmBA,MAAa,QAGK,oB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GAAG,MAAM,OAAO,GAAG,GAAG,GAAG,OAAO,eAAe,GAAG,GAAG;;WAKnE,QAAQ,6BAA6B;;WAErC,QAAQ,6BAA6B;;WAErC,QAAQ,6BAA6B;;WAErC,QAAQ,6BAA6B;;WAErC,eAAe,6BAA6B;;WAE5C,eAAe,6BAA6B;;WAE5C,QAAQ,6BAA6B;;WAErC,QAAQ,6BAA6B;;WAErC,aAAa,6BAA6B;;WAE1C,aAAa,6BAA6B;;;;;WAK1C,YAAY,6BAA6B;;WAKzC,SAAS,2BAA2B;;WAEpC,MAAM,6BAA6B;;WAEnC,KAAK,2BAA2B;;WAEhC,YAAY,oCAAoC;;WAEhD,gBAAgB,6BAA6B;;WAK7C,SAAS,8BAA8B;;WAEvC,QAAQ,8BAA8B;;WAEtC,YAAY,6BAA6B;;WAEzC,WAAW,6BAA6B;;WAExC,SAAS,8BAA8B;;WAEvC,OAAO,6BAA6B;;;;;WAQpC,cAAc,GAAG,GAAG,GAAG,GAAG,IAAI,IACrC,QAAQ,OAAO,GAAG,GAAG,GAAG,IACxB,iBACA,WAAW,OAAO,GAAG,IAAI,IAAI,OAC1B,eAAe,IAAI,IAAI,IAAI,IAAI;;;;;WAK3B,UAAU,GAAG,GAAG,IAAI,IAC3B,QAAQ,eAAe,GAAG,GAAG,IAC7B,iBACA,QAAQ,eAAe,IAAI,IAAI,OAC5B,eAAe,IAAI,IAAI,IAAI,IAAI;;;;;;;;;;;;;;;;qBAyCzB,OAAQ,mBAAmB,YAAY,UAAU,SAAS,OAAK,YAAY;;;;;;;qBAwZ3E,QAAQ;;;;;;;;;;;;;;;;qBAiBR,MAAM,YAAY;;;;;;;qBAQlB,SAAS,YAAY;;;;;;;qBAQrB,SAAS,YAAY;;;;;;;qBAQrB,QAAQ,YAAY"}
|
package/dist/Text.js
CHANGED
|
@@ -213,7 +213,7 @@ const make = (encoding) => {
|
|
|
213
213
|
const textOf = (state, start, end, kind, expected) => {
|
|
214
214
|
const count = internal.validate(enc, state, start, end);
|
|
215
215
|
if (count < 0) return backtrack(state, kind, expected, -1 - count);
|
|
216
|
-
return
|
|
216
|
+
return internal.textIn(enc, state, start, end);
|
|
217
217
|
};
|
|
218
218
|
const takeWhileText = (test, r, negate, name, expected, kind, hint, set = test) => {
|
|
219
219
|
const [min, max] = normalize(r);
|
|
@@ -228,7 +228,7 @@ const make = (encoding) => {
|
|
|
228
228
|
if (count < min) return backtrack(state, kind, expected, offset);
|
|
229
229
|
if (hint && count < max) state.setHint(offset, expected);
|
|
230
230
|
state.pos = offset;
|
|
231
|
-
return
|
|
231
|
+
return internal.textIn(enc, state, start, offset);
|
|
232
232
|
}, name, {
|
|
233
233
|
_tag: "TakeWhile",
|
|
234
234
|
set,
|
|
@@ -299,7 +299,7 @@ const make = (encoding) => {
|
|
|
299
299
|
pos += internal.width;
|
|
300
300
|
}
|
|
301
301
|
state.pos = pos;
|
|
302
|
-
return
|
|
302
|
+
return internal.textIn(enc, state, start, pos);
|
|
303
303
|
}, expected[0], {
|
|
304
304
|
_tag: "Literal",
|
|
305
305
|
literal: lit,
|
|
@@ -340,7 +340,7 @@ const make = (encoding) => {
|
|
|
340
340
|
pos += internal.width;
|
|
341
341
|
}
|
|
342
342
|
state.pos = pos;
|
|
343
|
-
return
|
|
343
|
+
return internal.textIn(enc, state, start, pos);
|
|
344
344
|
}, "take", {
|
|
345
345
|
_tag: "Take",
|
|
346
346
|
count,
|
|
@@ -367,7 +367,7 @@ const make = (encoding) => {
|
|
|
367
367
|
if (count < min) return backtrack(state, "TakeUntil", expected, idx);
|
|
368
368
|
if (count > max) return backtrack(state, "TakeUntil", expected);
|
|
369
369
|
state.pos = idx;
|
|
370
|
-
return
|
|
370
|
+
return internal.textIn(enc, state, start, idx);
|
|
371
371
|
}, "takeUntil", {
|
|
372
372
|
_tag: "TakeUntil",
|
|
373
373
|
literal: lit,
|
|
@@ -385,7 +385,7 @@ const make = (encoding) => {
|
|
|
385
385
|
if (internal.scanStop === internal.Truncated) return state.incomplete(1, expectedAny);
|
|
386
386
|
if (internal.scanStop === internal.Invalid) return backtrack(state, "Token", expectedAny, offset);
|
|
387
387
|
state.pos = offset;
|
|
388
|
-
return
|
|
388
|
+
return internal.textIn(enc, state, start, offset);
|
|
389
389
|
}, "rest", {
|
|
390
390
|
_tag: "Rest",
|
|
391
391
|
encoding: enc
|
|
@@ -415,7 +415,7 @@ const make = (encoding) => {
|
|
|
415
415
|
const stop = internal.scanStop;
|
|
416
416
|
if (state.partial && (stop === internal.End || stop === internal.Truncated)) return state.incomplete(1, expectedIdentifier);
|
|
417
417
|
state.pos = internal.scanOffset;
|
|
418
|
-
return
|
|
418
|
+
return internal.textIn(enc, state, start, state.pos);
|
|
419
419
|
}, "identifier", {
|
|
420
420
|
_tag: "Identifier",
|
|
421
421
|
encoding: enc
|
|
@@ -451,7 +451,7 @@ const make = (encoding) => {
|
|
|
451
451
|
if (after !== 10) return backtrack(state, "LineEnding", expectedLineEnding, offset);
|
|
452
452
|
}
|
|
453
453
|
state.pos = offset;
|
|
454
|
-
return
|
|
454
|
+
return internal.textIn(enc, state, start, offset);
|
|
455
455
|
}, "tillLineEnding", {
|
|
456
456
|
_tag: "TillLineEnding",
|
|
457
457
|
encoding: enc
|
|
@@ -513,7 +513,7 @@ const make = (encoding) => {
|
|
|
513
513
|
decBigInt: signed.pipe(P.map((s) => BigInt(s.startsWith("+") ? s.slice(1) : s))),
|
|
514
514
|
hexUint: hexDigits.pipe(P.tryMap((s) => overflow(parseInt(s, 16))), P.named("hexUint")),
|
|
515
515
|
float: floatText$1.pipe(P.map(toFloat$1), P.named("float")),
|
|
516
|
-
takeEscaped: (normal, control, escapable) => takeEscapedImpl(normal, matchControl(control), escapable, (state, start) =>
|
|
516
|
+
takeEscaped: (normal, control, escapable) => takeEscapedImpl(normal, matchControl(control), escapable, (state, start) => internal.textIn(enc, state, start, state.pos), internal.firstCodePoint(control), enc),
|
|
517
517
|
escaped: (normal, control, escape) => escapedImpl(normal, matchControl(control), escape, internal.firstCodePoint(control), enc)
|
|
518
518
|
};
|
|
519
519
|
};
|