@here.build/arrival-syntax 0.10.0 → 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.
@@ -0,0 +1,27 @@
1
+ import type { Span } from "./errors.js";
2
+ /** 0-based line / 0-based UTF-16 column coordinate in source text. */
3
+ export interface LineCol {
4
+ readonly line: number;
5
+ readonly col: number;
6
+ }
7
+ /**
8
+ * Immutable line-start offset table built in one `charCodeAt` pass over the ORIGINAL
9
+ * source string without stripping `\r` (preserving exact UTF-16 offsets across LF, CRLF,
10
+ * and standalone CR).
11
+ */
12
+ export declare class LineIndex {
13
+ readonly length: number;
14
+ readonly starts: readonly number[];
15
+ constructor(src: string);
16
+ get lineCount(): number;
17
+ /** Map a UTF-16 offset into `{ line, col }` (0-based line, 0-based col). */
18
+ offsetToLineCol(offset: number): LineCol;
19
+ /** Map a UTF-16 offset into Arrival reader coordinates (1-based line, 0-based col). */
20
+ offsetToLine1Col0(offset: number): LineCol;
21
+ /** Convert a half-open UTF-16 span `[start, end)` into start/end line/col coordinates. */
22
+ spanToLineCols(span: Span): {
23
+ readonly start: LineCol;
24
+ readonly end: LineCol;
25
+ };
26
+ }
27
+ //# sourceMappingURL=line-index.d.ts.map
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Immutable line-start offset table built in one `charCodeAt` pass over the ORIGINAL
3
+ * source string without stripping `\r` (preserving exact UTF-16 offsets across LF, CRLF,
4
+ * and standalone CR).
5
+ */
6
+ export class LineIndex {
7
+ length;
8
+ starts;
9
+ constructor(src) {
10
+ this.length = src.length;
11
+ const starts = [0];
12
+ for (let i = 0; i < src.length; i++) {
13
+ const cc = src.charCodeAt(i);
14
+ if (cc === 13 /* \r */) {
15
+ if (src.charCodeAt(i + 1) === 10 /* \n */)
16
+ i++;
17
+ starts.push(i + 1);
18
+ }
19
+ else if (cc === 10 /* \n */) {
20
+ starts.push(i + 1);
21
+ }
22
+ }
23
+ this.starts = starts;
24
+ }
25
+ get lineCount() {
26
+ return this.starts.length;
27
+ }
28
+ /** Map a UTF-16 offset into `{ line, col }` (0-based line, 0-based col). */
29
+ offsetToLineCol(offset) {
30
+ const clamped = offset < 0 ? 0 : Math.min(offset, this.length);
31
+ const starts = this.starts;
32
+ let lo = 0;
33
+ let hi = starts.length - 1;
34
+ while (lo < hi) {
35
+ const mid = (lo + hi + 1) >>> 1;
36
+ if (starts[mid] <= clamped)
37
+ lo = mid;
38
+ else
39
+ hi = mid - 1;
40
+ }
41
+ return { line: lo, col: clamped - starts[lo] };
42
+ }
43
+ /** Map a UTF-16 offset into Arrival reader coordinates (1-based line, 0-based col). */
44
+ offsetToLine1Col0(offset) {
45
+ const lc = this.offsetToLineCol(offset);
46
+ return { line: lc.line + 1, col: lc.col };
47
+ }
48
+ /** Convert a half-open UTF-16 span `[start, end)` into start/end line/col coordinates. */
49
+ spanToLineCols(span) {
50
+ return {
51
+ start: this.offsetToLineCol(span[0]),
52
+ end: this.offsetToLineCol(span[1]),
53
+ };
54
+ }
55
+ }
56
+ //# sourceMappingURL=line-index.js.map
@@ -0,0 +1,16 @@
1
+ import type { Node } from "./parse-syntax.js";
2
+ export interface NormalizePolyglotOptions {
3
+ /** Allow `{a + b}` curly-infix lowering for odd brace forms (used by Sugarcoat). Default: `false`. */
4
+ readonly allowCurlyInfix?: boolean;
5
+ /** Also rewrite `[...]` / `{...}` inside `quote` / `quasiquote` (used by Sugarcoat). Default: `false`. */
6
+ readonly lowerContainersInQuote?: boolean;
7
+ }
8
+ /** Suffix keyword flip for dict keys: `name:` -> `:name`, rejecting `::` (`name::` stays unflipped). */
9
+ export declare const flipSuffixKey: (nd: Node) => Node;
10
+ /**
11
+ * Lower Arrival polyglot supersets (`[...]` vectors, `{...}` dicts/infix, BG2a/b `let`,
12
+ * Decision 1 flat `(lambda [x y] ...)`, BG9 `cond`/`case`/`do` clauses) into canonical paren forms
13
+ * while preserving R7RS `#(...)` and `#u8(...)` containers and node spans/comments.
14
+ */
15
+ export declare function normalizePolyglotScheme(forms: readonly Node[], opts?: NormalizePolyglotOptions): Node[];
16
+ //# sourceMappingURL=normalize.d.ts.map
@@ -0,0 +1,205 @@
1
+ const POLY_LET_FAMILY = new Set(["let", "let*", "letrec", "letrec*"]);
2
+ const POLY_CLAUSE_HEADS = new Set(["cond", "case"]);
3
+ const POLY_QUOTE_HEADS = new Set(["quote", "quasiquote"]);
4
+ const POLY_SYNTAX_OPAQUE = new Set(["define-syntax", "define-syntax-rule", "syntax-rules"]);
5
+ const POLY_LET_SYNTAX = new Set(["let-syntax", "letrec-syntax"]);
6
+ const isAtom = (nd) => nd != null && "atom" in nd;
7
+ const isList = (nd) => nd != null && "list" in nd;
8
+ /** Preserve `lead`, `trail`, `span` on a rewritten list while stripping container `open`. */
9
+ function withParenList(nd, list) {
10
+ const out = { list };
11
+ if (nd.lead !== undefined)
12
+ out.lead = nd.lead;
13
+ if (nd.trail !== undefined)
14
+ out.trail = nd.trail;
15
+ if (nd.span !== undefined)
16
+ out.span = nd.span;
17
+ return out;
18
+ }
19
+ /** Binding pair shape `(name value)` — single atom name + one value expression. */
20
+ const isPairBinding = (nd) => isList(nd) && nd.list.length === 2 && isAtom(nd.list[0]);
21
+ /** Suffix keyword flip for dict keys: `name:` -> `:name`, rejecting `::` (`name::` stays unflipped). */
22
+ export const flipSuffixKey = (nd) => {
23
+ if (!isAtom(nd) || nd.str)
24
+ return nd;
25
+ const a = nd.atom;
26
+ if (a.length > 1 && a.endsWith(":") && !a.endsWith("::") && !a.startsWith(":")) {
27
+ return { ...nd, atom: `:${a.slice(0, -1)}` };
28
+ }
29
+ return nd;
30
+ };
31
+ function stripJsonColons(items) {
32
+ const out = [];
33
+ for (let i = 0; i < items.length; i++) {
34
+ const cur = items[i];
35
+ if (out.length % 2 === 1 && isAtom(cur) && !cur.str && cur.atom === ":" && i + 1 < items.length) {
36
+ continue;
37
+ }
38
+ out.push(cur);
39
+ }
40
+ return out;
41
+ }
42
+ function lowerBrace(nd, mapChild, allowCurlyInfix) {
43
+ const rawKids = nd.list.map(mapChild);
44
+ const kids = stripJsonColons(rawKids);
45
+ if (allowCurlyInfix && kids.length >= 3 && kids.length % 2 === 1) {
46
+ const op0 = kids[1];
47
+ if (isAtom(op0) && !op0.str) {
48
+ const op = op0.atom;
49
+ let ok = true;
50
+ for (let i = 1; i < kids.length; i += 2) {
51
+ const o = kids[i];
52
+ if (!isAtom(o) || o.str || o.atom !== op) {
53
+ ok = false;
54
+ break;
55
+ }
56
+ }
57
+ if (ok) {
58
+ const operands = [];
59
+ for (let i = 0; i < kids.length; i += 2)
60
+ operands.push(kids[i]);
61
+ return withParenList(nd, [{ atom: op }, ...operands]);
62
+ }
63
+ }
64
+ }
65
+ if (!allowCurlyInfix || kids.length % 2 === 0) {
66
+ const out = [{ atom: "dict" }];
67
+ for (const [i, kid] of kids.entries()) {
68
+ out.push(i % 2 === 0 ? flipSuffixKey(kid) : kid);
69
+ }
70
+ return withParenList(nd, out);
71
+ }
72
+ // Fallback for malformed odd non-infix brace expression under Sugarcoat.
73
+ return withParenList(nd, kids);
74
+ }
75
+ function lowerBindings(binds, form, mapChild) {
76
+ if (!isList(binds))
77
+ return binds;
78
+ const open = binds.open ?? "(";
79
+ const els = binds.list;
80
+ // BG2a whole-list: `[a 1 b 2]` -> `((a 1) (b 2))`.
81
+ if (open === "[" && (els.length === 0 || !els.every(isPairBinding))) {
82
+ if (form === "do" || els.length % 2 !== 0) {
83
+ return withParenList(binds, [{ atom: "vector" }, ...els.map(mapChild)]);
84
+ }
85
+ const pairs = [];
86
+ for (let i = 0; i < els.length; i += 2) {
87
+ pairs.push({ list: [mapChild(els[i]), mapChild(els[i + 1])] });
88
+ }
89
+ return withParenList(binds, pairs);
90
+ }
91
+ // BG2b per-element: `([a 1] [b 2])` or `(do ([i 0 (+ i 1)]) ...)`.
92
+ return withParenList(binds, els.map((el) => {
93
+ if (!isList(el))
94
+ return el;
95
+ if (el.list.length === 2 || (form === "do" && el.list.length === 3)) {
96
+ return withParenList(el, el.list.map(mapChild));
97
+ }
98
+ return mapChild(el);
99
+ }));
100
+ }
101
+ function lowerClause(cl, isCase, mapExpr) {
102
+ if (!isList(cl))
103
+ return mapExpr(cl);
104
+ if (cl.open !== "[" && cl.open !== undefined)
105
+ return mapExpr(cl);
106
+ if (isCase && cl.list.length > 0) {
107
+ // `(case key ((datum1 datum2) body...))`: never rewrite the datum list `cl.list[0]` as an expr!
108
+ return withParenList(cl, [cl.list[0], ...cl.list.slice(1).map(mapExpr)]);
109
+ }
110
+ return withParenList(cl, cl.list.map(mapExpr));
111
+ }
112
+ function isFlatSymbolVector(nd) {
113
+ return isList(nd) && nd.open === "[" && nd.list.every((el) => isAtom(el) && !el.str && el.atom !== ".");
114
+ }
115
+ /**
116
+ * Lower Arrival polyglot supersets (`[...]` vectors, `{...}` dicts/infix, BG2a/b `let`,
117
+ * Decision 1 flat `(lambda [x y] ...)`, BG9 `cond`/`case`/`do` clauses) into canonical paren forms
118
+ * while preserving R7RS `#(...)` and `#u8(...)` containers and node spans/comments.
119
+ */
120
+ export function normalizePolyglotScheme(forms, opts = {}) {
121
+ const allowCurlyInfix = Boolean(opts.allowCurlyInfix);
122
+ const lowerContainersInQuote = Boolean(opts.lowerContainersInQuote);
123
+ const mapExpr = (nd) => mapNode(nd, "expr");
124
+ function mapQuoteNode(nd) {
125
+ if (!isList(nd))
126
+ return nd;
127
+ const open = nd.open ?? "(";
128
+ if (lowerContainersInQuote) {
129
+ if (open === "[")
130
+ return withParenList(nd, [{ atom: "vector" }, ...nd.list.map(mapQuoteNode)]);
131
+ if (open === "{")
132
+ return lowerBrace(nd, mapQuoteNode, allowCurlyInfix);
133
+ }
134
+ if (nd.open === "#(" || nd.open === "#u8(" || nd.open === "[" || nd.open === "{") {
135
+ return { ...nd, list: nd.list.map(mapQuoteNode) };
136
+ }
137
+ if (nd.list.length > 0 && isAtom(nd.list[0]) && !nd.list[0].str && POLY_QUOTE_HEADS.has(nd.list[0].atom)) {
138
+ return withParenList(nd, [nd.list[0], ...nd.list.slice(1).map(mapQuoteNode)]);
139
+ }
140
+ return withParenList(nd, nd.list.map(mapQuoteNode));
141
+ }
142
+ function mapNode(nd, ctx) {
143
+ if (!isList(nd))
144
+ return nd;
145
+ if (ctx === "quote")
146
+ return mapQuoteNode(nd);
147
+ const open = nd.open ?? "(";
148
+ const items = nd.list;
149
+ // R7RS constant vectors and bytevectors stay untouched structurally (handled via `open`).
150
+ if (open === "#(" || open === "#u8(") {
151
+ return { ...nd, list: items.map(mapExpr) };
152
+ }
153
+ if (items.length > 0 && isAtom(items[0]) && !items[0].str) {
154
+ const h = items[0].atom;
155
+ if (POLY_SYNTAX_OPAQUE.has(h)) {
156
+ return nd;
157
+ }
158
+ if (POLY_LET_SYNTAX.has(h)) {
159
+ return withParenList(nd, [items[0], ...(items.length > 1 ? [items[1]] : []), ...items.slice(2).map(mapExpr)]);
160
+ }
161
+ if (POLY_QUOTE_HEADS.has(h) && items.length >= 2) {
162
+ return withParenList(nd, [items[0], mapQuoteNode(items[1]), ...items.slice(2).map(mapExpr)]);
163
+ }
164
+ if (h === "lambda" && items.length >= 2 && isFlatSymbolVector(items[1])) {
165
+ return withParenList(nd, [items[0], withParenList(items[1], items[1].list), ...items.slice(2).map(mapExpr)]);
166
+ }
167
+ if (POLY_LET_FAMILY.has(h) || h === "do") {
168
+ const named = h !== "do" && items.length > 2 && isAtom(items[1]) && !items[1].str;
169
+ const bindIdx = named ? 2 : 1;
170
+ if (items.length > bindIdx && items[bindIdx] !== undefined) {
171
+ const out = [items[0]];
172
+ if (named)
173
+ out.push(items[1]);
174
+ out.push(lowerBindings(items[bindIdx], h, mapExpr));
175
+ for (const rest of items.slice(bindIdx + 1)) {
176
+ if (h === "do" && rest === items[bindIdx + 1] && isList(rest) && rest.open === "[") {
177
+ out.push(withParenList(rest, rest.list.map(mapExpr)));
178
+ }
179
+ else {
180
+ out.push(mapExpr(rest));
181
+ }
182
+ }
183
+ return withParenList(nd, out);
184
+ }
185
+ }
186
+ if (POLY_CLAUSE_HEADS.has(h)) {
187
+ const clauseStart = h === "case" ? 2 : 1;
188
+ const out = items.slice(0, clauseStart).map((c, i) => (i === 0 ? c : mapExpr(c)));
189
+ for (const cl of items.slice(clauseStart)) {
190
+ out.push(lowerClause(cl, h === "case", mapExpr));
191
+ }
192
+ return withParenList(nd, out);
193
+ }
194
+ }
195
+ if (open === "[") {
196
+ return withParenList(nd, [{ atom: "vector" }, ...items.map(mapExpr)]);
197
+ }
198
+ if (open === "{") {
199
+ return lowerBrace(nd, mapExpr, allowCurlyInfix);
200
+ }
201
+ return withParenList(nd, items.map(mapExpr));
202
+ }
203
+ return forms.map((f) => mapNode(f, "expr"));
204
+ }
205
+ //# sourceMappingURL=normalize.js.map
@@ -0,0 +1,44 @@
1
+ import { type Span, type SyntaxDiagnostic } from "./errors.js";
2
+ /** Opener that minted a list/vector node. Absent or `"("` means a plain paren list. */
3
+ export type ListOpen = "(" | "[" | "{" | "#(" | "#u8(";
4
+ export type AtomNode = {
5
+ atom: string;
6
+ str?: boolean;
7
+ decoded?: string;
8
+ raw?: string;
9
+ lead?: string[];
10
+ trail?: string[];
11
+ span?: Span;
12
+ };
13
+ export type ListNode = {
14
+ list: Node[];
15
+ open?: ListOpen;
16
+ lead?: string[];
17
+ trail?: string[];
18
+ span?: Span;
19
+ };
20
+ export type Node = AtomNode | ListNode;
21
+ export interface ParseSyntaxOptions {
22
+ /** Return partial trees + diagnostics instead of throwing {@link ArrivalSyntaxError}. Default: `false`. */
23
+ readonly tolerant?: boolean;
24
+ /** Report strict R7RS diagnostics on Arrival/Clojure sugar (`#null`, `#void`, `#_`). Default: `false`. */
25
+ readonly strict?: boolean;
26
+ /** Also throw on lexical `Invalid` tokens such as unknown `#...` prefixes when `tolerant: false`. Default: `false`. */
27
+ readonly rejectInvalidTokens?: boolean;
28
+ }
29
+ export interface ParseSyntaxResult {
30
+ readonly forms: Node[];
31
+ readonly diagnostics: readonly SyntaxDiagnostic[];
32
+ readonly closeSuffix: string;
33
+ readonly closeable: boolean;
34
+ readonly danglingPrefix: boolean;
35
+ }
36
+ /**
37
+ * Parse `src` into span- and comment-preserving {@link Node} trees using {@link lexScheme}.
38
+ */
39
+ export declare function parseSyntax(src: string, opts?: ParseSyntaxOptions): ParseSyntaxResult;
40
+ /** Strict Scheme s-expression forest parser (throws {@link ArrivalSyntaxError} on syntax errors). */
41
+ export declare function parseSexprs(src: string): Node[];
42
+ /** Never-throwing tolerant parser returning partial trees, diagnostics, and closing stack info. */
43
+ export declare function parseSexprsTolerant(src: string): ParseSyntaxResult;
44
+ //# sourceMappingURL=parse-syntax.d.ts.map