@thomasfosterau/effect-parse 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +550 -2
- package/dist/Ascii.d.ts +392 -0
- package/dist/Ascii.d.ts.map +1 -0
- package/dist/Ascii.js +610 -0
- package/dist/Ascii.js.map +1 -0
- package/dist/Binary.d.ts +153 -0
- package/dist/Binary.d.ts.map +1 -0
- package/dist/Binary.js +171 -0
- package/dist/Binary.js.map +1 -0
- package/dist/Bits.d.ts +60 -0
- package/dist/Bits.d.ts.map +1 -0
- package/dist/Bits.js +144 -0
- package/dist/Bits.js.map +1 -0
- package/dist/Encoding.d.ts +116 -0
- package/dist/Encoding.d.ts.map +1 -0
- package/dist/Encoding.js +85 -0
- package/dist/Encoding.js.map +1 -0
- package/dist/Expression.d.ts +124 -0
- package/dist/Expression.d.ts.map +1 -0
- package/dist/Expression.js +139 -0
- package/dist/Expression.js.map +1 -0
- package/dist/Input.d.ts +301 -0
- package/dist/Input.d.ts.map +1 -0
- package/dist/Input.js +312 -0
- package/dist/Input.js.map +1 -0
- package/dist/Nom.d.ts +518 -0
- package/dist/Nom.d.ts.map +1 -0
- package/dist/Nom.js +519 -0
- package/dist/Nom.js.map +1 -0
- package/dist/ParseError.d.ts +120 -0
- package/dist/ParseError.d.ts.map +1 -0
- package/dist/ParseError.js +301 -0
- package/dist/ParseError.js.map +1 -0
- package/dist/Parser.d.ts +1312 -0
- package/dist/Parser.d.ts.map +1 -0
- package/dist/Parser.js +1936 -0
- package/dist/Parser.js.map +1 -0
- package/dist/ParserSchema.d.ts +31 -0
- package/dist/ParserSchema.d.ts.map +1 -0
- package/dist/ParserSchema.js +56 -0
- package/dist/ParserSchema.js.map +1 -0
- package/dist/ParserStream.d.ts +127 -0
- package/dist/ParserStream.d.ts.map +1 -0
- package/dist/ParserStream.js +270 -0
- package/dist/ParserStream.js.map +1 -0
- package/dist/Text.d.ts +330 -0
- package/dist/Text.d.ts.map +1 -0
- package/dist/Text.js +529 -0
- package/dist/Text.js.map +1 -0
- package/dist/Token.d.ts +225 -0
- package/dist/Token.d.ts.map +1 -0
- package/dist/Token.js +294 -0
- package/dist/Token.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/compiler/closure.d.ts +25 -0
- package/dist/internal/compiler/closure.d.ts.map +1 -0
- package/dist/internal/compiler/closure.js +1668 -0
- package/dist/internal/compiler/closure.js.map +1 -0
- package/dist/internal/compiler/entries.d.ts +19 -0
- package/dist/internal/compiler/entries.d.ts.map +1 -0
- package/dist/internal/compiler/entries.js +32 -0
- package/dist/internal/compiler/entries.js.map +1 -0
- package/dist/internal/compiler/first.d.ts +33 -0
- package/dist/internal/compiler/first.d.ts.map +1 -0
- package/dist/internal/compiler/first.js +235 -0
- package/dist/internal/compiler/first.js.map +1 -0
- package/dist/internal/compiler/jit.d.ts +20 -0
- package/dist/internal/compiler/jit.d.ts.map +1 -0
- package/dist/internal/compiler/jit.js +1030 -0
- package/dist/internal/compiler/jit.js.map +1 -0
- package/dist/internal/compiler/registry.d.ts +34 -0
- package/dist/internal/compiler/registry.d.ts.map +1 -0
- package/dist/internal/compiler/registry.js +46 -0
- package/dist/internal/compiler/registry.js.map +1 -0
- package/dist/internal/compiler/sets.d.ts +29 -0
- package/dist/internal/compiler/sets.d.ts.map +1 -0
- package/dist/internal/compiler/sets.js +85 -0
- package/dist/internal/compiler/sets.js.map +1 -0
- package/dist/internal/entries.d.ts +27 -0
- package/dist/internal/entries.d.ts.map +1 -0
- package/dist/internal/entries.js +42 -0
- package/dist/internal/entries.js.map +1 -0
- package/dist/internal/node.d.ts +251 -0
- package/dist/internal/node.d.ts.map +1 -0
- package/dist/internal/node.js +73 -0
- package/dist/internal/node.js.map +1 -0
- package/dist/internal/numbers.d.ts +41 -0
- package/dist/internal/numbers.d.ts.map +1 -0
- package/dist/internal/numbers.js +302 -0
- package/dist/internal/numbers.js.map +1 -0
- package/dist/internal/resume.d.ts +39 -0
- package/dist/internal/resume.d.ts.map +1 -0
- package/dist/internal/resume.js +37 -0
- package/dist/internal/resume.js.map +1 -0
- package/dist/internal/text.d.ts +72 -0
- package/dist/internal/text.d.ts.map +1 -0
- package/dist/internal/text.js +391 -0
- package/dist/internal/text.js.map +1 -0
- package/dist/internal/tokens.d.ts +93 -0
- package/dist/internal/tokens.d.ts.map +1 -0
- package/dist/internal/tokens.js +400 -0
- package/dist/internal/tokens.js.map +1 -0
- package/package.json +115 -3
- package/src/Ascii.ts +741 -0
- package/src/Binary.ts +228 -0
- package/src/Bits.ts +192 -0
- package/src/Encoding.ts +128 -0
- package/src/Expression.ts +245 -0
- package/src/Input.ts +429 -0
- package/src/Nom.ts +642 -0
- package/src/ParseError.ts +378 -0
- package/src/Parser.ts +2763 -0
- package/src/ParserSchema.ts +87 -0
- package/src/ParserStream.ts +390 -0
- package/src/Text.ts +757 -0
- package/src/Token.ts +416 -0
- package/src/index.ts +16 -0
- package/src/internal/compiler/closure.ts +1583 -0
- package/src/internal/compiler/entries.ts +36 -0
- package/src/internal/compiler/first.ts +252 -0
- package/src/internal/compiler/jit.ts +1091 -0
- package/src/internal/compiler/registry.ts +79 -0
- package/src/internal/compiler/sets.ts +100 -0
- package/src/internal/entries.ts +51 -0
- package/src/internal/node.ts +207 -0
- package/src/internal/numbers.ts +291 -0
- package/src/internal/resume.ts +55 -0
- package/src/internal/text.ts +411 -0
- package/src/internal/tokens.ts +409 -0
package/dist/Parser.js
ADDED
|
@@ -0,0 +1,1936 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `Parser` data type and its general-purpose combinators.
|
|
3
|
+
*
|
|
4
|
+
* A `Parser<A, E, R, I>` consumes input of type `I` and produces a value of
|
|
5
|
+
* type `A`. It may fail with a `ParseError<E>`, where `E` is the type of
|
|
6
|
+
* user supplied error causes, and it may require services `R` from an Effect
|
|
7
|
+
* `Context`.
|
|
8
|
+
*
|
|
9
|
+
* Under the hood a parser is a function over a mutable cursor (`Input.State`),
|
|
10
|
+
* as in winnow. Failure is cheap and backtracking is a matter of resetting an
|
|
11
|
+
* offset. On the surface the API follows Effect's conventions: parsers are
|
|
12
|
+
* pipeable, combinators are dual (data-first or data-last), and parsers can
|
|
13
|
+
* be written with generators:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
17
|
+
*
|
|
18
|
+
* const point = Parser.gen(function*() {
|
|
19
|
+
* yield* Token.literal("(")
|
|
20
|
+
* const x = yield* Ascii.decInt
|
|
21
|
+
* yield* Token.literal(",")
|
|
22
|
+
* const y = yield* Ascii.decInt
|
|
23
|
+
* yield* Token.literal(")")
|
|
24
|
+
* return { x, y }
|
|
25
|
+
* })
|
|
26
|
+
*
|
|
27
|
+
* Parser.parse(point, "(1,-2)") // Result.succeed({ x: 1, y: -2 })
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @since 0.1.0
|
|
31
|
+
*/
|
|
32
|
+
import * as Context from "effect/Context";
|
|
33
|
+
import * as Effect from "effect/Effect";
|
|
34
|
+
import { dual } from "effect/Function";
|
|
35
|
+
import { NodeInspectSymbol } from "effect/Inspectable";
|
|
36
|
+
import * as Option from "effect/Option";
|
|
37
|
+
import { pipeArguments } from "effect/Pipeable";
|
|
38
|
+
import * as Result from "effect/Result";
|
|
39
|
+
import { Fail, Failure, mergeExpected, mergeFailures, State } from "./Input.js";
|
|
40
|
+
import * as ParseError from "./ParseError.js";
|
|
41
|
+
import * as Compiler from "./internal/compiler/registry.js";
|
|
42
|
+
import * as Entries from "./internal/entries.js";
|
|
43
|
+
import * as Resume from "./internal/resume.js";
|
|
44
|
+
import { bounds, NodeId } from "./internal/node.js";
|
|
45
|
+
// -----------------------------------------------------------------------------
|
|
46
|
+
// Models
|
|
47
|
+
// -----------------------------------------------------------------------------
|
|
48
|
+
/**
|
|
49
|
+
* @since 0.1.0
|
|
50
|
+
* @category type ids
|
|
51
|
+
*/
|
|
52
|
+
export const TypeId = "~effect-parse/Parser";
|
|
53
|
+
// -----------------------------------------------------------------------------
|
|
54
|
+
// Internals
|
|
55
|
+
// -----------------------------------------------------------------------------
|
|
56
|
+
const variance = {
|
|
57
|
+
_A: (_) => _,
|
|
58
|
+
_E: (_) => _,
|
|
59
|
+
_R: (_) => _,
|
|
60
|
+
_I: (_) => { }
|
|
61
|
+
};
|
|
62
|
+
class SingleShotGen {
|
|
63
|
+
self;
|
|
64
|
+
called = false;
|
|
65
|
+
constructor(self) {
|
|
66
|
+
this.self = self;
|
|
67
|
+
}
|
|
68
|
+
next(a) {
|
|
69
|
+
if (this.called)
|
|
70
|
+
return { value: a, done: true };
|
|
71
|
+
this.called = true;
|
|
72
|
+
return { value: this.self, done: false };
|
|
73
|
+
}
|
|
74
|
+
return(a) {
|
|
75
|
+
return { value: a, done: true };
|
|
76
|
+
}
|
|
77
|
+
throw(e) {
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
[Symbol.iterator]() {
|
|
81
|
+
return new SingleShotGen(this.self);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
class ParserImpl {
|
|
85
|
+
step;
|
|
86
|
+
name;
|
|
87
|
+
[TypeId] = variance;
|
|
88
|
+
/** The description used by the compiler; `undefined` for `Opaque`. */
|
|
89
|
+
[NodeId];
|
|
90
|
+
constructor(step, name, node) {
|
|
91
|
+
this.step = step;
|
|
92
|
+
this.name = name;
|
|
93
|
+
this[NodeId] = node;
|
|
94
|
+
}
|
|
95
|
+
pipe() {
|
|
96
|
+
return pipeArguments(this, arguments);
|
|
97
|
+
}
|
|
98
|
+
[Symbol.iterator]() {
|
|
99
|
+
return new SingleShotGen(this);
|
|
100
|
+
}
|
|
101
|
+
toString() {
|
|
102
|
+
return this.name === undefined ? "Parser" : `Parser(${this.name})`;
|
|
103
|
+
}
|
|
104
|
+
toJSON() {
|
|
105
|
+
return { _id: "Parser", name: this.name };
|
|
106
|
+
}
|
|
107
|
+
[NodeInspectSymbol]() {
|
|
108
|
+
return this.toJSON();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Tests whether a value is a `Parser`.
|
|
113
|
+
*
|
|
114
|
+
* @since 0.1.0
|
|
115
|
+
* @category guards
|
|
116
|
+
*/
|
|
117
|
+
export const isParser = (u) => typeof u === "object" && u !== null && TypeId in u;
|
|
118
|
+
const isParserArg = (args) => isParser(args[0]);
|
|
119
|
+
const isTwoParserArgs = (args) => isParser(args[0]) && isParser(args[1]);
|
|
120
|
+
// -----------------------------------------------------------------------------
|
|
121
|
+
// Constructors
|
|
122
|
+
// -----------------------------------------------------------------------------
|
|
123
|
+
/**
|
|
124
|
+
* Creates a parser from a step function over the mutable {@link State}
|
|
125
|
+
* cursor. This is the escape hatch for writing low-level parsers, much like
|
|
126
|
+
* passing a plain function as a parser in winnow.
|
|
127
|
+
*
|
|
128
|
+
* The step function must either return the parsed value, having advanced
|
|
129
|
+
* `state.pos` past the consumed input, or return the result of one of
|
|
130
|
+
* `state.backtrack`, `state.cut`, `state.incomplete`, ... to signal failure.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```ts
|
|
134
|
+
* import { Parser } from "@thomasfosterau/effect-parse"
|
|
135
|
+
*
|
|
136
|
+
* // Parses a single ASCII uppercase letter
|
|
137
|
+
* const upper = Parser.make<string>((state) => {
|
|
138
|
+
* const c = state.input.charCodeAt(state.pos)
|
|
139
|
+
* if (state.pos < state.end && c >= 65 && c <= 90) {
|
|
140
|
+
* state.pos++
|
|
141
|
+
* return String.fromCharCode(c)
|
|
142
|
+
* }
|
|
143
|
+
* return state.pos >= state.end
|
|
144
|
+
* ? state.eoi("Token", ["uppercase letter"], 1)
|
|
145
|
+
* : state.backtrack("Token", ["uppercase letter"])
|
|
146
|
+
* })
|
|
147
|
+
* ```
|
|
148
|
+
*
|
|
149
|
+
* @since 0.1.0
|
|
150
|
+
* @category constructors
|
|
151
|
+
*/
|
|
152
|
+
export const make = (step, name) => new ParserImpl(step, name, undefined);
|
|
153
|
+
/**
|
|
154
|
+
* Creates a parser together with its description, used by the compiler.
|
|
155
|
+
*
|
|
156
|
+
* @internal
|
|
157
|
+
*/
|
|
158
|
+
export const described = (step, name, node) => new ParserImpl(step, name, node);
|
|
159
|
+
const nodeOfParser = (p) => p[NodeId];
|
|
160
|
+
/**
|
|
161
|
+
* Gives a parser a name, used by `toString`.
|
|
162
|
+
*
|
|
163
|
+
* @since 0.1.0
|
|
164
|
+
* @category utils
|
|
165
|
+
*/
|
|
166
|
+
export const named = dual(2, (self, name) => new ParserImpl(self.step, name, nodeOfParser(self)));
|
|
167
|
+
/**
|
|
168
|
+
* A parser that consumes nothing and succeeds with the given value.
|
|
169
|
+
*
|
|
170
|
+
* @since 0.1.0
|
|
171
|
+
* @category constructors
|
|
172
|
+
*/
|
|
173
|
+
export const succeed = (value) => described(() => value, "succeed", { _tag: "Succeed", value });
|
|
174
|
+
/**
|
|
175
|
+
* A parser that consumes nothing and succeeds with the result of a thunk.
|
|
176
|
+
*
|
|
177
|
+
* @since 0.1.0
|
|
178
|
+
* @category constructors
|
|
179
|
+
*/
|
|
180
|
+
export const sync = (evaluate) => described(() => evaluate(), "sync", { _tag: "Sync", evaluate });
|
|
181
|
+
/**
|
|
182
|
+
* A parser that consumes nothing and succeeds with `undefined` (winnow's
|
|
183
|
+
* `empty`, nom's `success(())`).
|
|
184
|
+
*
|
|
185
|
+
* @since 0.1.0
|
|
186
|
+
* @category constructors
|
|
187
|
+
*/
|
|
188
|
+
export const empty = described(() => undefined, "empty", {
|
|
189
|
+
_tag: "Succeed",
|
|
190
|
+
value: undefined
|
|
191
|
+
});
|
|
192
|
+
/**
|
|
193
|
+
* Alias of {@link empty}, following Effect's `Effect.void`.
|
|
194
|
+
*
|
|
195
|
+
* @since 0.1.0
|
|
196
|
+
* @category constructors
|
|
197
|
+
*/
|
|
198
|
+
export const void_ = empty;
|
|
199
|
+
export {
|
|
200
|
+
/**
|
|
201
|
+
* @since 0.1.0
|
|
202
|
+
* @category constructors
|
|
203
|
+
*/
|
|
204
|
+
void_ as void };
|
|
205
|
+
/**
|
|
206
|
+
* A parser that always fails (backtracks) with the given user error as its
|
|
207
|
+
* cause.
|
|
208
|
+
*
|
|
209
|
+
* @since 0.1.0
|
|
210
|
+
* @category constructors
|
|
211
|
+
*/
|
|
212
|
+
export const fail = (error) => described((state) => state.failCause("Backtrack", "Fail", error), "fail", failBacktrack);
|
|
213
|
+
const failBacktrack = { _tag: "Fail", mode: "Backtrack" };
|
|
214
|
+
/**
|
|
215
|
+
* A parser that always fails (backtracks) without a cause. This is winnow's
|
|
216
|
+
* `fail` and nom's `fail()`.
|
|
217
|
+
*
|
|
218
|
+
* @since 0.1.0
|
|
219
|
+
* @category constructors
|
|
220
|
+
*/
|
|
221
|
+
export const reject = described((state) => state.backtrack("Fail"), "reject", failBacktrack);
|
|
222
|
+
/**
|
|
223
|
+
* A parser that always fails with a message.
|
|
224
|
+
*
|
|
225
|
+
* @since 0.1.0
|
|
226
|
+
* @category constructors
|
|
227
|
+
*/
|
|
228
|
+
export const failMessage = (message) => described((state) => state.failMessage("Backtrack", "Fail", message), "failMessage", failBacktrack);
|
|
229
|
+
/**
|
|
230
|
+
* A placeholder parser that fails with an unrecoverable error (winnow's
|
|
231
|
+
* `todo`).
|
|
232
|
+
*
|
|
233
|
+
* @since 0.1.0
|
|
234
|
+
* @category constructors
|
|
235
|
+
*/
|
|
236
|
+
export const todo = described((state) => state.failMessage("Cut", "Assert", "`todo` parser reached"), "todo", { _tag: "Fail", mode: "Cut" });
|
|
237
|
+
/**
|
|
238
|
+
* Lazily constructs a parser, which is needed to define recursive grammars.
|
|
239
|
+
* The thunk is evaluated once, on first use.
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* ```ts
|
|
243
|
+
* import { Parser, Token } from "@thomasfosterau/effect-parse"
|
|
244
|
+
*
|
|
245
|
+
* type Nested = ReadonlyArray<Nested>
|
|
246
|
+
* const nested: Parser.Parser<Nested> = Parser.delimited(
|
|
247
|
+
* Token.literal("["),
|
|
248
|
+
* Parser.repeat(Parser.suspend(() => nested)),
|
|
249
|
+
* Token.literal("]")
|
|
250
|
+
* )
|
|
251
|
+
* ```
|
|
252
|
+
*
|
|
253
|
+
* @since 0.1.0
|
|
254
|
+
* @category constructors
|
|
255
|
+
*/
|
|
256
|
+
export const suspend = (evaluate) => {
|
|
257
|
+
let parser;
|
|
258
|
+
return described((state) => (parser ??= evaluate()).step(state), "suspend", {
|
|
259
|
+
_tag: "Suspend",
|
|
260
|
+
resolve: () => parser ??= evaluate()
|
|
261
|
+
});
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* The current offset into the input (winnow's `Location`).
|
|
265
|
+
*
|
|
266
|
+
* @since 0.1.0
|
|
267
|
+
* @category constructors
|
|
268
|
+
*/
|
|
269
|
+
export const location = described((state) => state.pos, "location", {
|
|
270
|
+
_tag: "Location"
|
|
271
|
+
});
|
|
272
|
+
/**
|
|
273
|
+
* Succeeds (with `undefined`) only at the end of the input; nom's and
|
|
274
|
+
* winnow's `eof`. On partial input, reaching the end of the available data
|
|
275
|
+
* is reported as `Incomplete` since more data may follow.
|
|
276
|
+
*
|
|
277
|
+
* @since 0.1.0
|
|
278
|
+
* @category constructors
|
|
279
|
+
*/
|
|
280
|
+
export const eof = described((state) => {
|
|
281
|
+
if (state.pos < state.end)
|
|
282
|
+
return state.backtrack("Eof", expectedEof);
|
|
283
|
+
if (state.partial)
|
|
284
|
+
return state.incomplete(1, expectedEof);
|
|
285
|
+
return undefined;
|
|
286
|
+
}, "eof", { _tag: "Eof" });
|
|
287
|
+
const expectedEof = ["end of input"];
|
|
288
|
+
// -----------------------------------------------------------------------------
|
|
289
|
+
// Mapping
|
|
290
|
+
// -----------------------------------------------------------------------------
|
|
291
|
+
/**
|
|
292
|
+
* Transforms the output of a parser.
|
|
293
|
+
*
|
|
294
|
+
* @since 0.1.0
|
|
295
|
+
* @category mapping
|
|
296
|
+
*/
|
|
297
|
+
export const map = dual(2, (self, f) => {
|
|
298
|
+
const step = self.step;
|
|
299
|
+
return described((state) => {
|
|
300
|
+
const a = step(state);
|
|
301
|
+
return a === Fail ? Fail : f(a);
|
|
302
|
+
}, self.name, { _tag: "Map", self, f });
|
|
303
|
+
});
|
|
304
|
+
/**
|
|
305
|
+
* Builds an object from the `[key, value]` entries a parser returns, as
|
|
306
|
+
* `Object.fromEntries` does: `fromEntries(self)` is
|
|
307
|
+
* `map(self, Object.fromEntries)`.
|
|
308
|
+
*
|
|
309
|
+
* Compiled parsers build the object directly when `self` repeats a pair
|
|
310
|
+
* (`separated` or `repeat` of `separatedPair` or a two-element `seq`,
|
|
311
|
+
* possibly inside `preceded`, `terminated`, `delimited` or `cut`), without
|
|
312
|
+
* the pairs and the array. They do the same for `map(Object.fromEntries)`.
|
|
313
|
+
*
|
|
314
|
+
* @example
|
|
315
|
+
* ```ts
|
|
316
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
317
|
+
*
|
|
318
|
+
* const entry = Parser.separatedPair(Ascii.alpha1, Token.literal("="), Ascii.decUint)
|
|
319
|
+
* const record = Parser.fromEntries(Parser.separated(entry, Token.literal(",")))
|
|
320
|
+
* Parser.parse(record, "a=1,b=2") // Result.succeed({ a: 1, b: 2 })
|
|
321
|
+
* ```
|
|
322
|
+
*
|
|
323
|
+
* @since 0.2.0
|
|
324
|
+
* @category mapping
|
|
325
|
+
*/
|
|
326
|
+
export const fromEntries = (self) => map(self, Entries.fromEntries);
|
|
327
|
+
/**
|
|
328
|
+
* Replaces the output of a parser with a constant (winnow's `value`, nom's
|
|
329
|
+
* `value`).
|
|
330
|
+
*
|
|
331
|
+
* @since 0.1.0
|
|
332
|
+
* @category mapping
|
|
333
|
+
*/
|
|
334
|
+
export const as = dual(2, (self, value) => {
|
|
335
|
+
const step = self.step;
|
|
336
|
+
return described((state) => step(state) === Fail ? Fail : value, self.name, { _tag: "As", self, value });
|
|
337
|
+
});
|
|
338
|
+
/**
|
|
339
|
+
* Discards the output of a parser (winnow's `void`).
|
|
340
|
+
*
|
|
341
|
+
* @since 0.1.0
|
|
342
|
+
* @category mapping
|
|
343
|
+
*/
|
|
344
|
+
export const asVoid = (self) => as(self, undefined);
|
|
345
|
+
/**
|
|
346
|
+
* Replaces the output of a parser with `Option.some(output)`.
|
|
347
|
+
*
|
|
348
|
+
* @since 0.1.0
|
|
349
|
+
* @category mapping
|
|
350
|
+
*/
|
|
351
|
+
export const asSome = (self) => map(self, Option.some);
|
|
352
|
+
/**
|
|
353
|
+
* Runs a side effect on the output of a parser, keeping the output.
|
|
354
|
+
*
|
|
355
|
+
* @since 0.1.0
|
|
356
|
+
* @category mapping
|
|
357
|
+
*/
|
|
358
|
+
export const tap = dual(2, (self, f) => {
|
|
359
|
+
const step = self.step;
|
|
360
|
+
return described((state) => {
|
|
361
|
+
const a = step(state);
|
|
362
|
+
if (a !== Fail)
|
|
363
|
+
f(a);
|
|
364
|
+
return a;
|
|
365
|
+
}, self.name, { _tag: "Tap", self, f });
|
|
366
|
+
});
|
|
367
|
+
/**
|
|
368
|
+
* Uses the output of a parser to choose the parser that consumes the rest
|
|
369
|
+
* of the input (winnow's `flat_map`, nom's `flat_map`).
|
|
370
|
+
*
|
|
371
|
+
* @since 0.1.0
|
|
372
|
+
* @category sequencing
|
|
373
|
+
*/
|
|
374
|
+
export const flatMap = dual(2, (self, f) => {
|
|
375
|
+
const step = self.step;
|
|
376
|
+
return described((state) => {
|
|
377
|
+
const a = step(state);
|
|
378
|
+
return a === Fail ? Fail : f(a).step(state);
|
|
379
|
+
}, undefined, { _tag: "FlatMap", self, f });
|
|
380
|
+
});
|
|
381
|
+
/**
|
|
382
|
+
* Applies a second parser to the *output* of the first (winnow's
|
|
383
|
+
* `and_then`, nom's `map_parser`). The output of the first parser must
|
|
384
|
+
* itself be an input, e.g. a slice produced by {@link taken} or
|
|
385
|
+
* `Token.take`.
|
|
386
|
+
*
|
|
387
|
+
* Error offsets reported by the inner parser are translated relative to the
|
|
388
|
+
* start of the outer parser.
|
|
389
|
+
*
|
|
390
|
+
* @example
|
|
391
|
+
* ```ts
|
|
392
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
393
|
+
*
|
|
394
|
+
* // Take exactly 4 characters, then require them all to be digits
|
|
395
|
+
* const year = Token.take(4).pipe(Parser.mapParser(Parser.allConsuming(Ascii.decUint)))
|
|
396
|
+
* ```
|
|
397
|
+
*
|
|
398
|
+
* @since 0.1.0
|
|
399
|
+
* @category sequencing
|
|
400
|
+
*/
|
|
401
|
+
export const mapParser = dual(2, (self, inner) => {
|
|
402
|
+
const step = self.step;
|
|
403
|
+
return make((state) => {
|
|
404
|
+
const start = state.pos;
|
|
405
|
+
const a = step(state);
|
|
406
|
+
if (a === Fail)
|
|
407
|
+
return Fail;
|
|
408
|
+
const sub = new State(a, { context: state.context });
|
|
409
|
+
sub.tracer = state.tracer;
|
|
410
|
+
sub.depth = state.depth;
|
|
411
|
+
sub.recovered = state.recovered;
|
|
412
|
+
const b = inner.step(sub);
|
|
413
|
+
if (b === Fail) {
|
|
414
|
+
const f = sub.failure;
|
|
415
|
+
if (sub.encoding !== undefined)
|
|
416
|
+
state.encoding = sub.encoding;
|
|
417
|
+
// The inner input is usually a slice ending where the outer parser stopped
|
|
418
|
+
const base = Math.max(start, state.pos - a.length);
|
|
419
|
+
const offset = Math.min(base + f.offset, state.pos);
|
|
420
|
+
return state.failWith(sub.mode === "Incomplete" ? "Backtrack" : sub.mode, new Failure(offset, f.kind, f.expected, f.context, f.hasCause, f.cause, f.message, 0));
|
|
421
|
+
}
|
|
422
|
+
return b;
|
|
423
|
+
});
|
|
424
|
+
});
|
|
425
|
+
/**
|
|
426
|
+
* Transforms the output of a parser with a function that may fail with a
|
|
427
|
+
* `Result` (winnow's `try_map`, nom's `map_res`). On failure the parser
|
|
428
|
+
* backtracks to where it started and the error becomes the `cause` of the
|
|
429
|
+
* `ParseError`.
|
|
430
|
+
*
|
|
431
|
+
* @since 0.1.0
|
|
432
|
+
* @category mapping
|
|
433
|
+
*/
|
|
434
|
+
export const tryMap = dual(2, (self, f) => {
|
|
435
|
+
const step = self.step;
|
|
436
|
+
return described((state) => {
|
|
437
|
+
const start = state.pos;
|
|
438
|
+
const a = step(state);
|
|
439
|
+
if (a === Fail)
|
|
440
|
+
return Fail;
|
|
441
|
+
const r = f(a);
|
|
442
|
+
if (Result.isSuccess(r))
|
|
443
|
+
return r.success;
|
|
444
|
+
state.pos = start;
|
|
445
|
+
return state.failCause("Backtrack", "Verify", r.failure);
|
|
446
|
+
}, self.name, { _tag: "TryMap", self, f });
|
|
447
|
+
});
|
|
448
|
+
/**
|
|
449
|
+
* Like {@link tryMap}, but the function may throw. Thrown values become the
|
|
450
|
+
* `cause` of the error.
|
|
451
|
+
*
|
|
452
|
+
* @since 0.1.0
|
|
453
|
+
* @category mapping
|
|
454
|
+
*/
|
|
455
|
+
export const tryMapUnknown = dual(2, (self, f) => tryMap(self, (a) => {
|
|
456
|
+
try {
|
|
457
|
+
return Result.succeed(f(a));
|
|
458
|
+
}
|
|
459
|
+
catch (e) {
|
|
460
|
+
return Result.fail(e);
|
|
461
|
+
}
|
|
462
|
+
}));
|
|
463
|
+
/**
|
|
464
|
+
* Transforms the output of a parser with a function returning an `Option`;
|
|
465
|
+
* `None` makes the parser backtrack (winnow's `verify_map`, nom's
|
|
466
|
+
* `map_opt`).
|
|
467
|
+
*
|
|
468
|
+
* @since 0.1.0
|
|
469
|
+
* @category filtering
|
|
470
|
+
*/
|
|
471
|
+
export const filterMap = dual(2, (self, f) => {
|
|
472
|
+
const step = self.step;
|
|
473
|
+
return described((state) => {
|
|
474
|
+
const start = state.pos;
|
|
475
|
+
const a = step(state);
|
|
476
|
+
if (a === Fail)
|
|
477
|
+
return Fail;
|
|
478
|
+
const o = f(a);
|
|
479
|
+
if (Option.isSome(o))
|
|
480
|
+
return o.value;
|
|
481
|
+
state.pos = start;
|
|
482
|
+
return state.backtrack("Verify");
|
|
483
|
+
}, self.name, { _tag: "FilterMap", self, f });
|
|
484
|
+
});
|
|
485
|
+
/**
|
|
486
|
+
* Keeps the output of a parser only if it satisfies a predicate, otherwise
|
|
487
|
+
* backtracks (winnow's and nom's `verify`).
|
|
488
|
+
*
|
|
489
|
+
* @since 0.1.0
|
|
490
|
+
* @category filtering
|
|
491
|
+
*/
|
|
492
|
+
export const filter = dual(2, (self, predicate) => {
|
|
493
|
+
const step = self.step;
|
|
494
|
+
return described((state) => {
|
|
495
|
+
const start = state.pos;
|
|
496
|
+
const a = step(state);
|
|
497
|
+
if (a === Fail)
|
|
498
|
+
return Fail;
|
|
499
|
+
if (predicate(a))
|
|
500
|
+
return a;
|
|
501
|
+
state.pos = start;
|
|
502
|
+
return state.backtrack("Verify");
|
|
503
|
+
}, self.name, { _tag: "Filter", self, predicate });
|
|
504
|
+
});
|
|
505
|
+
/**
|
|
506
|
+
* Keeps the output of a parser only if it satisfies a predicate, otherwise
|
|
507
|
+
* backtracks with the given user error.
|
|
508
|
+
*
|
|
509
|
+
* @since 0.1.0
|
|
510
|
+
* @category filtering
|
|
511
|
+
*/
|
|
512
|
+
export const filterOrFail = dual(3, (self, predicate, orFailWith) => {
|
|
513
|
+
const step = self.step;
|
|
514
|
+
return described((state) => {
|
|
515
|
+
const start = state.pos;
|
|
516
|
+
const a = step(state);
|
|
517
|
+
if (a === Fail)
|
|
518
|
+
return Fail;
|
|
519
|
+
if (predicate(a))
|
|
520
|
+
return a;
|
|
521
|
+
state.pos = start;
|
|
522
|
+
return state.failCause("Backtrack", "Verify", orFailWith(a));
|
|
523
|
+
}, self.name, { _tag: "Filter", self, predicate });
|
|
524
|
+
});
|
|
525
|
+
// -----------------------------------------------------------------------------
|
|
526
|
+
// Consumed input
|
|
527
|
+
// -----------------------------------------------------------------------------
|
|
528
|
+
/**
|
|
529
|
+
* Returns the slice of input consumed by a parser instead of its output
|
|
530
|
+
* (winnow's `take`, nom's `recognize`).
|
|
531
|
+
*
|
|
532
|
+
* @since 0.1.0
|
|
533
|
+
* @category consumed input
|
|
534
|
+
*/
|
|
535
|
+
export const taken = (self) => {
|
|
536
|
+
const step = self.step;
|
|
537
|
+
return described((state) => {
|
|
538
|
+
const start = state.pos;
|
|
539
|
+
return step(state) === Fail ? Fail : state.slice(start, state.pos);
|
|
540
|
+
}, self.name, { _tag: "Taken", self, encoding: undefined });
|
|
541
|
+
};
|
|
542
|
+
/**
|
|
543
|
+
* Returns both the output of a parser and the slice of input it consumed
|
|
544
|
+
* (winnow's `with_taken`; nom's `consumed` returns them in the other order).
|
|
545
|
+
*
|
|
546
|
+
* @since 0.1.0
|
|
547
|
+
* @category consumed input
|
|
548
|
+
*/
|
|
549
|
+
export const withTaken = (self) => {
|
|
550
|
+
const step = self.step;
|
|
551
|
+
return described((state) => {
|
|
552
|
+
const start = state.pos;
|
|
553
|
+
const a = step(state);
|
|
554
|
+
return a === Fail ? Fail : [a, state.slice(start, state.pos)];
|
|
555
|
+
}, self.name, { _tag: "WithTaken", self });
|
|
556
|
+
};
|
|
557
|
+
/**
|
|
558
|
+
* Returns the span (`[start, end)` offsets) consumed by a parser instead of
|
|
559
|
+
* its output (winnow's `span`).
|
|
560
|
+
*
|
|
561
|
+
* @since 0.1.0
|
|
562
|
+
* @category consumed input
|
|
563
|
+
*/
|
|
564
|
+
export const span = (self) => {
|
|
565
|
+
const step = self.step;
|
|
566
|
+
return described((state) => {
|
|
567
|
+
const start = state.pos;
|
|
568
|
+
return step(state) === Fail ? Fail : { start, end: state.pos };
|
|
569
|
+
}, self.name, { _tag: "Span", self });
|
|
570
|
+
};
|
|
571
|
+
/**
|
|
572
|
+
* Returns both the output of a parser and the span it consumed (winnow's
|
|
573
|
+
* `with_span`).
|
|
574
|
+
*
|
|
575
|
+
* @since 0.1.0
|
|
576
|
+
* @category consumed input
|
|
577
|
+
*/
|
|
578
|
+
export const withSpan = (self) => {
|
|
579
|
+
const step = self.step;
|
|
580
|
+
return described((state) => {
|
|
581
|
+
const start = state.pos;
|
|
582
|
+
const a = step(state);
|
|
583
|
+
return a === Fail ? Fail : [a, { start, end: state.pos }];
|
|
584
|
+
}, self.name, { _tag: "WithSpan", self });
|
|
585
|
+
};
|
|
586
|
+
// -----------------------------------------------------------------------------
|
|
587
|
+
// Error management
|
|
588
|
+
// -----------------------------------------------------------------------------
|
|
589
|
+
const changeMode = (self, from, to) => {
|
|
590
|
+
const step = self.step;
|
|
591
|
+
return described((state) => {
|
|
592
|
+
const a = step(state);
|
|
593
|
+
if (a === Fail && state.mode === from)
|
|
594
|
+
state.mode = to;
|
|
595
|
+
return a;
|
|
596
|
+
}, self.name, { _tag: "Mode", self, from, to });
|
|
597
|
+
};
|
|
598
|
+
/**
|
|
599
|
+
* Commits to the current branch: recoverable failures of the parser become
|
|
600
|
+
* unrecoverable, so enclosing `alt`, `opt`, `repeat`, ... do not try
|
|
601
|
+
* alternatives (winnow's `cut_err`, nom's `cut`).
|
|
602
|
+
*
|
|
603
|
+
* @example
|
|
604
|
+
* ```ts
|
|
605
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
606
|
+
*
|
|
607
|
+
* // Once we have seen "-", a number must follow
|
|
608
|
+
* const negative = Parser.preceded(Token.literal("-"), Parser.cut(Ascii.decUint))
|
|
609
|
+
* ```
|
|
610
|
+
*
|
|
611
|
+
* @since 0.1.0
|
|
612
|
+
* @category error management
|
|
613
|
+
*/
|
|
614
|
+
export const cut = (self) => changeMode(self, "Backtrack", "Cut");
|
|
615
|
+
/**
|
|
616
|
+
* Turns unrecoverable failures back into recoverable ones (winnow's
|
|
617
|
+
* `backtrack_err`).
|
|
618
|
+
*
|
|
619
|
+
* @since 0.1.0
|
|
620
|
+
* @category error management
|
|
621
|
+
*/
|
|
622
|
+
export const backtrack = (self) => changeMode(self, "Cut", "Backtrack");
|
|
623
|
+
/**
|
|
624
|
+
* Turns `Incomplete` failures into recoverable ones, treating the input as
|
|
625
|
+
* complete for this parser (winnow's `complete_err`, nom's `complete`).
|
|
626
|
+
*
|
|
627
|
+
* @since 0.1.0
|
|
628
|
+
* @category error management
|
|
629
|
+
*/
|
|
630
|
+
export const complete = (self) => {
|
|
631
|
+
const step = self.step;
|
|
632
|
+
return described((state) => {
|
|
633
|
+
const start = state.pos;
|
|
634
|
+
const a = step(state);
|
|
635
|
+
if (a === Fail && state.mode === "Incomplete") {
|
|
636
|
+
state.pos = start;
|
|
637
|
+
return state.backtrack("Complete");
|
|
638
|
+
}
|
|
639
|
+
return a;
|
|
640
|
+
}, self.name, { _tag: "Mode", self, from: "Incomplete", to: "Backtrack" });
|
|
641
|
+
};
|
|
642
|
+
/**
|
|
643
|
+
* Adds a context label to failures of a parser (winnow's
|
|
644
|
+
* `context(StrContext::Label(..))`, nom's `context`). Labels are rendered as
|
|
645
|
+
* "while parsing <label>" in the error message.
|
|
646
|
+
*
|
|
647
|
+
* @since 0.1.0
|
|
648
|
+
* @category error management
|
|
649
|
+
*/
|
|
650
|
+
export const context = dual(2, (self, label) => {
|
|
651
|
+
const step = self.step;
|
|
652
|
+
return described((state) => {
|
|
653
|
+
const a = step(state);
|
|
654
|
+
if (a === Fail && state.mode !== "Incomplete") {
|
|
655
|
+
const f = state.failure;
|
|
656
|
+
state.replaceFailure(new Failure(f.offset, f.kind, f.expected, [...f.context, label], f.hasCause, f.cause, f.message, f.needed));
|
|
657
|
+
}
|
|
658
|
+
return a;
|
|
659
|
+
}, self.name ?? label, { _tag: "Context", self, label });
|
|
660
|
+
});
|
|
661
|
+
/**
|
|
662
|
+
* Names what a parser expects. When the parser fails without consuming any
|
|
663
|
+
* input, its expectations are replaced with `description`, so a failure is
|
|
664
|
+
* reported as `expected <description>` rather than in terms of the parser's
|
|
665
|
+
* internals (Parsec's `<?>`, winnow's `StrContext::Expected`).
|
|
666
|
+
*
|
|
667
|
+
* @since 0.1.0
|
|
668
|
+
* @category error management
|
|
669
|
+
*/
|
|
670
|
+
export const expected = dual(2, (self, description) => {
|
|
671
|
+
const step = self.step;
|
|
672
|
+
const desc = [description];
|
|
673
|
+
return described((state) => {
|
|
674
|
+
const start = state.pos;
|
|
675
|
+
const hintOffset = state.hintOffset;
|
|
676
|
+
const hintExpected = state.hintExpected;
|
|
677
|
+
const a = step(state);
|
|
678
|
+
if (a === Fail && state.failure.offset === start) {
|
|
679
|
+
const f = state.failure;
|
|
680
|
+
const expected = hintOffset === start ? mergeExpected(hintExpected, desc) : desc;
|
|
681
|
+
state.replaceFailure(new Failure(f.offset, f.kind, expected, f.context, f.hasCause, f.cause, f.message, f.needed));
|
|
682
|
+
}
|
|
683
|
+
return a;
|
|
684
|
+
}, description, { _tag: "Expected", self, description });
|
|
685
|
+
});
|
|
686
|
+
/**
|
|
687
|
+
* Transforms the user error (cause) of a parser's failures.
|
|
688
|
+
*
|
|
689
|
+
* @since 0.1.0
|
|
690
|
+
* @category error management
|
|
691
|
+
*/
|
|
692
|
+
export const mapError = dual(2, (self, f) => {
|
|
693
|
+
const step = self.step;
|
|
694
|
+
return described((state) => {
|
|
695
|
+
const a = step(state);
|
|
696
|
+
if (a === Fail && state.failure.hasCause) {
|
|
697
|
+
const x = state.failure;
|
|
698
|
+
state.replaceFailure(new Failure(x.offset, x.kind, x.expected, x.context, true, f(x.cause), x.message, x.needed));
|
|
699
|
+
}
|
|
700
|
+
return a;
|
|
701
|
+
}, self.name, { _tag: "MapError", self });
|
|
702
|
+
});
|
|
703
|
+
/**
|
|
704
|
+
* Replaces any failure of a parser with the given user error, keeping the
|
|
705
|
+
* failure's position and mode.
|
|
706
|
+
*
|
|
707
|
+
* @since 0.1.0
|
|
708
|
+
* @category error management
|
|
709
|
+
*/
|
|
710
|
+
export const orFail = dual(2, (self, error) => {
|
|
711
|
+
const step = self.step;
|
|
712
|
+
return described((state) => {
|
|
713
|
+
const start = state.pos;
|
|
714
|
+
const a = step(state);
|
|
715
|
+
if (a === Fail && state.mode !== "Incomplete") {
|
|
716
|
+
const x = state.failure;
|
|
717
|
+
state.replaceFailure(new Failure(start, x.kind, [], x.context, true, error(), undefined, 0));
|
|
718
|
+
}
|
|
719
|
+
return a;
|
|
720
|
+
}, self.name, { _tag: "OrFail", self });
|
|
721
|
+
});
|
|
722
|
+
/**
|
|
723
|
+
* If the parser fails recoverably, tries `that` from the same position.
|
|
724
|
+
* `p.pipe(Parser.orElse(() => q))` is equivalent to `Parser.alt(p, q)`.
|
|
725
|
+
*
|
|
726
|
+
* @since 0.1.0
|
|
727
|
+
* @category error management
|
|
728
|
+
*/
|
|
729
|
+
export const orElse = dual(2, (self, that) => alt(self, suspend(that)));
|
|
730
|
+
/**
|
|
731
|
+
* If the parser fails recoverably, succeeds with the given value without
|
|
732
|
+
* consuming input.
|
|
733
|
+
*
|
|
734
|
+
* @since 0.1.0
|
|
735
|
+
* @category error management
|
|
736
|
+
*/
|
|
737
|
+
export const orElseSucceed = dual(2, (self, value) => {
|
|
738
|
+
const step = self.step;
|
|
739
|
+
return described((state) => {
|
|
740
|
+
const start = state.pos;
|
|
741
|
+
const a = step(state);
|
|
742
|
+
if (a !== Fail)
|
|
743
|
+
return a;
|
|
744
|
+
if (state.mode !== "Backtrack")
|
|
745
|
+
return Fail;
|
|
746
|
+
recover(state, start);
|
|
747
|
+
return value();
|
|
748
|
+
}, self.name, { _tag: "OrElseSucceed", self, value });
|
|
749
|
+
});
|
|
750
|
+
/** Rewinds after a recoverable failure, remembering it as a hint. */
|
|
751
|
+
const recover = (state, start) => {
|
|
752
|
+
state.pos = start;
|
|
753
|
+
const f = state.failure;
|
|
754
|
+
if (f.offset === start) {
|
|
755
|
+
state.hintOffset = start;
|
|
756
|
+
state.hintExpected = f.expected;
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
// -----------------------------------------------------------------------------
|
|
760
|
+
// Control
|
|
761
|
+
// -----------------------------------------------------------------------------
|
|
762
|
+
/**
|
|
763
|
+
* Makes a parser optional: returns `Option.none()` without consuming input if
|
|
764
|
+
* it fails recoverably (winnow's and nom's `opt`).
|
|
765
|
+
*
|
|
766
|
+
* @since 0.1.0
|
|
767
|
+
* @category control
|
|
768
|
+
*/
|
|
769
|
+
export const opt = (self) => {
|
|
770
|
+
const step = self.step;
|
|
771
|
+
return described((state) => {
|
|
772
|
+
const start = state.pos;
|
|
773
|
+
const a = step(state);
|
|
774
|
+
if (a !== Fail)
|
|
775
|
+
return Option.some(a);
|
|
776
|
+
if (state.mode !== "Backtrack")
|
|
777
|
+
return Fail;
|
|
778
|
+
recover(state, start);
|
|
779
|
+
return Option.none();
|
|
780
|
+
}, self.name, { _tag: "Opt", self });
|
|
781
|
+
};
|
|
782
|
+
/**
|
|
783
|
+
* Like {@link opt}, but returns `undefined` instead of `None`.
|
|
784
|
+
*
|
|
785
|
+
* @since 0.1.0
|
|
786
|
+
* @category control
|
|
787
|
+
*/
|
|
788
|
+
export const optional = (self) => orElseSucceed(self, () => undefined);
|
|
789
|
+
/**
|
|
790
|
+
* Runs the parser only if `condition` holds, otherwise succeeds with
|
|
791
|
+
* `Option.none()` (winnow's and nom's `cond`).
|
|
792
|
+
*
|
|
793
|
+
* @since 0.1.0
|
|
794
|
+
* @category control
|
|
795
|
+
*/
|
|
796
|
+
export const cond = (condition, self) => condition ? asSome(self) : succeed(Option.none());
|
|
797
|
+
/**
|
|
798
|
+
* Runs a parser without consuming input (winnow's and nom's `peek`).
|
|
799
|
+
*
|
|
800
|
+
* @since 0.1.0
|
|
801
|
+
* @category control
|
|
802
|
+
*/
|
|
803
|
+
export const peek = (self) => {
|
|
804
|
+
const step = self.step;
|
|
805
|
+
return described((state) => {
|
|
806
|
+
const start = state.pos;
|
|
807
|
+
const hintOffset = state.hintOffset;
|
|
808
|
+
const hintExpected = state.hintExpected;
|
|
809
|
+
const a = step(state);
|
|
810
|
+
if (a !== Fail) {
|
|
811
|
+
state.pos = start;
|
|
812
|
+
state.hintOffset = hintOffset;
|
|
813
|
+
state.hintExpected = hintExpected;
|
|
814
|
+
}
|
|
815
|
+
return a;
|
|
816
|
+
}, self.name, { _tag: "Peek", self });
|
|
817
|
+
};
|
|
818
|
+
/**
|
|
819
|
+
* Succeeds, without consuming input, only if the parser fails recoverably
|
|
820
|
+
* (winnow's and nom's `not`).
|
|
821
|
+
*
|
|
822
|
+
* @since 0.1.0
|
|
823
|
+
* @category control
|
|
824
|
+
*/
|
|
825
|
+
export const not = (self) => {
|
|
826
|
+
const step = self.step;
|
|
827
|
+
return described((state) => {
|
|
828
|
+
const start = state.pos;
|
|
829
|
+
const hintOffset = state.hintOffset;
|
|
830
|
+
const hintExpected = state.hintExpected;
|
|
831
|
+
const a = step(state);
|
|
832
|
+
if (a !== Fail) {
|
|
833
|
+
state.pos = start;
|
|
834
|
+
return state.backtrack("Not");
|
|
835
|
+
}
|
|
836
|
+
if (state.mode !== "Backtrack")
|
|
837
|
+
return Fail;
|
|
838
|
+
state.pos = start;
|
|
839
|
+
state.hintOffset = hintOffset;
|
|
840
|
+
state.hintExpected = hintExpected;
|
|
841
|
+
return undefined;
|
|
842
|
+
}, self.name, { _tag: "Not", self });
|
|
843
|
+
};
|
|
844
|
+
/**
|
|
845
|
+
* Requires the parser to consume the whole input (nom's `all_consuming`).
|
|
846
|
+
*
|
|
847
|
+
* @since 0.1.0
|
|
848
|
+
* @category control
|
|
849
|
+
*/
|
|
850
|
+
export const allConsuming = (self) => terminated(self, eof);
|
|
851
|
+
// -----------------------------------------------------------------------------
|
|
852
|
+
// Sequencing
|
|
853
|
+
// -----------------------------------------------------------------------------
|
|
854
|
+
/**
|
|
855
|
+
* Runs parsers in sequence, collecting their outputs in a tuple (winnow's
|
|
856
|
+
* and nom's tuple parsers, winnow's `seq!`).
|
|
857
|
+
*
|
|
858
|
+
* @since 0.1.0
|
|
859
|
+
* @category sequencing
|
|
860
|
+
*/
|
|
861
|
+
export const seq = (...parsers) => {
|
|
862
|
+
const steps = parsers.map((p) => p.step);
|
|
863
|
+
const n = steps.length;
|
|
864
|
+
return described((state) => {
|
|
865
|
+
const out = new Array(n);
|
|
866
|
+
for (let i = 0; i < n; i++) {
|
|
867
|
+
const a = steps[i](state);
|
|
868
|
+
if (a === Fail)
|
|
869
|
+
return Fail;
|
|
870
|
+
out[i] = a;
|
|
871
|
+
}
|
|
872
|
+
return out;
|
|
873
|
+
}, "seq", { _tag: "Seq", parsers, output: "tuple" });
|
|
874
|
+
};
|
|
875
|
+
/**
|
|
876
|
+
* Runs a record of parsers in sequence (in key order), collecting their
|
|
877
|
+
* outputs in a record. This is the Effect counterpart to winnow's
|
|
878
|
+
* `seq!(Struct { .. })`.
|
|
879
|
+
*
|
|
880
|
+
* @since 0.1.0
|
|
881
|
+
* @category sequencing
|
|
882
|
+
*/
|
|
883
|
+
export const struct = (fields) => {
|
|
884
|
+
const keys = Object.keys(fields);
|
|
885
|
+
const steps = keys.map((k) => fields[k].step);
|
|
886
|
+
const n = keys.length;
|
|
887
|
+
return described((state) => {
|
|
888
|
+
const out = {};
|
|
889
|
+
for (let i = 0; i < n; i++) {
|
|
890
|
+
const a = steps[i](state);
|
|
891
|
+
if (a === Fail)
|
|
892
|
+
return Fail;
|
|
893
|
+
out[keys[i]] = a;
|
|
894
|
+
}
|
|
895
|
+
return out;
|
|
896
|
+
}, "struct", { _tag: "Struct", keys, parsers: keys.map((k) => fields[k]) });
|
|
897
|
+
};
|
|
898
|
+
/**
|
|
899
|
+
* Runs two parsers in sequence and returns both outputs.
|
|
900
|
+
*
|
|
901
|
+
* @since 0.1.0
|
|
902
|
+
* @category sequencing
|
|
903
|
+
*/
|
|
904
|
+
export const zip = dual(2, (self, that) => zipWith(self, that, (a, b) => [a, b]));
|
|
905
|
+
/**
|
|
906
|
+
* Runs two parsers in sequence and combines their outputs.
|
|
907
|
+
*
|
|
908
|
+
* @since 0.1.0
|
|
909
|
+
* @category sequencing
|
|
910
|
+
*/
|
|
911
|
+
export const zipWith = dual(3, (self, that, f) => {
|
|
912
|
+
const s1 = self.step;
|
|
913
|
+
const s2 = that.step;
|
|
914
|
+
return described((state) => {
|
|
915
|
+
const a = s1(state);
|
|
916
|
+
if (a === Fail)
|
|
917
|
+
return Fail;
|
|
918
|
+
const b = s2(state);
|
|
919
|
+
if (b === Fail)
|
|
920
|
+
return Fail;
|
|
921
|
+
return f(a, b);
|
|
922
|
+
}, undefined, { _tag: "ZipWith", self, that, f });
|
|
923
|
+
});
|
|
924
|
+
/**
|
|
925
|
+
* Runs two parsers in sequence, keeping the output of the first.
|
|
926
|
+
*
|
|
927
|
+
* @since 0.1.0
|
|
928
|
+
* @category sequencing
|
|
929
|
+
*/
|
|
930
|
+
export const zipLeft = dual(2, (self, that) => terminated(self, that));
|
|
931
|
+
/**
|
|
932
|
+
* Runs two parsers in sequence, keeping the output of the second.
|
|
933
|
+
*
|
|
934
|
+
* @since 0.1.0
|
|
935
|
+
* @category sequencing
|
|
936
|
+
*/
|
|
937
|
+
export const zipRight = dual(2, (self, that) => preceded(self, that));
|
|
938
|
+
/**
|
|
939
|
+
* Runs `prefix` then `parser`, keeping the output of `parser` (winnow's and
|
|
940
|
+
* nom's `preceded`).
|
|
941
|
+
*
|
|
942
|
+
* @since 0.1.0
|
|
943
|
+
* @category sequencing
|
|
944
|
+
*/
|
|
945
|
+
export const preceded = (prefix, parser) => {
|
|
946
|
+
const s1 = prefix.step;
|
|
947
|
+
const s2 = parser.step;
|
|
948
|
+
return described((state) => s1(state) === Fail ? Fail : s2(state), parser.name, {
|
|
949
|
+
_tag: "Seq",
|
|
950
|
+
parsers: [prefix, parser],
|
|
951
|
+
output: 1
|
|
952
|
+
});
|
|
953
|
+
};
|
|
954
|
+
/**
|
|
955
|
+
* Runs `parser` then `suffix`, keeping the output of `parser` (winnow's and
|
|
956
|
+
* nom's `terminated`).
|
|
957
|
+
*
|
|
958
|
+
* @since 0.1.0
|
|
959
|
+
* @category sequencing
|
|
960
|
+
*/
|
|
961
|
+
export const terminated = (parser, suffix) => {
|
|
962
|
+
const s1 = parser.step;
|
|
963
|
+
const s2 = suffix.step;
|
|
964
|
+
return described((state) => {
|
|
965
|
+
const a = s1(state);
|
|
966
|
+
if (a === Fail)
|
|
967
|
+
return Fail;
|
|
968
|
+
return s2(state) === Fail ? Fail : a;
|
|
969
|
+
}, parser.name, { _tag: "Seq", parsers: [parser, suffix], output: 0 });
|
|
970
|
+
};
|
|
971
|
+
/**
|
|
972
|
+
* Runs `open`, `parser` and `close`, keeping the output of `parser`
|
|
973
|
+
* (winnow's and nom's `delimited`).
|
|
974
|
+
*
|
|
975
|
+
* @since 0.1.0
|
|
976
|
+
* @category sequencing
|
|
977
|
+
*/
|
|
978
|
+
export const delimited = (open, parser, close) => {
|
|
979
|
+
const s1 = open.step;
|
|
980
|
+
const s2 = parser.step;
|
|
981
|
+
const s3 = close.step;
|
|
982
|
+
return described((state) => {
|
|
983
|
+
if (s1(state) === Fail)
|
|
984
|
+
return Fail;
|
|
985
|
+
const a = s2(state);
|
|
986
|
+
if (a === Fail)
|
|
987
|
+
return Fail;
|
|
988
|
+
return s3(state) === Fail ? Fail : a;
|
|
989
|
+
}, parser.name, { _tag: "Seq", parsers: [open, parser, close], output: 1 });
|
|
990
|
+
};
|
|
991
|
+
/**
|
|
992
|
+
* Runs `first`, `separator` and `second`, keeping the outputs of `first` and
|
|
993
|
+
* `second` (winnow's and nom's `separated_pair`).
|
|
994
|
+
*
|
|
995
|
+
* @since 0.1.0
|
|
996
|
+
* @category sequencing
|
|
997
|
+
*/
|
|
998
|
+
export const separatedPair = (first, separator, second) => {
|
|
999
|
+
const s1 = first.step;
|
|
1000
|
+
const s2 = separator.step;
|
|
1001
|
+
const s3 = second.step;
|
|
1002
|
+
return described((state) => {
|
|
1003
|
+
const a = s1(state);
|
|
1004
|
+
if (a === Fail)
|
|
1005
|
+
return Fail;
|
|
1006
|
+
if (s2(state) === Fail)
|
|
1007
|
+
return Fail;
|
|
1008
|
+
const b = s3(state);
|
|
1009
|
+
return b === Fail ? Fail : [a, b];
|
|
1010
|
+
}, undefined, { _tag: "Seq", parsers: [first, separator, second], output: [0, 2] });
|
|
1011
|
+
};
|
|
1012
|
+
/**
|
|
1013
|
+
* Writes a parser in imperative style with a generator, Effect style:
|
|
1014
|
+
* `yield*` a parser to run it and get its output.
|
|
1015
|
+
*
|
|
1016
|
+
* @example
|
|
1017
|
+
* ```ts
|
|
1018
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
1019
|
+
*
|
|
1020
|
+
* const keyValue = Parser.gen(function*() {
|
|
1021
|
+
* const key = yield* Ascii.alpha1
|
|
1022
|
+
* yield* Token.literal("=")
|
|
1023
|
+
* const value = yield* Ascii.decInt
|
|
1024
|
+
* return [key, value] as const
|
|
1025
|
+
* })
|
|
1026
|
+
* ```
|
|
1027
|
+
*
|
|
1028
|
+
* @since 0.1.0
|
|
1029
|
+
* @category sequencing
|
|
1030
|
+
*/
|
|
1031
|
+
export const gen = (f) => make((state) => {
|
|
1032
|
+
const iterator = f();
|
|
1033
|
+
let next = iterator.next();
|
|
1034
|
+
while (!next.done) {
|
|
1035
|
+
const a = next.value.step(state);
|
|
1036
|
+
if (a === Fail) {
|
|
1037
|
+
iterator.return?.(undefined);
|
|
1038
|
+
return Fail;
|
|
1039
|
+
}
|
|
1040
|
+
next = iterator.next(a);
|
|
1041
|
+
}
|
|
1042
|
+
return next.value;
|
|
1043
|
+
}, "gen");
|
|
1044
|
+
/**
|
|
1045
|
+
* The starting point for Do notation.
|
|
1046
|
+
*
|
|
1047
|
+
* @example
|
|
1048
|
+
* ```ts
|
|
1049
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
1050
|
+
*
|
|
1051
|
+
* const range = Parser.Do.pipe(
|
|
1052
|
+
* Parser.bind("start", () => Ascii.decUint),
|
|
1053
|
+
* Parser.zipLeft(Token.literal("..")),
|
|
1054
|
+
* Parser.bind("end", () => Ascii.decUint)
|
|
1055
|
+
* )
|
|
1056
|
+
* ```
|
|
1057
|
+
*
|
|
1058
|
+
* @since 0.1.0
|
|
1059
|
+
* @category do notation
|
|
1060
|
+
*/
|
|
1061
|
+
export const Do = succeed({});
|
|
1062
|
+
/**
|
|
1063
|
+
* Binds the output of a parser to a field of the Do record.
|
|
1064
|
+
*
|
|
1065
|
+
* @since 0.1.0
|
|
1066
|
+
* @category do notation
|
|
1067
|
+
*/
|
|
1068
|
+
export const bind = dual(3, (self, name, f) => flatMap(self, (a) => map(f(a), (b) => ({ ...a, [name]: b }))));
|
|
1069
|
+
/**
|
|
1070
|
+
* Wraps the output of a parser in a record with a single field.
|
|
1071
|
+
*
|
|
1072
|
+
* @since 0.1.0
|
|
1073
|
+
* @category do notation
|
|
1074
|
+
*/
|
|
1075
|
+
export const bindTo = dual(2, (self, name) => map(self, (a) => ({ [name]: a })));
|
|
1076
|
+
const let_ = dual(3, (self, name, f) => map(self, (a) => ({ ...a, [name]: f(a) })));
|
|
1077
|
+
export {
|
|
1078
|
+
/**
|
|
1079
|
+
* Adds a computed field to the Do record.
|
|
1080
|
+
*
|
|
1081
|
+
* @since 0.1.0
|
|
1082
|
+
* @category do notation
|
|
1083
|
+
*/
|
|
1084
|
+
let_ as let };
|
|
1085
|
+
// -----------------------------------------------------------------------------
|
|
1086
|
+
// Choice
|
|
1087
|
+
// -----------------------------------------------------------------------------
|
|
1088
|
+
/**
|
|
1089
|
+
* Tries each parser in turn and returns the output of the first that
|
|
1090
|
+
* succeeds (winnow's and nom's `alt`).
|
|
1091
|
+
*
|
|
1092
|
+
* Unrecoverable (`Cut`) and `Incomplete` failures stop the search
|
|
1093
|
+
* immediately. If every alternative fails recoverably, the failures are
|
|
1094
|
+
* merged: the one that got furthest wins, and failures at the same offset
|
|
1095
|
+
* combine their expectations, e.g. `expected "true", "false" or "null"`.
|
|
1096
|
+
*
|
|
1097
|
+
* @since 0.1.0
|
|
1098
|
+
* @category choice
|
|
1099
|
+
*/
|
|
1100
|
+
export const alt = (...parsers) => {
|
|
1101
|
+
const steps = parsers.map((p) => p.step);
|
|
1102
|
+
const n = steps.length;
|
|
1103
|
+
if (n === 0)
|
|
1104
|
+
return reject;
|
|
1105
|
+
if (n === 1)
|
|
1106
|
+
return parsers[0];
|
|
1107
|
+
return described((state) => {
|
|
1108
|
+
const start = state.pos;
|
|
1109
|
+
let failure;
|
|
1110
|
+
for (let i = 0; i < n; i++) {
|
|
1111
|
+
const a = steps[i](state);
|
|
1112
|
+
if (a !== Fail) {
|
|
1113
|
+
if (failure !== undefined && failure.offset === state.pos)
|
|
1114
|
+
state.setHint(failure.offset, failure.expected);
|
|
1115
|
+
return a;
|
|
1116
|
+
}
|
|
1117
|
+
if (state.mode !== "Backtrack")
|
|
1118
|
+
return Fail;
|
|
1119
|
+
failure = failure === undefined ? state.failure : mergeFailures(failure, state.failure);
|
|
1120
|
+
state.pos = start;
|
|
1121
|
+
}
|
|
1122
|
+
return state.failWith("Backtrack", failure);
|
|
1123
|
+
}, "alt", { _tag: "Alt", parsers });
|
|
1124
|
+
};
|
|
1125
|
+
/**
|
|
1126
|
+
* Selects the parser to run next based on the output of `selector`, like a
|
|
1127
|
+
* `match` over the input (winnow's `dispatch!`). If no case matches, the
|
|
1128
|
+
* parser backtracks to where it started.
|
|
1129
|
+
*
|
|
1130
|
+
* Cases are given either as a record keyed by the selector's output (with
|
|
1131
|
+
* an optional `otherwise` parser for unlisted keys, like winnow's `_ =>`
|
|
1132
|
+
* arm), or as a function returning a parser (or `undefined` for no match).
|
|
1133
|
+
*
|
|
1134
|
+
* @example
|
|
1135
|
+
* ```ts
|
|
1136
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
1137
|
+
*
|
|
1138
|
+
* const escape = Parser.preceded(
|
|
1139
|
+
* Token.literal("\\"),
|
|
1140
|
+
* Parser.dispatch(Token.any, {
|
|
1141
|
+
* n: Parser.succeed("\n"),
|
|
1142
|
+
* t: Parser.succeed("\t"),
|
|
1143
|
+
* u: Parser.preceded(Token.literal("{"), Ascii.hexUint).pipe(
|
|
1144
|
+
* Parser.zipLeft(Token.literal("}")),
|
|
1145
|
+
* Parser.map((cp) => String.fromCodePoint(cp))
|
|
1146
|
+
* )
|
|
1147
|
+
* })
|
|
1148
|
+
* )
|
|
1149
|
+
* ```
|
|
1150
|
+
*
|
|
1151
|
+
* @since 0.1.0
|
|
1152
|
+
* @category choice
|
|
1153
|
+
*/
|
|
1154
|
+
export const dispatch = (selector, cases, otherwise) => {
|
|
1155
|
+
const choose = typeof cases === "function" ? cases : (key) => Object.prototype.hasOwnProperty.call(cases, key) ? cases[key] : otherwise;
|
|
1156
|
+
const step = selector.step;
|
|
1157
|
+
return described((state) => {
|
|
1158
|
+
const start = state.pos;
|
|
1159
|
+
const key = step(state);
|
|
1160
|
+
if (key === Fail)
|
|
1161
|
+
return Fail;
|
|
1162
|
+
const parser = choose(key);
|
|
1163
|
+
if (parser === undefined) {
|
|
1164
|
+
state.pos = start;
|
|
1165
|
+
return state.backtrack("Dispatch");
|
|
1166
|
+
}
|
|
1167
|
+
return parser.step(state);
|
|
1168
|
+
}, "dispatch", {
|
|
1169
|
+
_tag: "Dispatch",
|
|
1170
|
+
selector,
|
|
1171
|
+
cases: typeof cases === "function" ? undefined : cases,
|
|
1172
|
+
otherwise: typeof cases === "function" ? undefined : otherwise,
|
|
1173
|
+
choose
|
|
1174
|
+
});
|
|
1175
|
+
};
|
|
1176
|
+
/**
|
|
1177
|
+
* Applies every parser exactly once, in whatever order they match, and
|
|
1178
|
+
* returns their outputs in the order the parsers were given (winnow's and
|
|
1179
|
+
* nom's `permutation`).
|
|
1180
|
+
*
|
|
1181
|
+
* @since 0.1.0
|
|
1182
|
+
* @category choice
|
|
1183
|
+
*/
|
|
1184
|
+
export const permutation = (...parsers) => {
|
|
1185
|
+
const steps = parsers.map((p) => p.step);
|
|
1186
|
+
const n = steps.length;
|
|
1187
|
+
return make((state) => {
|
|
1188
|
+
const out = new Array(n);
|
|
1189
|
+
const done = new Array(n).fill(false);
|
|
1190
|
+
let remaining = n;
|
|
1191
|
+
while (remaining > 0) {
|
|
1192
|
+
let failure;
|
|
1193
|
+
let matched = false;
|
|
1194
|
+
for (let i = 0; i < n; i++) {
|
|
1195
|
+
if (done[i])
|
|
1196
|
+
continue;
|
|
1197
|
+
const start = state.pos;
|
|
1198
|
+
const a = steps[i](state);
|
|
1199
|
+
if (a !== Fail) {
|
|
1200
|
+
out[i] = a;
|
|
1201
|
+
done[i] = true;
|
|
1202
|
+
remaining--;
|
|
1203
|
+
matched = true;
|
|
1204
|
+
break;
|
|
1205
|
+
}
|
|
1206
|
+
if (state.mode !== "Backtrack")
|
|
1207
|
+
return Fail;
|
|
1208
|
+
failure = failure === undefined ? state.failure : mergeFailures(failure, state.failure);
|
|
1209
|
+
state.pos = start;
|
|
1210
|
+
}
|
|
1211
|
+
if (!matched)
|
|
1212
|
+
return state.failWith("Backtrack", failure);
|
|
1213
|
+
}
|
|
1214
|
+
return out;
|
|
1215
|
+
}, "permutation");
|
|
1216
|
+
};
|
|
1217
|
+
// -----------------------------------------------------------------------------
|
|
1218
|
+
// Repetition
|
|
1219
|
+
// -----------------------------------------------------------------------------
|
|
1220
|
+
const normalizeRange = (range) => {
|
|
1221
|
+
if (range === undefined)
|
|
1222
|
+
return [0, Infinity];
|
|
1223
|
+
if (typeof range === "number")
|
|
1224
|
+
return [range, range];
|
|
1225
|
+
const min = range.min ?? 0;
|
|
1226
|
+
const max = range.max ?? Infinity;
|
|
1227
|
+
if (min > max)
|
|
1228
|
+
throw new RangeError(`invalid range: min (${min}) > max (${max})`);
|
|
1229
|
+
return [min, max];
|
|
1230
|
+
};
|
|
1231
|
+
const assertConsumes = (state, name) => state.failMessage("Cut", "Assert", `\`${name}\` parsers must always consume`);
|
|
1232
|
+
const saveFold = (state, key, entry, acc, pos) => Resume.save(state, key, entry, { acc, count: 0, pos });
|
|
1233
|
+
const foldImpl = (self, range, init, f, name, node) => {
|
|
1234
|
+
const [min, max] = normalizeRange(range);
|
|
1235
|
+
const step = self.step;
|
|
1236
|
+
const checkLoop = max === Infinity;
|
|
1237
|
+
const key = {};
|
|
1238
|
+
return described((state) => {
|
|
1239
|
+
const entry = state.pos;
|
|
1240
|
+
let acc;
|
|
1241
|
+
let count = 0;
|
|
1242
|
+
const resumed = state.resume === undefined ? undefined : Resume.take(state, key, entry);
|
|
1243
|
+
if (resumed instanceof Resume.Done) {
|
|
1244
|
+
state.pos = resumed.pos;
|
|
1245
|
+
return resumed.value;
|
|
1246
|
+
}
|
|
1247
|
+
if (resumed !== undefined) {
|
|
1248
|
+
acc = resumed.acc;
|
|
1249
|
+
count = resumed.count;
|
|
1250
|
+
state.pos = resumed.pos;
|
|
1251
|
+
}
|
|
1252
|
+
else {
|
|
1253
|
+
acc = init();
|
|
1254
|
+
}
|
|
1255
|
+
for (; count < max; count++) {
|
|
1256
|
+
const start = state.pos;
|
|
1257
|
+
const a = step(state);
|
|
1258
|
+
if (a === Fail) {
|
|
1259
|
+
if (state.mode === "Incomplete" && state.resume !== undefined) {
|
|
1260
|
+
Resume.save(state, key, entry, { acc, count, pos: start });
|
|
1261
|
+
}
|
|
1262
|
+
if (state.mode !== "Backtrack" || count < min)
|
|
1263
|
+
return Fail;
|
|
1264
|
+
recover(state, start);
|
|
1265
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1266
|
+
}
|
|
1267
|
+
if (checkLoop && state.pos === start)
|
|
1268
|
+
return assertConsumes(state, name);
|
|
1269
|
+
acc = f(acc, a);
|
|
1270
|
+
}
|
|
1271
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1272
|
+
}, name, node ?? { _tag: "Fold", self, init, f, name, ...bounds(range) });
|
|
1273
|
+
};
|
|
1274
|
+
/**
|
|
1275
|
+
* Applies a parser repeatedly, collecting the outputs in an array (winnow's
|
|
1276
|
+
* `repeat`, nom's `many0`, `many1`, `many_m_n` and `count`).
|
|
1277
|
+
*
|
|
1278
|
+
* The range defaults to `{ min: 0 }` (zero or more). A number repeats
|
|
1279
|
+
* exactly that many times. With a literal positive `min`, the output is
|
|
1280
|
+
* typed as a non-empty array.
|
|
1281
|
+
*
|
|
1282
|
+
* As in winnow, an unbounded repetition of a parser that succeeds without
|
|
1283
|
+
* consuming input fails with an unrecoverable assertion instead of looping
|
|
1284
|
+
* forever.
|
|
1285
|
+
*
|
|
1286
|
+
* @example
|
|
1287
|
+
* ```ts
|
|
1288
|
+
* import { Parser, Token } from "@thomasfosterau/effect-parse"
|
|
1289
|
+
*
|
|
1290
|
+
* const abs = Parser.repeat(Token.literal("ab"), { min: 1 })
|
|
1291
|
+
* Parser.parse(abs, "ababab") // Result.succeed(["ab", "ab", "ab"])
|
|
1292
|
+
* ```
|
|
1293
|
+
*
|
|
1294
|
+
* @since 0.1.0
|
|
1295
|
+
* @category repetition
|
|
1296
|
+
*/
|
|
1297
|
+
export const repeat = dual(isParserArg, (self, range) => foldImpl(self, range, () => [], (acc, a) => {
|
|
1298
|
+
acc.push(a);
|
|
1299
|
+
return acc;
|
|
1300
|
+
}, "repeat", { _tag: "Repeat", self, ...bounds(range) }));
|
|
1301
|
+
/**
|
|
1302
|
+
* Applies a parser repeatedly, folding the outputs into an accumulator
|
|
1303
|
+
* (winnow's `repeat(..).fold(..)`, nom's `fold_many0`/`fold_many1`/
|
|
1304
|
+
* `fold_many_m_n`).
|
|
1305
|
+
*
|
|
1306
|
+
* @since 0.1.0
|
|
1307
|
+
* @category repetition
|
|
1308
|
+
*/
|
|
1309
|
+
export const fold = dual(2, (self, options) => foldImpl(self, options.range, options.init, options.f, "fold"));
|
|
1310
|
+
/**
|
|
1311
|
+
* Applies `self` repeatedly until `end` succeeds, returning the collected
|
|
1312
|
+
* outputs and the output of `end` (winnow's `repeat_till`, nom's
|
|
1313
|
+
* `many_till`).
|
|
1314
|
+
*
|
|
1315
|
+
* @since 0.1.0
|
|
1316
|
+
* @category repetition
|
|
1317
|
+
*/
|
|
1318
|
+
export const repeatTill = dual(isTwoParserArgs, (self, end, range) => {
|
|
1319
|
+
const [min, max] = normalizeRange(range);
|
|
1320
|
+
const step = self.step;
|
|
1321
|
+
const endStep = end.step;
|
|
1322
|
+
return described((state) => {
|
|
1323
|
+
const acc = [];
|
|
1324
|
+
while (true) {
|
|
1325
|
+
const start = state.pos;
|
|
1326
|
+
let endFailure;
|
|
1327
|
+
if (acc.length >= min) {
|
|
1328
|
+
const b = endStep(state);
|
|
1329
|
+
if (b !== Fail)
|
|
1330
|
+
return [acc, b];
|
|
1331
|
+
if (state.mode !== "Backtrack")
|
|
1332
|
+
return Fail;
|
|
1333
|
+
endFailure = state.failure;
|
|
1334
|
+
state.pos = start;
|
|
1335
|
+
if (acc.length >= max)
|
|
1336
|
+
return Fail;
|
|
1337
|
+
}
|
|
1338
|
+
const a = step(state);
|
|
1339
|
+
if (a === Fail) {
|
|
1340
|
+
if (endFailure !== undefined && state.mode === "Backtrack") {
|
|
1341
|
+
state.failWith("Backtrack", mergeFailures(endFailure, state.failure));
|
|
1342
|
+
}
|
|
1343
|
+
return Fail;
|
|
1344
|
+
}
|
|
1345
|
+
if (state.pos === start)
|
|
1346
|
+
return assertConsumes(state, "repeatTill");
|
|
1347
|
+
acc.push(a);
|
|
1348
|
+
}
|
|
1349
|
+
}, "repeatTill", { _tag: "RepeatTill", self, end, ...bounds(range) });
|
|
1350
|
+
});
|
|
1351
|
+
export const separated = dual(isTwoParserArgs, (self, separator, range) => {
|
|
1352
|
+
const [min, max] = normalizeRange(range);
|
|
1353
|
+
const step = self.step;
|
|
1354
|
+
const sepStep = separator.step;
|
|
1355
|
+
const checkLoop = max === Infinity;
|
|
1356
|
+
const key = {};
|
|
1357
|
+
return described((state) => {
|
|
1358
|
+
const entry = state.pos;
|
|
1359
|
+
let acc;
|
|
1360
|
+
const resumed = state.resume === undefined ? undefined : Resume.take(state, key, entry);
|
|
1361
|
+
if (resumed instanceof Resume.Done) {
|
|
1362
|
+
state.pos = resumed.pos;
|
|
1363
|
+
return resumed.value;
|
|
1364
|
+
}
|
|
1365
|
+
if (resumed !== undefined) {
|
|
1366
|
+
acc = resumed.acc;
|
|
1367
|
+
state.pos = resumed.pos;
|
|
1368
|
+
}
|
|
1369
|
+
else {
|
|
1370
|
+
acc = [];
|
|
1371
|
+
if (max === 0)
|
|
1372
|
+
return acc;
|
|
1373
|
+
const start = state.pos;
|
|
1374
|
+
const first = step(state);
|
|
1375
|
+
if (first === Fail) {
|
|
1376
|
+
if (state.mode !== "Backtrack" || min > 0)
|
|
1377
|
+
return Fail;
|
|
1378
|
+
recover(state, start);
|
|
1379
|
+
return acc;
|
|
1380
|
+
}
|
|
1381
|
+
acc.push(first);
|
|
1382
|
+
}
|
|
1383
|
+
while (acc.length < max) {
|
|
1384
|
+
const start = state.pos;
|
|
1385
|
+
if (sepStep(state) === Fail) {
|
|
1386
|
+
if (state.mode === "Incomplete" && state.resume !== undefined) {
|
|
1387
|
+
Resume.save(state, key, entry, { acc, pos: start });
|
|
1388
|
+
}
|
|
1389
|
+
if (state.mode !== "Backtrack" || acc.length < min)
|
|
1390
|
+
return Fail;
|
|
1391
|
+
recover(state, start);
|
|
1392
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1393
|
+
}
|
|
1394
|
+
if (checkLoop && state.pos === start)
|
|
1395
|
+
return assertConsumes(state, "separated");
|
|
1396
|
+
const a = step(state);
|
|
1397
|
+
if (a === Fail) {
|
|
1398
|
+
if (state.mode === "Incomplete" && state.resume !== undefined) {
|
|
1399
|
+
Resume.save(state, key, entry, { acc, pos: start });
|
|
1400
|
+
}
|
|
1401
|
+
if (state.mode !== "Backtrack" || acc.length < min)
|
|
1402
|
+
return Fail;
|
|
1403
|
+
state.pos = start;
|
|
1404
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1405
|
+
}
|
|
1406
|
+
acc.push(a);
|
|
1407
|
+
}
|
|
1408
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1409
|
+
}, "separated", { _tag: "Separated", self, separator, ...bounds(range) });
|
|
1410
|
+
});
|
|
1411
|
+
/**
|
|
1412
|
+
* Parses one or more `self` separated by `separator`, folding them from the
|
|
1413
|
+
* left with the separator's output: `((a op b) op c)` (winnow's
|
|
1414
|
+
* `separated_foldl1`). This is the classic way to parse left-associative
|
|
1415
|
+
* binary operators.
|
|
1416
|
+
*
|
|
1417
|
+
* @example
|
|
1418
|
+
* ```ts
|
|
1419
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
1420
|
+
*
|
|
1421
|
+
* const sum = Parser.separatedFoldl1(
|
|
1422
|
+
* Ascii.decInt,
|
|
1423
|
+
* Parser.alt(Token.literal("+"), Token.literal("-")),
|
|
1424
|
+
* (l, op, r) => op === "+" ? l + r : l - r
|
|
1425
|
+
* )
|
|
1426
|
+
* Parser.parse(sum, "10-3+2") // Result.succeed(9)
|
|
1427
|
+
* ```
|
|
1428
|
+
*
|
|
1429
|
+
* @since 0.1.0
|
|
1430
|
+
* @category repetition
|
|
1431
|
+
*/
|
|
1432
|
+
export const separatedFoldl1 = (self, separator, op) => {
|
|
1433
|
+
const step = self.step;
|
|
1434
|
+
const sepStep = separator.step;
|
|
1435
|
+
const key = {};
|
|
1436
|
+
return described((state) => {
|
|
1437
|
+
const entry = state.pos;
|
|
1438
|
+
const resumed = state.resume === undefined ? undefined : Resume.take(state, key, entry);
|
|
1439
|
+
let acc;
|
|
1440
|
+
if (resumed instanceof Resume.Done) {
|
|
1441
|
+
state.pos = resumed.pos;
|
|
1442
|
+
return resumed.value;
|
|
1443
|
+
}
|
|
1444
|
+
if (resumed !== undefined) {
|
|
1445
|
+
acc = resumed.acc;
|
|
1446
|
+
state.pos = resumed.pos;
|
|
1447
|
+
}
|
|
1448
|
+
else {
|
|
1449
|
+
acc = step(state);
|
|
1450
|
+
if (acc === Fail)
|
|
1451
|
+
return Fail;
|
|
1452
|
+
}
|
|
1453
|
+
while (true) {
|
|
1454
|
+
const start = state.pos;
|
|
1455
|
+
const s = sepStep(state);
|
|
1456
|
+
if (s === Fail) {
|
|
1457
|
+
if (state.mode === "Incomplete" && state.resume !== undefined)
|
|
1458
|
+
saveFold(state, key, entry, acc, start);
|
|
1459
|
+
if (state.mode !== "Backtrack")
|
|
1460
|
+
return Fail;
|
|
1461
|
+
recover(state, start);
|
|
1462
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1463
|
+
}
|
|
1464
|
+
if (state.pos === start)
|
|
1465
|
+
return assertConsumes(state, "separatedFoldl1");
|
|
1466
|
+
const a = step(state);
|
|
1467
|
+
if (a === Fail) {
|
|
1468
|
+
if (state.mode === "Incomplete" && state.resume !== undefined)
|
|
1469
|
+
saveFold(state, key, entry, acc, start);
|
|
1470
|
+
if (state.mode !== "Backtrack")
|
|
1471
|
+
return Fail;
|
|
1472
|
+
state.pos = start;
|
|
1473
|
+
return Resume.done(state, key, entry, resumed !== undefined, acc);
|
|
1474
|
+
}
|
|
1475
|
+
acc = op(acc, s, a);
|
|
1476
|
+
}
|
|
1477
|
+
}, "separatedFoldl1", { _tag: "SeparatedFold", self, separator, op, right: false });
|
|
1478
|
+
};
|
|
1479
|
+
/**
|
|
1480
|
+
* Parses one or more `self` separated by `separator`, folding them from the
|
|
1481
|
+
* right with the separator's output: `(a op (b op c))` (winnow's
|
|
1482
|
+
* `separated_foldr1`). Useful for right-associative operators such as
|
|
1483
|
+
* exponentiation.
|
|
1484
|
+
*
|
|
1485
|
+
* @since 0.1.0
|
|
1486
|
+
* @category repetition
|
|
1487
|
+
*/
|
|
1488
|
+
export const separatedFoldr1 = (self, separator, op) => {
|
|
1489
|
+
const step = self.step;
|
|
1490
|
+
const sepStep = separator.step;
|
|
1491
|
+
return described((state) => {
|
|
1492
|
+
const first = step(state);
|
|
1493
|
+
if (first === Fail)
|
|
1494
|
+
return Fail;
|
|
1495
|
+
const values = [first];
|
|
1496
|
+
const seps = [];
|
|
1497
|
+
while (true) {
|
|
1498
|
+
const start = state.pos;
|
|
1499
|
+
const s = sepStep(state);
|
|
1500
|
+
if (s === Fail) {
|
|
1501
|
+
if (state.mode !== "Backtrack")
|
|
1502
|
+
return Fail;
|
|
1503
|
+
recover(state, start);
|
|
1504
|
+
break;
|
|
1505
|
+
}
|
|
1506
|
+
if (state.pos === start)
|
|
1507
|
+
return assertConsumes(state, "separatedFoldr1");
|
|
1508
|
+
const a = step(state);
|
|
1509
|
+
if (a === Fail) {
|
|
1510
|
+
if (state.mode !== "Backtrack")
|
|
1511
|
+
return Fail;
|
|
1512
|
+
state.pos = start;
|
|
1513
|
+
break;
|
|
1514
|
+
}
|
|
1515
|
+
seps.push(s);
|
|
1516
|
+
values.push(a);
|
|
1517
|
+
}
|
|
1518
|
+
let acc = values[values.length - 1];
|
|
1519
|
+
for (let i = seps.length - 1; i >= 0; i--) {
|
|
1520
|
+
acc = op(values[i], seps[i], acc);
|
|
1521
|
+
}
|
|
1522
|
+
return acc;
|
|
1523
|
+
}, "separatedFoldr1", { _tag: "SeparatedFold", self, separator, op, right: true });
|
|
1524
|
+
};
|
|
1525
|
+
// -----------------------------------------------------------------------------
|
|
1526
|
+
// Services
|
|
1527
|
+
// -----------------------------------------------------------------------------
|
|
1528
|
+
/**
|
|
1529
|
+
* Accesses a service from the parser's context. Services take the place of
|
|
1530
|
+
* winnow's `Stateful` input: they can hold configuration, or mutable state
|
|
1531
|
+
* such as an indentation stack or a symbol table.
|
|
1532
|
+
*
|
|
1533
|
+
* Services are provided with {@link provideService} / {@link provide}, with
|
|
1534
|
+
* the `context` option of the runners, or taken from the surrounding Effect
|
|
1535
|
+
* by {@link parseEffect}.
|
|
1536
|
+
*
|
|
1537
|
+
* Mutations made to a service's state are not undone on backtracking (as
|
|
1538
|
+
* with winnow's `Stateful`).
|
|
1539
|
+
*
|
|
1540
|
+
* @example
|
|
1541
|
+
* ```ts
|
|
1542
|
+
* import { Context } from "effect"
|
|
1543
|
+
* import { Ascii, Parser } from "@thomasfosterau/effect-parse"
|
|
1544
|
+
*
|
|
1545
|
+
* class Radix extends Context.Service<Radix, number>()("Radix") {}
|
|
1546
|
+
*
|
|
1547
|
+
* const number = Parser.service(Radix).pipe(
|
|
1548
|
+
* Parser.flatMap((radix) =>
|
|
1549
|
+
* Ascii.alphanumeric1.pipe(Parser.map((digits) => parseInt(digits, radix)))
|
|
1550
|
+
* )
|
|
1551
|
+
* )
|
|
1552
|
+
*
|
|
1553
|
+
* Parser.parse(Parser.provideService(number, Radix, 16), "ff") // Result.succeed(255)
|
|
1554
|
+
* ```
|
|
1555
|
+
*
|
|
1556
|
+
* @since 0.1.0
|
|
1557
|
+
* @category services
|
|
1558
|
+
*/
|
|
1559
|
+
export const service = (key) => described((state) => Context.getUnsafe(state.context, key), "service", serviceNode);
|
|
1560
|
+
const serviceNode = { _tag: "Service" };
|
|
1561
|
+
/**
|
|
1562
|
+
* Provides a service to a parser.
|
|
1563
|
+
*
|
|
1564
|
+
* @since 0.1.0
|
|
1565
|
+
* @category services
|
|
1566
|
+
*/
|
|
1567
|
+
export const provideService = dual(3, (self, key, service) => {
|
|
1568
|
+
const step = self.step;
|
|
1569
|
+
return described((state) => {
|
|
1570
|
+
const prev = state.context;
|
|
1571
|
+
state.context = Context.add(prev, key, service);
|
|
1572
|
+
try {
|
|
1573
|
+
return step(state);
|
|
1574
|
+
}
|
|
1575
|
+
finally {
|
|
1576
|
+
state.context = prev;
|
|
1577
|
+
}
|
|
1578
|
+
}, self.name, { _tag: "Provide", self });
|
|
1579
|
+
});
|
|
1580
|
+
/**
|
|
1581
|
+
* Provides a context of services to a parser.
|
|
1582
|
+
*
|
|
1583
|
+
* @since 0.1.0
|
|
1584
|
+
* @category services
|
|
1585
|
+
*/
|
|
1586
|
+
export const provide = dual(2, (self, context) => {
|
|
1587
|
+
const step = self.step;
|
|
1588
|
+
return described((state) => {
|
|
1589
|
+
const prev = state.context;
|
|
1590
|
+
state.context = Context.merge(prev, context);
|
|
1591
|
+
try {
|
|
1592
|
+
return step(state);
|
|
1593
|
+
}
|
|
1594
|
+
finally {
|
|
1595
|
+
state.context = prev;
|
|
1596
|
+
}
|
|
1597
|
+
}, self.name, { _tag: "Provide", self });
|
|
1598
|
+
});
|
|
1599
|
+
// -----------------------------------------------------------------------------
|
|
1600
|
+
// Error recovery
|
|
1601
|
+
// -----------------------------------------------------------------------------
|
|
1602
|
+
/**
|
|
1603
|
+
* Error recovery: if the parser fails, record the failure, skip input with
|
|
1604
|
+
* `recover`, and continue with `Option.none()` (winnow's `resume_after`).
|
|
1605
|
+
*
|
|
1606
|
+
* Recovery is only active when running with {@link parseRecoverable}. Under
|
|
1607
|
+
* the other runners the parser behaves like `Parser.asSome(self)`.
|
|
1608
|
+
*
|
|
1609
|
+
* @since 0.1.0
|
|
1610
|
+
* @category error recovery
|
|
1611
|
+
*/
|
|
1612
|
+
export const resumeAfter = dual(2, (self, recover) => {
|
|
1613
|
+
const step = self.step;
|
|
1614
|
+
const recoverStep = recover.step;
|
|
1615
|
+
return described((state) => {
|
|
1616
|
+
const start = state.pos;
|
|
1617
|
+
const a = step(state);
|
|
1618
|
+
if (a !== Fail)
|
|
1619
|
+
return Option.some(a);
|
|
1620
|
+
if (state.recovered === undefined || state.mode === "Incomplete")
|
|
1621
|
+
return Fail;
|
|
1622
|
+
const failure = state.failure;
|
|
1623
|
+
const mode = state.mode;
|
|
1624
|
+
state.pos = start;
|
|
1625
|
+
if (recoverStep(state) === Fail)
|
|
1626
|
+
return state.failWith(mode, failure);
|
|
1627
|
+
state.recovered.push(failure);
|
|
1628
|
+
return Option.none();
|
|
1629
|
+
}, self.name, { _tag: "ResumeAfter", self, recover });
|
|
1630
|
+
});
|
|
1631
|
+
/**
|
|
1632
|
+
* Error recovery: if the parser fails, record the failure, skip input with
|
|
1633
|
+
* `recover`, and try the parser again (winnow's `retry_after`).
|
|
1634
|
+
*
|
|
1635
|
+
* Recovery is only active when running with {@link parseRecoverable}. Under
|
|
1636
|
+
* the other runners the parser behaves like `self`.
|
|
1637
|
+
*
|
|
1638
|
+
* @since 0.1.0
|
|
1639
|
+
* @category error recovery
|
|
1640
|
+
*/
|
|
1641
|
+
export const retryAfter = dual(2, (self, recover) => {
|
|
1642
|
+
const step = self.step;
|
|
1643
|
+
const recoverStep = recover.step;
|
|
1644
|
+
return described((state) => {
|
|
1645
|
+
while (true) {
|
|
1646
|
+
const start = state.pos;
|
|
1647
|
+
const a = step(state);
|
|
1648
|
+
if (a !== Fail)
|
|
1649
|
+
return a;
|
|
1650
|
+
if (state.recovered === undefined || state.mode === "Incomplete")
|
|
1651
|
+
return Fail;
|
|
1652
|
+
const failure = state.failure;
|
|
1653
|
+
const mode = state.mode;
|
|
1654
|
+
state.pos = start;
|
|
1655
|
+
if (recoverStep(state) === Fail || state.pos === start)
|
|
1656
|
+
return state.failWith(mode, failure);
|
|
1657
|
+
state.recovered.push(failure);
|
|
1658
|
+
}
|
|
1659
|
+
}, self.name, { _tag: "RetryAfter", self, recover });
|
|
1660
|
+
});
|
|
1661
|
+
// -----------------------------------------------------------------------------
|
|
1662
|
+
// Debugging
|
|
1663
|
+
// -----------------------------------------------------------------------------
|
|
1664
|
+
/**
|
|
1665
|
+
* Traces the execution of a parser (winnow's `trace`). When a tracer is
|
|
1666
|
+
* installed (see the `trace` option of {@link parse}), `Enter` and `Exit`
|
|
1667
|
+
* events are reported for each traced parser; otherwise tracing has no
|
|
1668
|
+
* effect.
|
|
1669
|
+
*
|
|
1670
|
+
* @since 0.1.0
|
|
1671
|
+
* @category debugging
|
|
1672
|
+
*/
|
|
1673
|
+
export const trace = dual(2, (self, name) => {
|
|
1674
|
+
const step = self.step;
|
|
1675
|
+
return described((state) => {
|
|
1676
|
+
const tracer = state.tracer;
|
|
1677
|
+
if (tracer === undefined)
|
|
1678
|
+
return step(state);
|
|
1679
|
+
const start = state.pos;
|
|
1680
|
+
const depth = state.depth;
|
|
1681
|
+
tracer({ _tag: "Enter", name, depth, offset: start, state });
|
|
1682
|
+
state.depth = depth + 1;
|
|
1683
|
+
const a = step(state);
|
|
1684
|
+
state.depth = depth;
|
|
1685
|
+
tracer({
|
|
1686
|
+
_tag: "Exit",
|
|
1687
|
+
name,
|
|
1688
|
+
depth,
|
|
1689
|
+
offset: start,
|
|
1690
|
+
endOffset: state.pos,
|
|
1691
|
+
result: a === Fail ? state.mode : "Ok",
|
|
1692
|
+
state
|
|
1693
|
+
});
|
|
1694
|
+
return a;
|
|
1695
|
+
}, name, { _tag: "Trace", self, name });
|
|
1696
|
+
});
|
|
1697
|
+
const preview = (state, offset) => {
|
|
1698
|
+
const input = state.input;
|
|
1699
|
+
if (typeof input === "string") {
|
|
1700
|
+
const s = input.slice(offset, offset + 24);
|
|
1701
|
+
return JSON.stringify(s) + (offset + 24 < input.length ? "…" : "∅");
|
|
1702
|
+
}
|
|
1703
|
+
if (input instanceof Uint8Array) {
|
|
1704
|
+
return Array.from(input.subarray(offset, offset + 12), (b) => b.toString(16).padStart(2, "0")).join(" ");
|
|
1705
|
+
}
|
|
1706
|
+
return `[${offset}/${input.length}]`;
|
|
1707
|
+
};
|
|
1708
|
+
/**
|
|
1709
|
+
* A tracer that writes an indented trace to `console.log`, similar to
|
|
1710
|
+
* winnow's `debug` feature.
|
|
1711
|
+
*
|
|
1712
|
+
* @since 0.1.0
|
|
1713
|
+
* @category debugging
|
|
1714
|
+
*/
|
|
1715
|
+
export const consoleTracer = (event) => {
|
|
1716
|
+
const indent = " ".repeat(event.depth);
|
|
1717
|
+
if (event._tag === "Enter") {
|
|
1718
|
+
console.log(`${indent}> ${event.name} @${event.offset} | ${preview(event.state, event.offset)}`);
|
|
1719
|
+
}
|
|
1720
|
+
else {
|
|
1721
|
+
const consumed = (event.endOffset ?? event.offset) - event.offset;
|
|
1722
|
+
console.log(`${indent}< ${event.name} | ${event.result === "Ok" ? `+${consumed}` : event.result}`);
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
/**
|
|
1726
|
+
* Compiles a parser into fused, specialized code, and returns the same
|
|
1727
|
+
* parser. Grammars are written as usual; compilation only makes
|
|
1728
|
+
* {@link parse}, {@link parseSync}, {@link parsePeek} and
|
|
1729
|
+
* {@link parseEffect} faster. Compile the root of a grammar once, where it
|
|
1730
|
+
* is defined:
|
|
1731
|
+
*
|
|
1732
|
+
* ```ts
|
|
1733
|
+
* import { Ascii, Parser, Token } from "@thomasfosterau/effect-parse"
|
|
1734
|
+
*
|
|
1735
|
+
* export const list = Parser.compile(
|
|
1736
|
+
* Parser.separated(Ascii.decInt, Token.literal(","))
|
|
1737
|
+
* )
|
|
1738
|
+
* Parser.parse(list, "1,2,3") // Result.succeed([1, 2, 3]), compiled
|
|
1739
|
+
* ```
|
|
1740
|
+
*
|
|
1741
|
+
* The code is generated lazily on the first run, for each kind of input
|
|
1742
|
+
* (string, bytes or array), and cached with the parser.
|
|
1743
|
+
*
|
|
1744
|
+
* **Results and errors are unchanged.** Compiled code records no
|
|
1745
|
+
* diagnostics. When it fails, the parser runs again, interpreted, from the
|
|
1746
|
+
* start, so every `ParseError` (offset, expected, context, cause and
|
|
1747
|
+
* message) is exactly the one the interpreter reports.
|
|
1748
|
+
*
|
|
1749
|
+
* **Callbacks should be pure.** On an input that fails, the callbacks given
|
|
1750
|
+
* to `map`, `filter`, `tryMap`, `tap`, `fold`, ... may run twice, once
|
|
1751
|
+
* compiled and once interpreted. Callbacks whose results are discarded
|
|
1752
|
+
* (a `map` inside `taken` or `preceded`, for example) may not run at all,
|
|
1753
|
+
* nor those of a branch that is certain to fail, and token-set predicates
|
|
1754
|
+
* may be called once per character code and cached.
|
|
1755
|
+
*
|
|
1756
|
+
* Runs on partial input ({@link parsePartial}, `ParserStream`), with
|
|
1757
|
+
* {@link parseRecoverable} or with the `trace` option are always
|
|
1758
|
+
* interpreted. Parsers that can't be described, such as {@link make} and
|
|
1759
|
+
* {@link gen}, run interpreted inside compiled code.
|
|
1760
|
+
*
|
|
1761
|
+
* @since 0.1.0
|
|
1762
|
+
* @category compilation
|
|
1763
|
+
*/
|
|
1764
|
+
export const compile = dual(isParserArg, (self, options) => {
|
|
1765
|
+
Compiler.register(self, options?.backend ?? "auto");
|
|
1766
|
+
return self;
|
|
1767
|
+
});
|
|
1768
|
+
/** Returned by {@link runCompiled} when there is no compiled form to run. */
|
|
1769
|
+
const NotCompiled = Symbol("NotCompiled");
|
|
1770
|
+
/**
|
|
1771
|
+
* Runs the compiled form of `self`, if it has one: returns its value, or
|
|
1772
|
+
* `Fail` when it failed (or, with `whole`, did not consume the whole
|
|
1773
|
+
* input), in which case the state must be thrown away.
|
|
1774
|
+
*/
|
|
1775
|
+
const runCompiled = (self, state, whole) => {
|
|
1776
|
+
if (state.tracer !== undefined || state.recovered !== undefined)
|
|
1777
|
+
return NotCompiled;
|
|
1778
|
+
const step = Compiler.stepFor(self, state);
|
|
1779
|
+
if (step === undefined)
|
|
1780
|
+
return NotCompiled;
|
|
1781
|
+
const a = step(state);
|
|
1782
|
+
if (a === Fail || (whole && state.pos < state.end))
|
|
1783
|
+
return Fail;
|
|
1784
|
+
return a;
|
|
1785
|
+
};
|
|
1786
|
+
const makeState = (input, options, partial) => {
|
|
1787
|
+
const state = new State(input, { partial, context: options?.context });
|
|
1788
|
+
const t = options?.trace;
|
|
1789
|
+
if (t !== undefined && t !== false)
|
|
1790
|
+
state.tracer = t === true ? consoleTracer : t;
|
|
1791
|
+
return state;
|
|
1792
|
+
};
|
|
1793
|
+
const toError = (state) => ParseError.fromFailure(state.input, state.reportedFailure(), state.mode, state.encoding);
|
|
1794
|
+
/** Runs a parser against a complete input, compiled when possible. */
|
|
1795
|
+
const parseComplete = (self, input, options) => {
|
|
1796
|
+
const state = makeState(input, options, false);
|
|
1797
|
+
const a = runCompiled(self, state, true);
|
|
1798
|
+
if (a === NotCompiled)
|
|
1799
|
+
return runComplete(self, state);
|
|
1800
|
+
if (a !== Fail)
|
|
1801
|
+
return Result.succeed(a);
|
|
1802
|
+
// Re-run interpreted for the diagnostics
|
|
1803
|
+
return runComplete(self, makeState(input, options, false));
|
|
1804
|
+
};
|
|
1805
|
+
const runComplete = (self, state) => {
|
|
1806
|
+
const a = self.step(state);
|
|
1807
|
+
if (a === Fail)
|
|
1808
|
+
return Result.fail(toError(state));
|
|
1809
|
+
if (state.pos < state.end) {
|
|
1810
|
+
state.backtrack("Eof", expectedEof);
|
|
1811
|
+
return Result.fail(toError(state));
|
|
1812
|
+
}
|
|
1813
|
+
return Result.succeed(a);
|
|
1814
|
+
};
|
|
1815
|
+
/**
|
|
1816
|
+
* Runs a parser against a complete input, requiring the whole input to be
|
|
1817
|
+
* consumed (winnow's `Parser::parse`).
|
|
1818
|
+
*
|
|
1819
|
+
* @example
|
|
1820
|
+
* ```ts
|
|
1821
|
+
* import { Result } from "effect"
|
|
1822
|
+
* import { Ascii, Parser } from "@thomasfosterau/effect-parse"
|
|
1823
|
+
*
|
|
1824
|
+
* Parser.parse(Ascii.decInt, "-42") // Result.succeed(-42)
|
|
1825
|
+
* Result.isFailure(Parser.parse(Ascii.decInt, "42x")) // true
|
|
1826
|
+
* ```
|
|
1827
|
+
*
|
|
1828
|
+
* @since 0.1.0
|
|
1829
|
+
* @category running
|
|
1830
|
+
*/
|
|
1831
|
+
export const parse = (self, input, options) => parseComplete(self, input, options);
|
|
1832
|
+
/**
|
|
1833
|
+
* Like {@link parse}, but throws the `ParseError` on failure.
|
|
1834
|
+
*
|
|
1835
|
+
* @since 0.1.0
|
|
1836
|
+
* @category running
|
|
1837
|
+
*/
|
|
1838
|
+
export const parseSync = (self, input, options) => {
|
|
1839
|
+
const result = parseComplete(self, input, options);
|
|
1840
|
+
if (Result.isSuccess(result))
|
|
1841
|
+
return result.success;
|
|
1842
|
+
throw result.failure;
|
|
1843
|
+
};
|
|
1844
|
+
/**
|
|
1845
|
+
* Runs a parser against the start of an input, returning the remaining
|
|
1846
|
+
* input along with the output, nom-style (winnow's `parse_peek`, nom's
|
|
1847
|
+
* `IResult`).
|
|
1848
|
+
*
|
|
1849
|
+
* @since 0.1.0
|
|
1850
|
+
* @category running
|
|
1851
|
+
*/
|
|
1852
|
+
export const parsePeek = (self, input, options) => {
|
|
1853
|
+
let state = makeState(input, options, false);
|
|
1854
|
+
const compiled = runCompiled(self, state, false);
|
|
1855
|
+
if (compiled !== NotCompiled && compiled !== Fail) {
|
|
1856
|
+
return Result.succeed([state.slice(state.pos, state.end), compiled]);
|
|
1857
|
+
}
|
|
1858
|
+
if (compiled === Fail)
|
|
1859
|
+
state = makeState(input, options, false);
|
|
1860
|
+
const a = self.step(state);
|
|
1861
|
+
if (a === Fail)
|
|
1862
|
+
return Result.fail(toError(state));
|
|
1863
|
+
return Result.succeed([state.slice(state.pos, state.end), a]);
|
|
1864
|
+
};
|
|
1865
|
+
/**
|
|
1866
|
+
* Runs a parser against a *partial* input, i.e. a chunk of a stream that may
|
|
1867
|
+
* be followed by more data (winnow's `Partial`, nom's `streaming` parsers).
|
|
1868
|
+
* Token parsers that reach the end of the chunk report `Incomplete` instead
|
|
1869
|
+
* of failing or succeeding early.
|
|
1870
|
+
*
|
|
1871
|
+
* The parser does not have to consume the whole input; the returned
|
|
1872
|
+
* `offset` says how much was consumed.
|
|
1873
|
+
*
|
|
1874
|
+
* @example
|
|
1875
|
+
* ```ts
|
|
1876
|
+
* import { Ascii, Parser } from "@thomasfosterau/effect-parse"
|
|
1877
|
+
*
|
|
1878
|
+
* Parser.parsePartial(Ascii.digit1, "123")
|
|
1879
|
+
* // Result.succeed({ _tag: "Incomplete", needed: Option.some(1) })
|
|
1880
|
+
* Parser.parsePartial(Ascii.digit1, "123;")
|
|
1881
|
+
* // Result.succeed({ _tag: "Done", value: "123", offset: 3 })
|
|
1882
|
+
* ```
|
|
1883
|
+
*
|
|
1884
|
+
* @since 0.1.0
|
|
1885
|
+
* @category running
|
|
1886
|
+
*/
|
|
1887
|
+
export const parsePartial = (self, input, options) => {
|
|
1888
|
+
const state = makeState(input, options, true);
|
|
1889
|
+
const a = self.step(state);
|
|
1890
|
+
if (a !== Fail)
|
|
1891
|
+
return Result.succeed({ _tag: "Done", value: a, offset: state.pos });
|
|
1892
|
+
if (state.mode === "Incomplete") {
|
|
1893
|
+
const needed = state.failure.needed;
|
|
1894
|
+
return Result.succeed({ _tag: "Incomplete", needed: needed > 0 ? Option.some(needed) : Option.none() });
|
|
1895
|
+
}
|
|
1896
|
+
return Result.fail(toError(state));
|
|
1897
|
+
};
|
|
1898
|
+
/**
|
|
1899
|
+
* Runs a parser against a complete input as an `Effect`. Services required
|
|
1900
|
+
* by the parser are taken from the Effect's context.
|
|
1901
|
+
*
|
|
1902
|
+
* @example
|
|
1903
|
+
* ```ts
|
|
1904
|
+
* import { Effect } from "effect"
|
|
1905
|
+
* import { Ascii, Parser } from "@thomasfosterau/effect-parse"
|
|
1906
|
+
*
|
|
1907
|
+
* const program = Effect.gen(function*() {
|
|
1908
|
+
* const n = yield* Parser.parseEffect(Ascii.decInt, "42")
|
|
1909
|
+
* return n + 1
|
|
1910
|
+
* })
|
|
1911
|
+
* ```
|
|
1912
|
+
*
|
|
1913
|
+
* @since 0.1.0
|
|
1914
|
+
* @category running
|
|
1915
|
+
*/
|
|
1916
|
+
export const parseEffect = (self, input, options) => Effect.flatMap(Effect.context(), (context) => Effect.fromResult(parseComplete(self, input, { ...options, context })));
|
|
1917
|
+
/**
|
|
1918
|
+
* Runs a parser with error recovery enabled (winnow's `Recoverable`
|
|
1919
|
+
* stream). Failures handled by {@link resumeAfter} and {@link retryAfter}
|
|
1920
|
+
* are collected instead of aborting the parse.
|
|
1921
|
+
*
|
|
1922
|
+
* @since 0.1.0
|
|
1923
|
+
* @category running
|
|
1924
|
+
*/
|
|
1925
|
+
export const parseRecoverable = (self, input, options) => {
|
|
1926
|
+
const state = makeState(input, options, false);
|
|
1927
|
+
const recovered = [];
|
|
1928
|
+
state.recovered = recovered;
|
|
1929
|
+
const result = runComplete(self, state);
|
|
1930
|
+
const errors = recovered.map((f) => ParseError.fromFailure(state.input, f, "Backtrack", state.encoding));
|
|
1931
|
+
if (Result.isSuccess(result))
|
|
1932
|
+
return { value: Option.some(result.success), errors };
|
|
1933
|
+
errors.push(result.failure);
|
|
1934
|
+
return { value: Option.none(), errors };
|
|
1935
|
+
};
|
|
1936
|
+
//# sourceMappingURL=Parser.js.map
|