@here.build/arrival-syntax 0.0.0-stage → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2026 here.build
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # @here.build/arrival-syntax
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Span-preserving Scheme s-expression forest. This is the syntax tree, not the evaluator.
4
+
5
+ `parseSexprs` answers “what did the user write, and where?” Arrival’s `Parser` answers “what does this program mean?” — it expands reader macros into `APair` / `AVector` / interned `ASymbol` and drops comments. Editors, the type-lens, and the sugarcoat round-trip need the first tree.
6
+
7
+ ```ts
8
+ import { parseSexprs } from "@here.build/arrival-syntax";
9
+
10
+ parseSexprs("(map f xs) ; trailing");
11
+ // [{ list: [{ atom: "map" }, { atom: "f" }, { atom: "xs" }], span: [0, 10], trail: ["; trailing"] }]
12
+ ```
13
+
14
+ `[]` and `{}` are containers (`open: "[" | "{"`), not atom glue. Racket `#:limit` mints as `:limit`. A `;` comment on its own line before a datum is that datum’s `lead`; one on the same line after is its `trail`.
15
+
16
+ `@here.build/arrival-sugarcoat` re-exports `parseSexprs` / `Node` and owns the Scheme↔sugarcoat lens on top. `@here.build/arrival`’s type-layer and `@here.build/arrival-types-bridge` import this package directly.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pnpm add @here.build/arrival-syntax
22
+ ```
23
+
24
+ ## License
25
+
26
+ [MIT](./LICENSE.md).
@@ -0,0 +1,63 @@
1
+ export type DecodeFailure = {
2
+ readonly ok: false;
3
+ readonly code: string;
4
+ readonly message: string;
5
+ readonly offset: number;
6
+ };
7
+ /** Result of strict R7RS escape decoding without throwing host exceptions. */
8
+ export type DecodeResult = {
9
+ readonly ok: true;
10
+ readonly value: string;
11
+ } | DecodeFailure;
12
+ /** Validate and decode `\x<hex>;` scalar escape starting right after `\x`. */
13
+ export declare function parseHexScalarEscape(src: string, startAfterX: number, errorCode: string): {
14
+ readonly ok: true;
15
+ readonly value: string;
16
+ readonly nextIndex: number;
17
+ } | DecodeFailure;
18
+ /** Decode a single R7RS hex scalar digit run without `;`, returning `null` if invalid or surrogate. */
19
+ export declare function decodeHexScalar(hex: string): string | null;
20
+ /**
21
+ * Decode the raw interior of an R7RS double-quoted string (without surrounding `"`).
22
+ * Handles R7RS §6.7 / §7.1.1 escapes (`\a`, `\b`, `\t`, `\n`, `\r`, `\"`, `\\`, `\|`,
23
+ * `\x<hex>;`, intraline `\` line continuations), literal tabs, and CRLF/CR → LF normalization.
24
+ */
25
+ export declare function decodeSchemeString(rawInner: string): DecodeResult;
26
+ /** Tolerant R7RS string decoder for IDE/lint paths: never throws, keeps malformed escapes verbatim. */
27
+ export declare function decodeSchemeStringTolerant(rawInner: string): string;
28
+ /**
29
+ * Decode the raw interior of an R7RS bar-quoted symbol segment (without enclosing `|...|`).
30
+ */
31
+ export declare function decodeBarSymbol(rawInner: string): DecodeResult;
32
+ /** One piece of a symbol token, tagged with whether it came from a `|...|` segment. */
33
+ export interface SymbolSegment {
34
+ readonly text: string;
35
+ readonly quoted: boolean;
36
+ }
37
+ /**
38
+ * Decode a symbol token that may compose unquoted and `|...|` bar-quoted runs
39
+ * (e.g. `|with\| bar|`, `a|b c|d`, `:|24|`, `||`).
40
+ */
41
+ export declare function decodeComposedSymbolSegments(raw: string): {
42
+ readonly ok: true;
43
+ readonly segments: readonly SymbolSegment[];
44
+ } | DecodeFailure;
45
+ /** Convenience wrapper decoding a possibly-composed `|...|` symbol into one string. */
46
+ export declare function decodeComposedSymbol(raw: string): DecodeResult;
47
+ /** True if printing `name` unquoted could fail to re-read as the exact same symbol. */
48
+ export declare function needsBarQuoting(name: string): boolean;
49
+ /** Escape a symbol's characters for `|...|` representation (R7RS §7.1.1). */
50
+ export declare function escapeBarContent(name: string): string;
51
+ /** Format `name` in R7RS external syntax so `parse(formatBarSymbol(name))` recovers `name`. */
52
+ export declare function formatBarSymbol(name: string): string;
53
+ /**
54
+ * Encode `value` as an R7RS §6.7 double-quoted string literal (`"..."`) using
55
+ * mnemonic escapes (`\\`, `\"`, `\a`, `\b`, `\t`, `\n`, `\r`) and `\x<hex>;`
56
+ * for all remaining C0/DEL control characters (never JSON-only `\u` or `\f`).
57
+ */
58
+ export declare function encodeSchemeString(value: string): string;
59
+ /** Format an unboxed JS number in canonical R7RS external syntax (`-0.0`, `+nan.0`, `+inf.0`, `-inf.0`). */
60
+ export declare function formatSchemeNumber(n: number): string;
61
+ /** Format a single character value in R7RS character-literal syntax (`#\space`, `#\x1`, `#\a`). */
62
+ export declare function formatCharLiteral(ch: string): string;
63
+ //# sourceMappingURL=decode.d.ts.map
package/dist/decode.js ADDED
@@ -0,0 +1,416 @@
1
+ const SINGLE_CHAR_ESCAPES = {
2
+ 97: "\u0007", // \a alarm (hex escape avoids raw control char in source)
3
+ 98: "\b", // \b backspace
4
+ 116: "\t", // \t tab
5
+ 110: "\n", // \n newline
6
+ 114: "\r", // \r return
7
+ 34: '"', // \" double quote
8
+ 92: "\\", // \\ backslash
9
+ 124: "|", // \| vertical bar (R7RS §7.1.1 inside both strings and |...|)
10
+ };
11
+ function isAsciiHex(cc) {
12
+ return (cc >= 48 && cc <= 57) || (cc >= 65 && cc <= 70) || (cc >= 97 && cc <= 102);
13
+ }
14
+ function isIntralineWs(cc) {
15
+ return cc === 32 /* space */ || cc === 9 /* \t */;
16
+ }
17
+ /** Validate and decode `\x<hex>;` scalar escape starting right after `\x`. */
18
+ export function parseHexScalarEscape(src, startAfterX, errorCode) {
19
+ const n = src.length;
20
+ let j = startAfterX;
21
+ while (j < n && isAsciiHex(src.charCodeAt(j)))
22
+ j++;
23
+ if (j === startAfterX) {
24
+ return {
25
+ ok: false,
26
+ code: errorCode,
27
+ message: String.raw `empty \x hex scalar escape; expected digits followed by ';'`,
28
+ offset: startAfterX - 2,
29
+ };
30
+ }
31
+ if (j >= n || src.charCodeAt(j) !== 59 /* ; */) {
32
+ return {
33
+ ok: false,
34
+ code: errorCode,
35
+ message: String.raw `unterminated \x hex scalar escape; R7RS requires a trailing ';' (e.g. \x41;)`,
36
+ offset: startAfterX - 2,
37
+ };
38
+ }
39
+ const cp = Number.parseInt(src.slice(startAfterX, j), 16);
40
+ if (!Number.isFinite(cp) || cp > 0x10_ff_ff || (cp >= 0xd8_00 && cp <= 0xdf_ff)) {
41
+ return {
42
+ ok: false,
43
+ code: errorCode,
44
+ message: `invalid Unicode scalar value U+${cp.toString(16).toUpperCase()} in hex escape`,
45
+ offset: startAfterX - 2,
46
+ };
47
+ }
48
+ return { ok: true, value: String.fromCodePoint(cp), nextIndex: j + 1 };
49
+ }
50
+ /** Skip R7RS intraline continuation: `<intraline>* <line-ending> <intraline>*`, or return `-1`. */
51
+ function matchLineContinuation(src, afterSlash) {
52
+ const n = src.length;
53
+ let j = afterSlash;
54
+ while (j < n && isIntralineWs(src.charCodeAt(j)))
55
+ j++;
56
+ if (j >= n)
57
+ return -1;
58
+ const cc = src.charCodeAt(j);
59
+ if (cc === 13 /* \r */) {
60
+ j += src.charCodeAt(j + 1) === 10 /* \n */ ? 2 : 1;
61
+ }
62
+ else if (cc === 10 /* \n */) {
63
+ j += 1;
64
+ }
65
+ else {
66
+ return -1;
67
+ }
68
+ while (j < n && isIntralineWs(src.charCodeAt(j)))
69
+ j++;
70
+ return j;
71
+ }
72
+ /** Decode a single R7RS hex scalar digit run without `;`, returning `null` if invalid or surrogate. */
73
+ export function decodeHexScalar(hex) {
74
+ if (hex.length === 0)
75
+ return null;
76
+ for (let i = 0; i < hex.length; i++) {
77
+ if (!isAsciiHex(hex.charCodeAt(i)))
78
+ return null;
79
+ }
80
+ const cp = Number.parseInt(hex, 16);
81
+ if (!Number.isFinite(cp) || cp > 0x10_ff_ff || (cp >= 0xd8_00 && cp <= 0xdf_ff))
82
+ return null;
83
+ return String.fromCodePoint(cp);
84
+ }
85
+ /**
86
+ * Decode the raw interior of an R7RS double-quoted string (without surrounding `"`).
87
+ * Handles R7RS §6.7 / §7.1.1 escapes (`\a`, `\b`, `\t`, `\n`, `\r`, `\"`, `\\`, `\|`,
88
+ * `\x<hex>;`, intraline `\` line continuations), literal tabs, and CRLF/CR → LF normalization.
89
+ */
90
+ export function decodeSchemeString(rawInner) {
91
+ const out = [];
92
+ const n = rawInner.length;
93
+ for (let i = 0; i < n; i++) {
94
+ const cc = rawInner.charCodeAt(i);
95
+ if (cc === 13 /* \r */) {
96
+ if (rawInner.charCodeAt(i + 1) === 10 /* \n */)
97
+ i++;
98
+ out.push("\n");
99
+ continue;
100
+ }
101
+ if (cc !== 92 /* \ */) {
102
+ out.push(rawInner[i]);
103
+ continue;
104
+ }
105
+ if (i + 1 >= n) {
106
+ return { ok: false, code: "E-STRING-ESCAPE", message: "trailing backslash in string literal", offset: i };
107
+ }
108
+ const cont = matchLineContinuation(rawInner, i + 1);
109
+ if (cont !== -1) {
110
+ i = cont - 1;
111
+ continue;
112
+ }
113
+ const esc = rawInner.charCodeAt(i + 1);
114
+ const mapped = SINGLE_CHAR_ESCAPES[esc];
115
+ if (mapped !== undefined) {
116
+ out.push(mapped);
117
+ i++;
118
+ continue;
119
+ }
120
+ if (esc === 120 /* x */) {
121
+ const hex = parseHexScalarEscape(rawInner, i + 2, "E-STRING-ESCAPE");
122
+ if (!hex.ok)
123
+ return hex;
124
+ out.push(hex.value);
125
+ i = hex.nextIndex - 1;
126
+ continue;
127
+ }
128
+ const escChar = rawInner[i + 1];
129
+ const msg = esc === 117 /* u */
130
+ ? String.raw `invalid escape '\u' in R7RS string literal — use R7RS hex escape '\x<hex>;'`
131
+ : `invalid escape sequence '\\${escChar}' in string literal`;
132
+ return { ok: false, code: "E-STRING-ESCAPE", message: msg, offset: i };
133
+ }
134
+ return { ok: true, value: out.join("") };
135
+ }
136
+ /** Tolerant R7RS string decoder for IDE/lint paths: never throws, keeps malformed escapes verbatim. */
137
+ export function decodeSchemeStringTolerant(rawInner) {
138
+ const out = [];
139
+ const n = rawInner.length;
140
+ for (let i = 0; i < n; i++) {
141
+ const cc = rawInner.charCodeAt(i);
142
+ if (cc === 13 /* \r */) {
143
+ if (rawInner.charCodeAt(i + 1) === 10 /* \n */)
144
+ i++;
145
+ out.push("\n");
146
+ continue;
147
+ }
148
+ if (cc !== 92 /* \ */ || i + 1 >= n) {
149
+ out.push(rawInner[i]);
150
+ continue;
151
+ }
152
+ const cont = matchLineContinuation(rawInner, i + 1);
153
+ if (cont !== -1) {
154
+ i = cont - 1;
155
+ continue;
156
+ }
157
+ const esc = rawInner.charCodeAt(i + 1);
158
+ const mapped = SINGLE_CHAR_ESCAPES[esc];
159
+ if (mapped !== undefined) {
160
+ out.push(mapped);
161
+ i++;
162
+ continue;
163
+ }
164
+ if (esc === 120 /* x */) {
165
+ const hex = parseHexScalarEscape(rawInner, i + 2, "E-STRING-ESCAPE");
166
+ if (hex.ok) {
167
+ out.push(hex.value);
168
+ i = hex.nextIndex - 1;
169
+ continue;
170
+ }
171
+ }
172
+ out.push("\\", rawInner[i + 1]);
173
+ i++;
174
+ }
175
+ return out.join("");
176
+ }
177
+ /**
178
+ * Decode the raw interior of an R7RS bar-quoted symbol segment (without enclosing `|...|`).
179
+ */
180
+ export function decodeBarSymbol(rawInner) {
181
+ const out = [];
182
+ const n = rawInner.length;
183
+ for (let i = 0; i < n; i++) {
184
+ const cc = rawInner.charCodeAt(i);
185
+ if (cc !== 92 /* \ */) {
186
+ out.push(rawInner[i]);
187
+ continue;
188
+ }
189
+ if (i + 1 >= n) {
190
+ return { ok: false, code: "E-SYMBOL-BAR-ESCAPE", message: "trailing backslash inside |...| symbol", offset: i };
191
+ }
192
+ const cont = matchLineContinuation(rawInner, i + 1);
193
+ if (cont !== -1) {
194
+ i = cont - 1;
195
+ continue;
196
+ }
197
+ const esc = rawInner.charCodeAt(i + 1);
198
+ const mapped = SINGLE_CHAR_ESCAPES[esc];
199
+ if (mapped !== undefined) {
200
+ out.push(mapped);
201
+ i++;
202
+ continue;
203
+ }
204
+ if (esc === 120 /* x */) {
205
+ const hex = parseHexScalarEscape(rawInner, i + 2, "E-SYMBOL-BAR-ESCAPE");
206
+ if (!hex.ok)
207
+ return hex;
208
+ out.push(hex.value);
209
+ i = hex.nextIndex - 1;
210
+ continue;
211
+ }
212
+ return {
213
+ ok: false,
214
+ code: "E-SYMBOL-BAR-ESCAPE",
215
+ message: `invalid escape '\\${rawInner[i + 1]}' inside |...| symbol`,
216
+ offset: i,
217
+ };
218
+ }
219
+ return { ok: true, value: out.join("") };
220
+ }
221
+ /**
222
+ * Decode a symbol token that may compose unquoted and `|...|` bar-quoted runs
223
+ * (e.g. `|with\| bar|`, `a|b c|d`, `:|24|`, `||`).
224
+ */
225
+ export function decodeComposedSymbolSegments(raw) {
226
+ const segments = [];
227
+ const n = raw.length;
228
+ let plainStart = 0;
229
+ let i = 0;
230
+ while (i < n) {
231
+ if (raw.charCodeAt(i) !== 124 /* | */) {
232
+ i++;
233
+ continue;
234
+ }
235
+ if (i > plainStart) {
236
+ segments.push({ text: raw.slice(plainStart, i), quoted: false });
237
+ }
238
+ const barStart = i + 1;
239
+ let j = barStart;
240
+ while (j < n) {
241
+ const cc = raw.charCodeAt(j);
242
+ if (cc === 92 /* \ */) {
243
+ j += 2;
244
+ continue;
245
+ }
246
+ if (cc === 124 /* | */)
247
+ break;
248
+ j++;
249
+ }
250
+ if (j >= n || raw.charCodeAt(j) !== 124 /* | */) {
251
+ return {
252
+ ok: false,
253
+ code: "E-UNTERMINATED",
254
+ message: "unterminated bar-quoted symbol '|'",
255
+ offset: i,
256
+ };
257
+ }
258
+ const decoded = decodeBarSymbol(raw.slice(barStart, j));
259
+ if (!decoded.ok)
260
+ return decoded;
261
+ segments.push({ text: decoded.value, quoted: true });
262
+ i = j + 1;
263
+ plainStart = i;
264
+ }
265
+ if (plainStart < n) {
266
+ segments.push({ text: raw.slice(plainStart, n), quoted: false });
267
+ }
268
+ return { ok: true, segments };
269
+ }
270
+ /** Convenience wrapper decoding a possibly-composed `|...|` symbol into one string. */
271
+ export function decodeComposedSymbol(raw) {
272
+ const segs = decodeComposedSymbolSegments(raw);
273
+ if (!segs.ok)
274
+ return segs;
275
+ return { ok: true, value: segs.segments.map((s) => s.text).join("") };
276
+ }
277
+ const DELIM_OR_SPECIAL_CODES = new Set([
278
+ 9,
279
+ 10,
280
+ 11,
281
+ 12,
282
+ 13,
283
+ 32, // whitespace
284
+ 40,
285
+ 41, // ( )
286
+ 91,
287
+ 93, // [ ]
288
+ 123,
289
+ 125, // { }
290
+ 34, // "
291
+ 59, // ;
292
+ 124, // |
293
+ 92, // \
294
+ 44, // ,
295
+ 96, // `
296
+ 39, // '
297
+ 35, // #
298
+ ]);
299
+ const PLAIN_NUMBER_LOOKALIKE_RE = /^(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|[+-]?\d+\/\d+|[+-]?(?:inf|nan)\.0)$/i;
300
+ /** True if printing `name` unquoted could fail to re-read as the exact same symbol. */
301
+ export function needsBarQuoting(name) {
302
+ if (name.length === 0 || name === ".")
303
+ return true;
304
+ for (let i = 0; i < name.length; i++) {
305
+ const cc = name.charCodeAt(i);
306
+ if (cc < 32 || cc === 127 || DELIM_OR_SPECIAL_CODES.has(cc))
307
+ return true;
308
+ // Also treat Unicode whitespace (e.g. NBSP, EM SPACE) as requiring quotes.
309
+ if (cc > 127 && /\s/.test(name[i]))
310
+ return true;
311
+ }
312
+ if (name.charCodeAt(0) === 58 /* : */ && name.length > 1)
313
+ return false;
314
+ if (PLAIN_NUMBER_LOOKALIKE_RE.test(name))
315
+ return true;
316
+ return false;
317
+ }
318
+ /** Escape a symbol's characters for `|...|` representation (R7RS §7.1.1). */
319
+ export function escapeBarContent(name) {
320
+ const out = [];
321
+ for (let i = 0; i < name.length; i++) {
322
+ const cc = name.charCodeAt(i);
323
+ if (cc === 124 /* | */)
324
+ out.push(String.raw `\|`);
325
+ else if (cc === 92 /* \ */)
326
+ out.push("\\\\");
327
+ else if (cc === 7)
328
+ out.push(String.raw `\a`);
329
+ else if (cc === 8)
330
+ out.push(String.raw `\b`);
331
+ else if (cc === 9)
332
+ out.push(String.raw `\t`);
333
+ else if (cc === 10)
334
+ out.push(String.raw `\n`);
335
+ else if (cc === 13)
336
+ out.push(String.raw `\r`);
337
+ else if (cc < 32 || cc === 127)
338
+ out.push(String.raw `\x${cc.toString(16)};`);
339
+ else
340
+ out.push(name[i]);
341
+ }
342
+ return out.join("");
343
+ }
344
+ /** Format `name` in R7RS external syntax so `parse(formatBarSymbol(name))` recovers `name`. */
345
+ export function formatBarSymbol(name) {
346
+ if (!needsBarQuoting(name))
347
+ return name;
348
+ return `|${escapeBarContent(name)}|`;
349
+ }
350
+ /**
351
+ * Encode `value` as an R7RS §6.7 double-quoted string literal (`"..."`) using
352
+ * mnemonic escapes (`\\`, `\"`, `\a`, `\b`, `\t`, `\n`, `\r`) and `\x<hex>;`
353
+ * for all remaining C0/DEL control characters (never JSON-only `\u` or `\f`).
354
+ */
355
+ export function encodeSchemeString(value) {
356
+ const out = ['"'];
357
+ for (let i = 0; i < value.length; i++) {
358
+ const cc = value.charCodeAt(i);
359
+ if (cc === 92 /* \ */)
360
+ out.push("\\\\");
361
+ else if (cc === 34 /* " */)
362
+ out.push(String.raw `\"`);
363
+ else if (cc === 7)
364
+ out.push(String.raw `\a`);
365
+ else if (cc === 8)
366
+ out.push(String.raw `\b`);
367
+ else if (cc === 9)
368
+ out.push(String.raw `\t`);
369
+ else if (cc === 10)
370
+ out.push(String.raw `\n`);
371
+ else if (cc === 13)
372
+ out.push(String.raw `\r`);
373
+ else if (cc < 32 || cc === 127)
374
+ out.push(String.raw `\x${cc.toString(16)};`);
375
+ else
376
+ out.push(value[i]);
377
+ }
378
+ out.push('"');
379
+ return out.join("");
380
+ }
381
+ /** Format an unboxed JS number in canonical R7RS external syntax (`-0.0`, `+nan.0`, `+inf.0`, `-inf.0`). */
382
+ export function formatSchemeNumber(n) {
383
+ if (Number.isNaN(n))
384
+ return "+nan.0";
385
+ if (n === Infinity)
386
+ return "+inf.0";
387
+ if (n === -Infinity)
388
+ return "-inf.0";
389
+ if (Object.is(n, -0))
390
+ return "-0.0";
391
+ return String(n);
392
+ }
393
+ const CANONICAL_NAMED_CHARS = {
394
+ "\u0007": String.raw `#\alarm`,
395
+ "\b": String.raw `#\backspace`,
396
+ "\u007F": String.raw `#\delete`,
397
+ "\u001B": String.raw `#\escape`,
398
+ "\n": String.raw `#\newline`,
399
+ "\0": String.raw `#\null`,
400
+ "\r": String.raw `#\return`,
401
+ " ": String.raw `#\space`,
402
+ "\t": String.raw `#\tab`,
403
+ };
404
+ /** Format a single character value in R7RS character-literal syntax (`#\space`, `#\x1`, `#\a`). */
405
+ export function formatCharLiteral(ch) {
406
+ const named = CANONICAL_NAMED_CHARS[ch];
407
+ if (named !== undefined)
408
+ return named;
409
+ if ([...ch].length === 1) {
410
+ const cp = ch.codePointAt(0);
411
+ if (cp < 32 || cp === 127)
412
+ return String.raw `#\x${cp.toString(16)}`;
413
+ }
414
+ return `#\\${ch}`;
415
+ }
416
+ //# sourceMappingURL=decode.js.map
@@ -0,0 +1,22 @@
1
+ /** Half-open UTF-16 byte/code-unit range `[start, end)` in original source text. */
2
+ export type Span = readonly [start: number, end: number];
3
+ /** Structured lexical or syntactic diagnostic emitted without throwing in tolerant mode. */
4
+ export interface SyntaxDiagnostic {
5
+ readonly code: string;
6
+ readonly message: string;
7
+ readonly span: Span;
8
+ readonly unterminated?: boolean;
9
+ readonly hint?: string;
10
+ }
11
+ /** Syntax error thrown by strict {@link parseSexprs} / {@link parseSyntax} when tolerant is false. */
12
+ export declare class ArrivalSyntaxError extends Error {
13
+ readonly code: string;
14
+ readonly span: Span;
15
+ readonly unterminated: boolean;
16
+ readonly hint?: string;
17
+ constructor(code: string, message: string, span: Span, opts?: {
18
+ unterminated?: boolean;
19
+ hint?: string;
20
+ });
21
+ }
22
+ //# sourceMappingURL=errors.d.ts.map
package/dist/errors.js ADDED
@@ -0,0 +1,16 @@
1
+ /** Syntax error thrown by strict {@link parseSexprs} / {@link parseSyntax} when tolerant is false. */
2
+ export class ArrivalSyntaxError extends Error {
3
+ code;
4
+ span;
5
+ unterminated;
6
+ hint;
7
+ constructor(code, message, span, opts) {
8
+ super(message);
9
+ this.name = "ArrivalSyntaxError";
10
+ this.code = code;
11
+ this.span = span;
12
+ this.unterminated = opts?.unterminated ?? false;
13
+ this.hint = opts?.hint;
14
+ }
15
+ }
16
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,7 @@
1
+ export { decodeBarSymbol, decodeComposedSymbol, decodeComposedSymbolSegments, decodeHexScalar, type DecodeFailure, type DecodeResult, decodeSchemeString, decodeSchemeStringTolerant, encodeSchemeString, escapeBarContent, formatBarSymbol, formatCharLiteral, formatSchemeNumber, needsBarQuoting, parseHexScalarEscape, type SymbolSegment, } from "./decode.js";
2
+ export { ArrivalSyntaxError, type Span, type SyntaxDiagnostic } from "./errors.js";
3
+ export { balanceSchemePrefix, closeSuffix, type Dialect, isDelimiterCharCode, isWhitespaceCharCode, type LexOptions, type LexResult, lexScheme, type Token, tokenAtOffset, TokenFlags, TokenKind, trailingAtomRange, } from "./lexer.js";
4
+ export { type LineCol, LineIndex } from "./line-index.js";
5
+ export { flipSuffixKey, normalizePolyglotScheme, type NormalizePolyglotOptions } from "./normalize.js";
6
+ export { type AtomNode, type ListNode, type ListOpen, type Node, parseSexprs, parseSexprsTolerant, parseSyntax, type ParseSyntaxOptions, type ParseSyntaxResult, } from "./parse-syntax.js";
7
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ // @here.build/arrival-syntax — zero-dependency R7RS/polyglot Scheme lexer, CST/AST forest & normalizer.
2
+ export { decodeBarSymbol, decodeComposedSymbol, decodeComposedSymbolSegments, decodeHexScalar, decodeSchemeString, decodeSchemeStringTolerant, encodeSchemeString, escapeBarContent, formatBarSymbol, formatCharLiteral, formatSchemeNumber, needsBarQuoting, parseHexScalarEscape, } from "./decode.js";
3
+ export { ArrivalSyntaxError } from "./errors.js";
4
+ export { balanceSchemePrefix, closeSuffix, isDelimiterCharCode, isWhitespaceCharCode, lexScheme, tokenAtOffset, TokenFlags, TokenKind, trailingAtomRange, } from "./lexer.js";
5
+ export { LineIndex } from "./line-index.js";
6
+ export { flipSuffixKey, normalizePolyglotScheme } from "./normalize.js";
7
+ export { parseSexprs, parseSexprsTolerant, parseSyntax, } from "./parse-syntax.js";
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,90 @@
1
+ import type { Span, SyntaxDiagnostic } from "./errors.js";
2
+ export type Dialect = "scheme" | "sweet" | "sugarcoat";
3
+ /** Bitmask metadata carried by every lexed {@link Token}. */
4
+ export declare const TokenFlags: {
5
+ readonly None: 0;
6
+ /** `token.span[0] === prevSignificant.span[1]` — TIGHT adjacency (`r[:id]`, `.op{}`, `@()`). */
7
+ readonly AdjacentToPrev: number;
8
+ /** Unclosed string, block comment, bar symbol, or truncated `#\` at EOF in tolerant mode. */
9
+ readonly Unterminated: number;
10
+ /** Token contains `|...|` bar-quoted escape segment(s). */
11
+ readonly HasBarEscape: number;
12
+ /** Token contains `\` escape sequence(s). */
13
+ readonly HasBackslashEscape: number;
14
+ /** `#!fold-case` was active when this token was lexed. */
15
+ readonly CaseFolded: number;
16
+ };
17
+ export declare const TokenKind: {
18
+ readonly LParen: "LParen";
19
+ readonly RParen: "RParen";
20
+ readonly LBracket: "LBracket";
21
+ readonly RBracket: "RBracket";
22
+ readonly LBrace: "LBrace";
23
+ readonly RBrace: "RBrace";
24
+ readonly VectorOpen: "VectorOpen";
25
+ readonly BytevectorOpen: "BytevectorOpen";
26
+ readonly Quote: "Quote";
27
+ readonly Quasiquote: "Quasiquote";
28
+ readonly Unquote: "Unquote";
29
+ readonly UnquoteSplicing: "UnquoteSplicing";
30
+ readonly DatumComment: "DatumComment";
31
+ readonly DatumLabelDef: "DatumLabelDef";
32
+ readonly DatumLabelRef: "DatumLabelRef";
33
+ readonly Dot: "Dot";
34
+ readonly String: "String";
35
+ readonly Char: "Char";
36
+ readonly Bool: "Bool";
37
+ readonly SpecialLit: "SpecialLit";
38
+ readonly Directive: "Directive";
39
+ readonly Keyword: "Keyword";
40
+ readonly Symbol: "Symbol";
41
+ readonly Whitespace: "Whitespace";
42
+ readonly LineComment: "LineComment";
43
+ readonly BlockComment: "BlockComment";
44
+ readonly Invalid: "Invalid";
45
+ };
46
+ export type TokenKind = (typeof TokenKind)[keyof typeof TokenKind];
47
+ export interface Token {
48
+ readonly kind: TokenKind;
49
+ readonly span: Span;
50
+ readonly raw: string;
51
+ readonly flags: number;
52
+ readonly errorCode?: string;
53
+ readonly errorMessage?: string;
54
+ }
55
+ export interface LexOptions {
56
+ readonly dialect?: Dialect;
57
+ readonly tolerant?: boolean;
58
+ readonly strict?: boolean;
59
+ readonly attachTrivia?: boolean;
60
+ readonly flatStream?: boolean;
61
+ }
62
+ export interface LexResult {
63
+ readonly tokens: readonly Token[];
64
+ readonly diagnostics: readonly SyntaxDiagnostic[];
65
+ readonly openDelims: readonly string[];
66
+ readonly unterminatedKind: "string" | "block-comment" | "bar-symbol" | "char" | null;
67
+ readonly trailingBackslashInString: boolean;
68
+ readonly unclosedBlockCommentDepth: number;
69
+ }
70
+ /** True when UTF-16 code unit `cc` acts as whitespace. */
71
+ export declare function isWhitespaceCharCode(cc: number): boolean;
72
+ /** True when UTF-16 code unit `cc` terminates unquoted Scheme tokens (R7RS §7.1.1 + Arrival containers/commas). */
73
+ export declare function isDelimiterCharCode(cc: number): boolean;
74
+ /**
75
+ * Single-pass charCode DFA lexer over `src`, returning lossless spans `[start, end)` in original UTF-16
76
+ * code units (never stripping `\r` and never state-hijacking across whitespace/delimiters).
77
+ */
78
+ export declare function lexScheme(src: string, opts?: LexOptions): LexResult;
79
+ /** Find the non-trivia token covering `offset` (or abutting `offset - 1` at atom end), or `null`. */
80
+ export declare function tokenAtOffset(src: string, offset: number): Token | null;
81
+ /**
82
+ * Compute `[start, src.length]` for the incomplete atom immediately preceding EOF (or cursor offset),
83
+ * cleanly stopping at true R7RS delimiters including `,` and `` ` ``.
84
+ */
85
+ export declare function trailingAtomRange(src: string): Span;
86
+ /** Return the exact closing suffix (including unterminated block-comment / string / bar / containers) for `src`. */
87
+ export declare function closeSuffix(src: string): string;
88
+ /** Balance an incomplete Scheme prefix so IDE cursor queries parse cleanly without throwing. */
89
+ export declare function balanceSchemePrefix(src: string): string;
90
+ //# sourceMappingURL=lexer.d.ts.map