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