@aufbau/syntax 0.0.5 → 0.0.6

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/dist/print.js CHANGED
@@ -5,9 +5,13 @@
5
5
  * the canonical spelling of each constructor (the last-declared notation,
6
6
  * Aufbau's rule), *full* parenthesization of sentential connectives with
7
7
  * the outermost pair optionally dropped (`@syntax display
8
- * drop-outer-parens`) — Carnap's convention, not minimal-parens — spaces
9
- * around connectives, everything else set tight (`¬P`, `∀x`, `a=b`,
10
- * `R(a,b)`).
8
+ * drop-outer-parens`) — Carnap's convention, not minimal-parens. A formula
9
+ * is outermost wherever the sort changes above it, not only at the top:
10
+ * `𝕋 A ∧ B`, `A ∧ B ⊢ C`. Connectives are spaced, and so is a notation
11
+ * that takes its operands to another sort (`a = b`, `𝕋 A`); everything
12
+ * else is set tight (`¬P`, `∀x`, `R(a,b)`). A notation token declared a
13
+ * delimiter on one side only hugs that side and stands off the other, so
14
+ * a right-only `,` writes `a, b`.
11
15
  *
12
16
  * **Engine** is what the Aufbau compiler's own math parser reads: the same
13
17
  * canonical spellings, every token whitespace-separated, every compound
@@ -16,120 +20,374 @@
16
20
  * `F ((x , y))`, `P (snil)` — which is valid at any slot once
17
21
  * parenthesized, and elided arguments are written out in full.
18
22
  *
19
- * Display mode presumes the spec's term-level infixes (identity, argument
20
- * commas) bind tighter than its prefixes, as every textbook's do; a spec
21
- * violating that should print through engine mode. The round-trip law —
22
- * parsing a printed term yields the same tree — is enforced by test for
23
- * both modes.
23
+ * Parentheses beyond the connectives' own are exactly the ones the parser
24
+ * needs, decided from its own precedence tables: a piece stands bare in a
25
+ * slot when its head binds at least as tight as the slot reads, and when
26
+ * nothing on its right edge would swallow the operator after it — the
27
+ * `(λx.x)·y` that bare would read the `y` into the body. So `1 + 0 * 0`
28
+ * prints as such, and `(1 + 0) * 0` keeps its pair.
29
+ *
30
+ * The round-trip law — parsing a printed term, in the same mode, yields
31
+ * the same tree — holds for every term, and is enforced by test over
32
+ * generated terms in both modes. Its segmentation half is structural:
33
+ * every seam between two printed pieces goes through {@link adjoin},
34
+ * which sets them tight only where the reader's delimiters would cut
35
+ * there anyway, and spaces them where it would not. "Tight" is the
36
+ * display convention, not a promise — under a spec with no letter
37
+ * delimiters `∀x Cube(x)` keeps its space, because `∀xCube(x)` would read
38
+ * `xCube` as one chunk.
24
39
  */
40
+ import { adjoin } from "./delimiters.js";
25
41
  import { delaborate } from "./elab.js";
42
+ import { generalParts, precNum } from "./parse.js";
43
+ /**
44
+ * A term display text cannot spell. The one such term is an `@syntax
45
+ * elided` term standing anywhere but where the reader supplies it —
46
+ * `R(snil,a)` — which has no surface spelling at all: written by name it
47
+ * either fails to read (`snil` is four letters to Calgary) or, worse,
48
+ * reads as something else (Magnus glues the letters into arguments). The
49
+ * printer refuses rather than write text that does not read back as the
50
+ * term. Engine text can always spell it, by name.
51
+ */
52
+ export class UnprintableTermError extends Error {
53
+ term;
54
+ constructor(term) {
55
+ super(`${term} is elided wherever it is read, so display text has no way to write it here`);
56
+ this.name = "UnprintableTermError";
57
+ this.term = term;
58
+ }
59
+ }
60
+ /**
61
+ * `term` as text in `mode`, which parses back in the same mode to the same
62
+ * term. Display mode throws {@link UnprintableTermError} for the one shape
63
+ * it cannot spell; engine mode is total.
64
+ */
26
65
  export function printTerm(lang, term, mode = "display") {
27
- let printed = render(lang, term, mode);
28
- if (mode === "display" &&
29
- lang.spec.display.dropOuterParens &&
30
- printed.startsWith("(") &&
31
- printed.endsWith(")")) {
32
- printed = printed.slice(1, -1);
66
+ const printer = {
67
+ lang,
68
+ mode,
69
+ // Each mode is read back by its own scanner, so each is set against
70
+ // that scanner's delimiters: the surface set for display, the
71
+ // theory's own for engine text (where `(a)` is one chunk to a theory
72
+ // that never declares `(`).
73
+ rules: mode === "display" ? lang.scanner.rules : lang.engineScanner.rules,
74
+ };
75
+ if (mode === "engine") {
76
+ return engine(printer, term);
33
77
  }
34
- if (mode === "display" && lang.spec.elabRules.length > 0) {
35
- printed = delaborate(lang, printed);
78
+ const printed = display(printer, term, lang.spec.display.dropOuterParens);
79
+ return lang.spec.elabRules.length > 0
80
+ ? delaborate(lang, printed.text)
81
+ : printed.text;
82
+ }
83
+ /** Pieces set as tight as the reader's delimiters allow. */
84
+ function tight(printer, ...pieces) {
85
+ return pieces.reduce((left, right) => adjoin(left, right, printer.rules));
86
+ }
87
+ /** Pieces set one space apart — always safe, and the connective style. */
88
+ function spaced(...pieces) {
89
+ return pieces.filter((piece) => piece.length > 0).join(" ");
90
+ }
91
+ function operand(text) {
92
+ return { text, token: false };
93
+ }
94
+ function token(text) {
95
+ return { text, token: true };
96
+ }
97
+ /**
98
+ * A display notation's pieces in order, its seams spaced when `apart` and
99
+ * otherwise as tight as the delimiters allow. A token the surface
100
+ * delimiters list on one side only decides its own seams instead: a
101
+ * right-only token breaks before itself, so it hugs what precedes it and
102
+ * stands off what follows (`a, b`); a left-only one is the mirror. That is
103
+ * the declaration read as layout, and it holds in a spec whose letters are
104
+ * delimiters too, where `a,b` would read back just as well.
105
+ */
106
+ function setPieces(printer, pieces, apart) {
107
+ let text = "";
108
+ let previous = null;
109
+ for (const piece of pieces) {
110
+ if (piece.text.length === 0) {
111
+ continue;
112
+ }
113
+ if (previous === null) {
114
+ text = piece.text;
115
+ previous = piece;
116
+ continue;
117
+ }
118
+ const after = previous.token ? oneSide(printer, previous.text) : null;
119
+ const before = piece.token ? oneSide(printer, piece.text) : null;
120
+ const space = after === "right" || before === "left"
121
+ ? true
122
+ : after === "left" || before === "right"
123
+ ? false
124
+ : apart;
125
+ // A space never joins two chunks, so only the tight seam needs adjoin.
126
+ text = space
127
+ ? `${text} ${piece.text}`
128
+ : adjoin(text, piece.text, printer.rules);
129
+ previous = piece;
36
130
  }
37
- return printed;
131
+ return text;
132
+ }
133
+ /** The one side `text` is a delimiter on, or null for both or neither. */
134
+ function oneSide(printer, text) {
135
+ const left = printer.rules.left.has(text);
136
+ const right = printer.rules.right.includes(text);
137
+ return left === right ? null : left ? "left" : "right";
138
+ }
139
+ /** A piece in the built-in grouping pair. */
140
+ function grouped(printer, inner) {
141
+ return tight(printer, "(", inner, ")");
38
142
  }
39
- function render(lang, term, mode) {
143
+ // ── engine text ──────────────────────────────────────────────────────
144
+ function engine(printer, term) {
145
+ const { lang } = printer;
40
146
  if (term.kind === "variable") {
41
147
  return term.name;
42
148
  }
43
- // Coercions are the parser's bookkeeping; both readers re-derive them.
44
- if (term.args.length === 1 && lang.coercionNames.has(term.term)) {
45
- const inner = term.args[0];
46
- if (inner !== undefined) {
47
- return render(lang, inner, mode);
149
+ // Coercions are the parser's bookkeeping; the engine re-derives them.
150
+ const inner = coerced(lang, term);
151
+ if (inner !== null) {
152
+ return engine(printer, inner);
153
+ }
154
+ const notation = lang.canonical.get(term.term);
155
+ // A term with no notation is written as application in full —
156
+ // `P (snil)`, `R ((x , y))` — which the compiler reads at
157
+ // expression(max).
158
+ if (notation === undefined) {
159
+ if (term.args.length === 0) {
160
+ return term.term;
161
+ }
162
+ const binders = lang.spec.terms.get(term.term)?.binders ?? [];
163
+ const args = term.args.map((arg, at) => {
164
+ const rendered = engine(printer, arg);
165
+ // A bound binder's argument is a variable and must stand bare: the
166
+ // engine wants a name in that slot, not a group around one.
167
+ if (binders[at]?.binds === true) {
168
+ return rendered;
169
+ }
170
+ return rendered.startsWith("(") ? rendered : grouped(printer, rendered);
171
+ });
172
+ return spaced(term.term, ...args);
173
+ }
174
+ if (notation.form === "simple") {
175
+ const args = term.args.map((arg) => engineOperand(printer, arg));
176
+ return notation.fixity === "prefix"
177
+ ? grouped(printer, spaced(notation.token, ...args))
178
+ : grouped(printer, spaced(args[0] ?? "", notation.token, args[1] ?? ""));
179
+ }
180
+ // General notation: constants and binder slots, in literal order.
181
+ const pieces = notation.literals.map((literal) => {
182
+ if (literal.kind === "constant") {
183
+ return literal.token;
48
184
  }
185
+ const index = notation.binders.findIndex((binder) => binder.name === literal.name);
186
+ return engineOperand(printer, term.args[index]);
187
+ });
188
+ return term.args.length === 0
189
+ ? spaced(...pieces)
190
+ : grouped(printer, spaced(...pieces));
191
+ }
192
+ /**
193
+ * An engine operand: any unparenthesized compound gets parentheses, so
194
+ * every operand is expression(max) and fits any slot.
195
+ */
196
+ function engineOperand(printer, term) {
197
+ if (term === undefined) {
198
+ return "";
199
+ }
200
+ const { lang } = printer;
201
+ const rendered = engine(printer, term);
202
+ const bearer = uncoerced(lang, term);
203
+ const bare = bearer.kind === "variable" ||
204
+ (bearer.kind === "app" &&
205
+ bearer.args.length === 0 &&
206
+ lang.canonical.get(bearer.term) === undefined) ||
207
+ rendered.startsWith("(");
208
+ return bare ? rendered : grouped(printer, rendered);
209
+ }
210
+ // ── display ──────────────────────────────────────────────────────────
211
+ const TIGHTEST = Number.POSITIVE_INFINITY;
212
+ /** mm0.md: bare constructor application is `expression(1024)`. */
213
+ const APPLICATION_PRECEDENCE = 1024;
214
+ function atom(text) {
215
+ return { text, head: TIGHTEST, tail: TIGHTEST };
216
+ }
217
+ /**
218
+ * A piece set in a slot the parser reads at `min`, with an operator of
219
+ * precedence `next` (or nothing) written after it: bare when it re-reads
220
+ * as itself there, parenthesized when it would not.
221
+ */
222
+ function fit(printer, piece, min, next) {
223
+ return piece.head >= min && (next === null || next < piece.tail)
224
+ ? piece
225
+ : atom(grouped(printer, piece.text));
226
+ }
227
+ /**
228
+ * `outer` is true, under `@syntax display drop-outer-parens`, for the whole
229
+ * printed term and for a term the sort changes above ({@link outermost}):
230
+ * the one pair a connective would wrap itself in is left off. Coercions
231
+ * pass it through, since they print as what they wrap.
232
+ */
233
+ function display(printer, term, outer = false) {
234
+ const { lang } = printer;
235
+ if (term.kind === "variable") {
236
+ return atom(term.name);
237
+ }
238
+ // Coercions are the parser's bookkeeping; the reader re-derives them.
239
+ const inner = coerced(lang, term);
240
+ if (inner !== null) {
241
+ return display(printer, inner, outer);
49
242
  }
50
243
  const notation = lang.canonical.get(term.term);
51
244
  if (notation === undefined) {
52
- return renderApplication(lang, term, mode);
245
+ return displayApplication(printer, term);
53
246
  }
247
+ const binders = lang.spec.terms.get(term.term)?.binders ?? [];
54
248
  if (notation.form === "simple" && notation.fixity !== "prefix") {
55
- const left = operand(lang, term.args[0], mode);
56
- const right = operand(lang, term.args[1], mode);
57
- if (mode === "engine") {
58
- return `(${left} ${notation.token} ${right})`;
59
- }
249
+ const prec = precNum(notation.prec);
250
+ const leftMin = notation.fixity === "infixl" ? prec : prec + 1;
251
+ const rightMin = notation.fixity === "infixl" ? prec + 1 : prec;
60
252
  const connective = lang.isConnective(term.term);
61
- // A juxtaposed combiner displays as nothing when it can: `abc` for
62
- // `mul(mul(a,b),c)`. An operand is parenthesized when its own
63
- // printed form rebinds below what its slot re-parses at — which
64
- // covers nesting against the associativity (`a*(bc)`) and, just as
65
- // fatally, a loose prefix whose body would swallow what follows
66
- // (`(λxx)·y`, where bare `λxxy` reads the `y` into the body). Then
67
- // the pieces glue when both can, and the visible token steps back in
68
- // when either cannot; either way the display form reparses to the
69
- // same tree. A *connective* combiner is left to the full-paren
70
- // convention below, which is already stable; invisibly glued
71
- // formulas would be unreadable anyway.
72
- if (!connective && lang.spec.terms.get(term.term)?.juxtaposed === true) {
73
- const prec = typeof notation.prec === "number" ? notation.prec : 0;
74
- const slot = (piece, arg, at) => arg !== undefined && printedPrec(lang, arg) < at
75
- ? `(${piece})`
76
- : piece;
77
- const l = slot(left, term.args[0], notation.fixity === "infixl" ? prec : prec + 1);
78
- const r = slot(right, term.args[1], notation.fixity === "infixl" ? prec + 1 : prec);
79
- return glueablePiece(lang, l) && glueablePiece(lang, r)
80
- ? `${l}${r}`
81
- : `${l}${notation.token}${r}`;
82
- }
253
+ // A connective's operands are compounds of its own sort, which keep
254
+ // their brackets under it: that is the full-paren convention.
255
+ const outerAt = (at) => !connective && outermost(printer, term, term.args[at]);
256
+ const left = fitArg(printer, term.args[0], leftMin, prec, outerAt(0));
257
+ const right = fitArg(printer, term.args[1], rightMin, null, outerAt(1));
258
+ const tail = Math.min(rightMin, right.tail);
259
+ const pieces = [
260
+ operand(left.text),
261
+ token(notation.token),
262
+ operand(right.text),
263
+ ];
83
264
  // Connectives are spaced and self-parenthesized (the full-paren
84
- // convention); term-level infixes close up and stand bare.
85
- return connective
86
- ? `(${left} ${notation.token} ${right})`
87
- : `${left}${notation.token}${right}`;
265
+ // convention), bar the outermost under drop-outer-parens.
266
+ if (connective) {
267
+ const text = setPieces(printer, pieces, true);
268
+ return outer
269
+ ? { text, head: prec, tail }
270
+ : atom(grouped(printer, text));
271
+ }
272
+ // A juxtaposed combiner displays as nothing when both sides are
273
+ // single glue operands: `abc` for `mul(mul(a,b),c)`. The adjacency
274
+ // arc is its operator written invisibly, at the same precedence, so
275
+ // the slots above hold for it too; a compound side (`a*(bc)`) brings
276
+ // the visible token back.
277
+ const glued = lang.spec.terms.get(term.term)?.juxtaposed === true &&
278
+ glueablePiece(lang, left.text) &&
279
+ glueablePiece(lang, right.text);
280
+ const text = glued
281
+ ? tight(printer, left.text, right.text)
282
+ : setPieces(printer, pieces, changesSort(lang, term.term));
283
+ return { text, head: prec, tail };
88
284
  }
89
285
  if (notation.form === "simple") {
90
- const args = term.args.map((arg) => operand(lang, arg, mode));
91
- return mode === "engine"
92
- ? `(${[notation.token, ...args].join(" ")})`
93
- : `${notation.token}${args.join("")}`;
286
+ // mm0.md: a prefix notation's intermediate arguments read at max,
287
+ // its last at the notation's own precedence.
288
+ const prec = precNum(notation.prec);
289
+ const pieces = [token(notation.token)];
290
+ let tail = TIGHTEST;
291
+ term.args.forEach((arg, at) => {
292
+ if (binders[at]?.binds === true) {
293
+ pieces.push(operand(display(printer, arg).text));
294
+ tail = TIGHTEST;
295
+ return;
296
+ }
297
+ const min = at === term.args.length - 1 ? prec : TIGHTEST;
298
+ const piece = fit(printer, display(printer, arg, outermost(printer, term, arg)), min, null);
299
+ pieces.push(operand(piece.text));
300
+ tail = Math.min(min, piece.tail);
301
+ });
302
+ return {
303
+ text: setPieces(printer, pieces, changesSort(lang, term.term)),
304
+ head: prec,
305
+ tail,
306
+ };
94
307
  }
95
- // General notation: constants and binder slots, in literal order.
96
- const pieces = [];
97
- for (const literal of notation.literals) {
98
- if (literal.kind === "constant") {
99
- pieces.push(literal.token);
308
+ const first = notation.literals[0];
309
+ if (first?.kind !== "constant") {
310
+ return displayApplication(printer, term);
311
+ }
312
+ // General notation: the head, then the parser's own slots in order.
313
+ const pieces = [token(first.token)];
314
+ let tail = TIGHTEST;
315
+ for (const part of generalParts(notation, first.prec)) {
316
+ if (part.kind === "constant") {
317
+ pieces.push(token(part.token));
318
+ tail = TIGHTEST;
100
319
  continue;
101
320
  }
102
- const index = notation.binders.findIndex((binder) => binder.name === literal.name);
103
- const arg = term.args[index];
104
- if (arg !== undefined) {
105
- pieces.push(operand(lang, arg, mode));
321
+ const arg = term.args[part.slot.index];
322
+ if (arg === undefined) {
323
+ continue;
106
324
  }
325
+ if (part.slot.binder.binds) {
326
+ pieces.push(operand(display(printer, arg).text));
327
+ tail = TIGHTEST;
328
+ continue;
329
+ }
330
+ const piece = fit(printer, display(printer, arg, outermost(printer, term, arg)), part.slot.prec, null);
331
+ pieces.push(operand(piece.text));
332
+ tail = Math.min(part.slot.prec, piece.tail);
107
333
  }
108
- if (mode === "engine") {
109
- return term.args.length === 0
110
- ? pieces.join(" ")
111
- : `(${pieces.join(" ")})`;
334
+ return {
335
+ text: setPieces(printer, pieces, changesSort(lang, term.term)),
336
+ head: precNum(first.prec),
337
+ tail,
338
+ };
339
+ }
340
+ function fitArg(printer, arg, min, next, outer) {
341
+ return arg === undefined
342
+ ? { text: "", head: TIGHTEST, tail: TIGHTEST }
343
+ : fit(printer, display(printer, arg, outer), min, next);
344
+ }
345
+ /**
346
+ * Whether `arg`, under `parent`, is the outermost formula of its sort:
347
+ * under drop-outer-parens a connective leaves off its own pair wherever
348
+ * the sort changes above it, as it does at the top — `𝕋 A ∧ B`, `A ∧ B ⊢
349
+ * C`. Read through coercions, which change sort without printing. Safe
350
+ * for the same reason the top is: {@link fit} still brackets a compound
351
+ * that would not read back bare in its slot.
352
+ */
353
+ function outermost(printer, parent, arg) {
354
+ return (arg !== undefined &&
355
+ printer.lang.spec.display.dropOuterParens &&
356
+ uncoerced(printer.lang, arg).sort !== parent.sort);
357
+ }
358
+ /**
359
+ * Whether `name` takes its operands to another sort, returning none of
360
+ * theirs: `=` from terms to a formula, `𝕋` from a formula to a row, `⊢`
361
+ * from a context and a formula to a judgement. Its display is spaced, as
362
+ * a connective's is; `¬`, `∀x` and `,` stay tight.
363
+ */
364
+ function changesSort(lang, name) {
365
+ const info = lang.spec.terms.get(name);
366
+ if (info === undefined) {
367
+ return false;
112
368
  }
113
- return pieces.join("");
369
+ const sorts = info.binders
370
+ .filter((binder) => !binder.binds)
371
+ .map((binder) => ("sort" in binder.type ? binder.type.sort : ""));
372
+ return sorts.length > 0 && !sorts.includes(info.returnSort);
114
373
  }
115
374
  /**
116
375
  * A term with no notation prints as application — the lexicon's shape.
117
376
  * Display elides an `@syntax elided` argument (bare `P`), flattens a
118
377
  * juxtaposed argument into glued leaves (`Rxy`), and otherwise sets each
119
378
  * argument in its own parentheses (`R(a,b)`, the comma coming from the
120
- * argument's own notation). Engine mode writes application in full —
121
- * `P (snil)`, `R ((x , y))` — which the compiler reads at expression(max).
379
+ * argument's own notation) — except a bound binder's variable, which the
380
+ * reader takes bare (`sb x(t)(p)`), as MM0 application does.
122
381
  */
123
- function renderApplication(lang, term, mode) {
382
+ function displayApplication(printer, term) {
383
+ const { lang } = printer;
124
384
  if (term.args.length === 0) {
125
- return term.term;
126
- }
127
- if (mode === "engine") {
128
- const args = term.args.map((arg) => {
129
- const rendered = render(lang, arg, mode);
130
- return rendered.startsWith("(") ? rendered : `(${rendered})`;
131
- });
132
- return [term.term, ...args].join(" ");
385
+ // Its one place is the sole argument of a name, which is elided
386
+ // below before it ever gets here.
387
+ if (lang.spec.terms.get(term.term)?.elided === true) {
388
+ throw new UnprintableTermError(term.term);
389
+ }
390
+ return atom(term.term);
133
391
  }
134
392
  const sole = term.args.length === 1 ? term.args[0] : undefined;
135
393
  if (sole !== undefined) {
@@ -138,63 +396,64 @@ function renderApplication(lang, term, mode) {
138
396
  if (elided !== undefined &&
139
397
  bare.kind === "app" &&
140
398
  bare.term === elided.name) {
141
- return term.term;
399
+ return atom(term.term);
142
400
  }
143
401
  const combiner = lang.juxtaposedOf.get(sole.sort);
144
402
  if (combiner !== undefined) {
403
+ // The parser folds glued leaves to the left, so only a left-nested
404
+ // tree flattens back into itself: `Rxyz` is `R((x,y),z)`, and a
405
+ // right operand that is itself a combination keeps its brackets.
145
406
  const leaves = [];
146
407
  const flatten = (node) => {
147
408
  const at = uncoerced(lang, node);
148
- if (at.kind === "app" && at.term === combiner.name) {
149
- for (const inner of at.args) {
150
- flatten(inner);
151
- }
152
- return;
409
+ if (at.kind !== "app" || at.term !== combiner.name) {
410
+ leaves.push(display(printer, at).text);
411
+ return true;
153
412
  }
154
- leaves.push(render(lang, at, mode));
413
+ const [left, right] = at.args;
414
+ const last = right === undefined ? undefined : uncoerced(lang, right);
415
+ if (left === undefined ||
416
+ last === undefined ||
417
+ (last.kind === "app" && last.term === combiner.name) ||
418
+ !flatten(left)) {
419
+ return false;
420
+ }
421
+ leaves.push(display(printer, last).text);
422
+ return true;
155
423
  };
156
- flatten(sole);
157
424
  // Glue only when every leaf is itself glueable — a single token the
158
425
  // parser would consume back. A compound element falls back to the
159
426
  // parenthesized form.
160
- const simple = leaves.every((leaf) => glueablePiece(lang, leaf));
161
- if (simple) {
162
- return `${term.term}${leaves.join("")}`;
427
+ if (flatten(sole) &&
428
+ leaves.every((leaf) => glueablePiece(lang, leaf))) {
429
+ return atom(tight(printer, term.term, ...leaves));
163
430
  }
164
431
  }
165
432
  }
166
- const args = term.args
167
- .map((arg) => `(${render(lang, arg, mode)})`)
168
- .join("");
169
- return `${term.term}${args}`;
433
+ const binders = lang.spec.terms.get(term.term)?.binders ?? [];
434
+ const binds = term.args.some((_, at) => binders[at]?.binds === true);
435
+ const pieces = term.args.map((arg, at) => binders[at]?.binds === true
436
+ ? display(printer, arg).text
437
+ : grouped(printer, display(printer, arg, outermost(printer, term, arg)).text));
438
+ // A name with a bound binder is read as bare application, which a
439
+ // slot tighter than expression(1024) refuses.
440
+ return {
441
+ text: tight(printer, term.term, ...pieces),
442
+ head: binds ? APPLICATION_PRECEDENCE : TIGHTEST,
443
+ tail: TIGHTEST,
444
+ };
170
445
  }
171
- /**
172
- * The precedence at which a term's display form rebinds when it is
173
- * re-parsed: its canonical notation's, or the general notation's head
174
- * precedence. Self-delimiting forms — variables, lexicon names (which
175
- * print as `F(x)`-style application), and connectives (which print
176
- * self-parenthesized) — never rebind, and answer infinity.
177
- */
178
- function printedPrec(lang, term) {
179
- const bare = uncoerced(lang, term);
180
- if (bare.kind === "variable") {
181
- return Number.POSITIVE_INFINITY;
182
- }
183
- const notation = lang.canonical.get(bare.term);
184
- if (notation === undefined || lang.isConnective(bare.term)) {
185
- return Number.POSITIVE_INFINITY;
186
- }
187
- const prec = notation.form === "general"
188
- ? notation.literals[0]?.kind === "constant"
189
- ? notation.literals[0].prec
190
- : "max"
191
- : notation.prec;
192
- return prec === "max" ? Number.POSITIVE_INFINITY : prec;
446
+ /** The argument of a coercion node, or null when it is not one. */
447
+ function coerced(lang, term) {
448
+ return term.args.length === 1 && lang.coercionNames.has(term.term)
449
+ ? (term.args[0] ?? null)
450
+ : null;
193
451
  }
194
452
  /**
195
- * Whether a printed piece can stand glued against another: no whitespace
196
- * and no brackets, so the delimiters re-cut the concatenation into the
197
- * same chunks the pieces were printed from.
453
+ * Whether a printed piece can stand as one glued element — one leaf of
454
+ * `Rxy`, one factor of `abc`: no whitespace and no brackets, so it is a
455
+ * single chunk the adjacency arc takes back whole. Where the seam falls
456
+ * is {@link adjoin}'s business; this is only whether the piece is atomic.
198
457
  */
199
458
  function glueablePiece(lang, piece) {
200
459
  return (!/\s/.test(piece) &&
@@ -214,24 +473,4 @@ function uncoerced(lang, term) {
214
473
  }
215
474
  return at;
216
475
  }
217
- /** An argument position: parenthesize what would not survive re-parsing. */
218
- function operand(lang, term, mode) {
219
- if (term === undefined) {
220
- return "";
221
- }
222
- const rendered = render(lang, term, mode);
223
- if (mode === "display") {
224
- // Connectives arrive self-parenthesized; everything else stands bare.
225
- return rendered;
226
- }
227
- // Engine mode: any unparenthesized compound gets parentheses, so every
228
- // operand is expression(max) and fits any slot.
229
- const bearer = uncoerced(lang, term);
230
- const bare = bearer.kind === "variable" ||
231
- (bearer.kind === "app" &&
232
- bearer.args.length === 0 &&
233
- lang.canonical.get(bearer.term) === undefined) ||
234
- rendered.startsWith("(");
235
- return bare ? rendered : `(${rendered})`;
236
- }
237
476
  //# sourceMappingURL=print.js.map