aontu 0.57.0 → 0.59.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 (132) hide show
  1. package/README.md +2 -2
  2. package/dist/agentsmd.js +1 -1
  3. package/dist/alias.d.ts +3 -0
  4. package/dist/alias.js +59 -0
  5. package/dist/alias.js.map +1 -0
  6. package/dist/aontu.d.ts +4 -2
  7. package/dist/aontu.js +12 -3
  8. package/dist/aontu.js.map +1 -1
  9. package/dist/cli.d.ts +3 -1
  10. package/dist/cli.js +486 -4
  11. package/dist/cli.js.map +1 -1
  12. package/dist/ctx.d.ts +4 -0
  13. package/dist/ctx.js +3 -0
  14. package/dist/ctx.js.map +1 -1
  15. package/dist/err.js +6 -3
  16. package/dist/err.js.map +1 -1
  17. package/dist/format.js +8 -2
  18. package/dist/format.js.map +1 -1
  19. package/dist/hints.js +40 -9
  20. package/dist/hints.js.map +1 -1
  21. package/dist/lang.js +409 -58
  22. package/dist/lang.js.map +1 -1
  23. package/dist/lower.d.ts +20 -0
  24. package/dist/lower.js +575 -0
  25. package/dist/lower.js.map +1 -0
  26. package/dist/lsp.d.ts +1 -1
  27. package/dist/lsp.js +1 -1
  28. package/dist/lsp.js.map +1 -1
  29. package/dist/mcp-server.js +1 -1
  30. package/dist/mcp.d.ts +1 -0
  31. package/dist/mcp.js +40 -3
  32. package/dist/mcp.js.map +1 -1
  33. package/dist/render.d.ts +53 -0
  34. package/dist/render.js +542 -0
  35. package/dist/render.js.map +1 -0
  36. package/dist/sigdecl.js +1 -1
  37. package/dist/sigdecl.js.map +1 -1
  38. package/dist/std.d.ts +2 -0
  39. package/dist/std.js +498 -2
  40. package/dist/std.js.map +1 -1
  41. package/dist/template.d.ts +5 -0
  42. package/dist/template.js +257 -0
  43. package/dist/template.js.map +1 -0
  44. package/dist/tsconfig.tsbuildinfo +1 -1
  45. package/dist/type.d.ts +2 -0
  46. package/dist/type.js.map +1 -1
  47. package/dist/unify.js +43 -0
  48. package/dist/unify.js.map +1 -1
  49. package/dist/val/AggFuncVal.d.ts +1 -1
  50. package/dist/val/AggFuncVal.js +10 -21
  51. package/dist/val/AggFuncVal.js.map +1 -1
  52. package/dist/val/BagVal.js +1 -1
  53. package/dist/val/BagVal.js.map +1 -1
  54. package/dist/val/ConstraintVal.js +1 -1
  55. package/dist/val/DisjunctVal.js +33 -2
  56. package/dist/val/DisjunctVal.js.map +1 -1
  57. package/dist/val/EachFuncVal.d.ts +1 -1
  58. package/dist/val/EachFuncVal.js +8 -13
  59. package/dist/val/EachFuncVal.js.map +1 -1
  60. package/dist/val/EmitFuncVal.d.ts +23 -4
  61. package/dist/val/EmitFuncVal.js +298 -28
  62. package/dist/val/EmitFuncVal.js.map +1 -1
  63. package/dist/val/FilterFuncVal.js +8 -4
  64. package/dist/val/FilterFuncVal.js.map +1 -1
  65. package/dist/val/FormFuncVal.d.ts +14 -0
  66. package/dist/val/FormFuncVal.js +55 -0
  67. package/dist/val/FormFuncVal.js.map +1 -0
  68. package/dist/val/FuncBaseVal.js +36 -13
  69. package/dist/val/FuncBaseVal.js.map +1 -1
  70. package/dist/val/ListVal.js +9 -1
  71. package/dist/val/ListVal.js.map +1 -1
  72. package/dist/val/MapVal.d.ts +2 -1
  73. package/dist/val/MapVal.js +2 -1
  74. package/dist/val/MapVal.js.map +1 -1
  75. package/dist/val/PackFuncVal.d.ts +1 -1
  76. package/dist/val/PackFuncVal.js +22 -18
  77. package/dist/val/PackFuncVal.js.map +1 -1
  78. package/dist/val/PlaceVal.js +7 -2
  79. package/dist/val/PlaceVal.js.map +1 -1
  80. package/dist/val/RefVal.d.ts +3 -0
  81. package/dist/val/RefVal.js +181 -18
  82. package/dist/val/RefVal.js.map +1 -1
  83. package/dist/val/Val.d.ts +8 -1
  84. package/dist/val/Val.js +39 -1
  85. package/dist/val/Val.js.map +1 -1
  86. package/dist/val/members.d.ts +9 -0
  87. package/dist/val/members.js +52 -0
  88. package/dist/val/members.js.map +1 -0
  89. package/grammar/aontu.abnf +1 -1
  90. package/grammar/aontu.gbnf +1 -1
  91. package/grammar/aontu.lark +1 -1
  92. package/grammar/aontu.tmLanguage.json +1 -1
  93. package/package.json +1 -1
  94. package/skill/SKILL.md +4 -4
  95. package/skill/error-codes.md +1 -1
  96. package/skill/examples.md +1 -1
  97. package/skill/grammar-card.md +1 -1
  98. package/src/agentsmd.ts +1 -1
  99. package/src/alias.ts +112 -0
  100. package/src/aontu.ts +20 -2
  101. package/src/cli.ts +528 -4
  102. package/src/ctx.ts +18 -0
  103. package/src/err.ts +6 -3
  104. package/src/format.ts +12 -2
  105. package/src/hints.ts +47 -9
  106. package/src/lang.ts +453 -63
  107. package/src/lower.ts +636 -0
  108. package/src/lsp.ts +1 -1
  109. package/src/mcp-server.ts +1 -1
  110. package/src/mcp.ts +43 -4
  111. package/src/render.ts +727 -0
  112. package/src/sigdecl.ts +1 -1
  113. package/src/std.ts +506 -1
  114. package/src/template.ts +291 -0
  115. package/src/type.ts +10 -1
  116. package/src/unify.ts +47 -0
  117. package/src/val/AggFuncVal.ts +10 -21
  118. package/src/val/BagVal.ts +1 -1
  119. package/src/val/ConstraintVal.ts +1 -1
  120. package/src/val/DisjunctVal.ts +33 -2
  121. package/src/val/EachFuncVal.ts +8 -16
  122. package/src/val/EmitFuncVal.ts +376 -39
  123. package/src/val/FilterFuncVal.ts +11 -4
  124. package/src/val/FormFuncVal.ts +119 -0
  125. package/src/val/FuncBaseVal.ts +36 -13
  126. package/src/val/ListVal.ts +9 -1
  127. package/src/val/MapVal.ts +3 -2
  128. package/src/val/PackFuncVal.ts +23 -19
  129. package/src/val/PlaceVal.ts +7 -2
  130. package/src/val/RefVal.ts +193 -20
  131. package/src/val/Val.ts +75 -4
  132. package/src/val/members.ts +86 -0
package/src/render.ts ADDED
@@ -0,0 +1,727 @@
1
+ /* Copyright (c) 2025 Richard Rodger, MIT License */
2
+
3
+
4
+ // THE RENDERER (docs/design/RENDER.0.md; docs/capability-review/
5
+ // g9-transformation.md §3). `render` evaluates a document, takes the
6
+ // value at `--at` (the root by default), vets it against the bundled
7
+ // `aontu:code` vocabulary, and folds `code.units` into bytes;
8
+ // `renderValue` is the fold alone, over `generate()` output. The fold
9
+ // is pure and total: it never touches the Val tree, never reads or
10
+ // writes a file, never sorts and never iterates a map, and every piece
11
+ // of a fragment carries its own depth (`at`), so the renderer owns
12
+ // every prefix and no piece nests another (the second amendment's
13
+ // fragment algebra, RENDER.0.md D2 and D6).
14
+ //
15
+ // WHAT THIS PHASE RENDERS (RENDER.0.md P3): fragments -- a line, a
16
+ // blank run, a raw block, a bare string piece, a reference inline --
17
+ // and the `text` escape, under a profile that knows its language. The
18
+ // one bundled profile is `aontu:lang/text`, which every fragment-only
19
+ // unit falls back to; a declaration (`record`, `enum`, ...) needs a
20
+ // LOWERING, which P5 brings with the TypeScript and Go profiles, and
21
+ // until then is `render_profile`.
22
+
23
+ import { Aontu } from './aontu'
24
+ import { vet, failureFinding, anchorAt } from './vet'
25
+ import type { VetFinding } from './vet'
26
+ import { hcanon } from './hcanon'
27
+ import { makeNilErr } from './err'
28
+ import { cmpCodePoint } from './keyorder'
29
+ import { includeOpts } from './utility'
30
+ import type { IncludeOptions } from './utility'
31
+ import { lowerDecl, lowerHeader, ident } from './lower'
32
+ import type { LowerCtx } from './lower'
33
+
34
+
35
+ export type RenderVerdict = 'ok' | 'lossy' | 'error'
36
+
37
+ // One rendered unit: the path the instance gave it, its language, and
38
+ // its bytes, as one string.
39
+ export type RenderUnit = {
40
+ path: string
41
+ lang: string
42
+ text: string
43
+ }
44
+
45
+ // THE THREE LOSS TIERS (RENDER.0.md D7). Tier 1 is a check the target's
46
+ // type system cannot enforce (the declaration lowering's, P5); tier 2
47
+ // a fragment -- structured, re-indentable, terminator-checked, saying
48
+ // nothing about target syntax; tier 3 an opaque escape, a `text`
49
+ // declaration or a `raw` piece. `strict` refuses tier 3 and only
50
+ // tier 3.
51
+ export type RenderLoss = {
52
+ unit: string
53
+ path: string
54
+ tier: 1 | 2 | 3
55
+ construct: string
56
+ reason: string
57
+ }
58
+
59
+ // ONE PIECE'S PROVENANCE (RENDER.0.md D9, D11; P7). A dispatch stamps
60
+ // every piece it emits with the node it matched and the rule it took,
61
+ // and the fold reads the stamps back off the instance: `piece` is the
62
+ // piece's own path there, `unit` the unit it landed in, `node` the
63
+ // model address the rule matched, and `rule` the rule's address --
64
+ // its table's, then `#`, then its index in that table.
65
+ export type RenderTrace = {
66
+ unit: string
67
+ piece: string
68
+ node: string
69
+ rule: string
70
+ }
71
+
72
+ // THE COVERAGE REPORT (P7; G9 §6, "coverage cuts both ways"). Two
73
+ // lists, and both are set computations over what the run recorded.
74
+ export type RenderCoverage = {
75
+ // Every model path a reference resolved to, in walk order: what the
76
+ // render READ.
77
+ read: string[]
78
+ // Dead model: the SHALLOWEST model paths no read reached. A path
79
+ // whose subtree holds a read is not named; its unread children are.
80
+ dead: string[]
81
+ // A silent hole: a rendered declaration no rule produced. In a
82
+ // document with no rule table that is every declaration, which is
83
+ // the true statement about it -- the rule layer governs none of this
84
+ // output.
85
+ unruled: { unit: string, path: string }[]
86
+ }
87
+
88
+ export type RenderReport = {
89
+ verdict: RenderVerdict
90
+ // In `units[]` order. Empty on `error`.
91
+ units: RenderUnit[]
92
+ // Per unit and path. Empty on `error`.
93
+ lossy: RenderLoss[]
94
+ // On `error` only, in vet's finding shape: the document did not
95
+ // stand up, the instance is not `aontu:code`, or a unit could not be
96
+ // rendered (`render_*`).
97
+ errors?: VetFinding[]
98
+ // The dispatch trace, under `trace` or `coverage` (P7), in document
99
+ // order. Absent when it is empty, on `error`, and from
100
+ // `renderValue`, which folds an instance the recorder never watched
101
+ // being built.
102
+ trace?: RenderTrace[]
103
+ // The coverage report, under `coverage` (P7).
104
+ coverage?: RenderCoverage
105
+ }
106
+
107
+ export type RenderOptions = IncludeOptions & {
108
+ // The value to render, a path into the document. Absent means the
109
+ // root.
110
+ at?: string
111
+ // Where the document CAME FROM, so a relative `@"file"` load inside
112
+ // it resolves from its own directory.
113
+ path?: string
114
+ // Profiles supplied by the caller, each an evaluated profile map
115
+ // (`{lang, indent, ...}`), matched to a unit by `lang` before the
116
+ // bundled set is asked (RENDER.0.md D5, step 1).
117
+ profiles?: any[]
118
+ // Render only the unit at this path.
119
+ unit?: string
120
+ // Refuse tier-3 loss: the opaque escapes.
121
+ strict?: boolean
122
+ // RECORD THE DISPATCH TRACE (P7). Off by default: an instrumented
123
+ // run stamps every value a reference resolves and every piece a rule
124
+ // emits, and an ordinary one pays one property load per meet.
125
+ trace?: boolean
126
+ // Compute the coverage report, which needs the trace and turns it on.
127
+ coverage?: boolean
128
+ // Measure coverage under this path only, instead of the document
129
+ // root (RENDER.0.md X-3). The narrower measure a document with its
130
+ // model under one key wants.
131
+ coverageAt?: string
132
+ }
133
+
134
+
135
+ const VOCABULARY = '@"aontu:code"'
136
+ // The bundled profiles, by lang: aontu:lang/<lang>.
137
+ const BUNDLED_LANGS = ['go', 'text', 'typescript']
138
+ const PROFILE_VOCABULARY = '@"aontu:profile"'
139
+
140
+
141
+ function finding(
142
+ code: string, cls: string, path: string, message: string
143
+ ): VetFinding {
144
+ return { code, class: cls as any, severity: 'error', path, message, sites: [] }
145
+ }
146
+
147
+
148
+ function errorReport(errors: VetFinding[]): RenderReport {
149
+ return { verdict: 'error', units: [], lossy: [], errors }
150
+ }
151
+
152
+
153
+ // The verb's evaluation, before the fold (RENDER.0.md D1): evaluate,
154
+ // anchor, vet the anchored value against the vocabulary as `aontu vet`
155
+ // would, and generate the MEET of the two -- so the vocabulary's
156
+ // defaults (`at: 0`, `n: 1`, `reindent: true`) are in the instance the
157
+ // fold reads, whether or not the document included the vocabulary
158
+ // itself. THE VET AND THE MEET READ THE SETTLED VALUE, re-sourced
159
+ // through its hash form (valid source that evaluates to the same
160
+ // value), not the document's text: a fragment's lines are what a
161
+ // transform COMPUTED -- an `emit`, a `join` -- and the vocabulary's
162
+ // alternatives are tried against values, not against calls that are
163
+ // still waiting to fire. A finding from that vet therefore addresses
164
+ // the instance by path, which is the addressing every render finding
165
+ // uses (G9 §3); a document that does not stand up at all is reported
166
+ // with its own sites, before any of this.
167
+ export function render(src: string, options?: RenderOptions): RenderReport {
168
+ const opts = options ?? {}
169
+ const aontu = new Aontu(includeOpts(opts))
170
+
171
+ // THE RECORDER (P7), on for a run that was asked for a trace or a
172
+ // coverage report and off for every other. Its presence is the one
173
+ // switch: the read set fills as references resolve, and the two
174
+ // riders that carry a read address and a dispatch stamp are written
175
+ // only while it is there.
176
+ const rec = true === opts.trace || true === opts.coverage
177
+ const reads = rec ? new Set<string>() : undefined
178
+
179
+ // COLLECT MODE, so a syntax error arrives on the context rather than
180
+ // as a throw (the jsonschema and vet precedent; no try/catch, for
181
+ // the reason those verbs have none).
182
+ const actx = aontu.ctx({ collect: true, reads })
183
+ const root: any = aontu.unify(src, { path: opts.path, collect: true }, actx)
184
+ if (0 < actx.err.length || true === root?.isNil) {
185
+ return errorReport([failureFinding(actx, opts.path, root)])
186
+ }
187
+
188
+ let node: any = root
189
+ if (null != opts.at && '' !== opts.at) {
190
+ const found: any = anchorAt(root, opts.at)
191
+ if (null == found) {
192
+ // The anchor names nothing: a `no_path` nil through the finding
193
+ // shape every other refusal here uses.
194
+ const nil: any = makeNilErr(actx, 'no_path', root, undefined, 'at')
195
+ actx.err.push(nil)
196
+ return errorReport([failureFinding(actx, opts.path, root)])
197
+ }
198
+ node = found
199
+ }
200
+
201
+ // UNDER NO CALLER CAPABILITY, here and in the meet below: the
202
+ // vocabulary is the engine's own and the instance is a canon, which
203
+ // includes nothing, so the caller's include capability -- which
204
+ // governs the DOCUMENT -- has nothing to govern here, and `none`
205
+ // must not deny the renderer its own schema.
206
+ const value = hcanon(node)
207
+ const report = vet(VOCABULARY, value)
208
+ if ('valid' !== report.verdict) {
209
+ return errorReport(report.findings)
210
+ }
211
+
212
+ // The meet, keyed: the vocabulary's root holds `code`, and so does
213
+ // the instance's (a value the vet admitted is a map), and a document
214
+ // with no `code` at all is the vocabulary's own empty instance.
215
+ const codeVal: any = node.peg.code
216
+ const instance = new Aontu().generate(
217
+ VOCABULARY + (undefined === codeVal ? '' : '\ncode: ' + hcanon(codeVal)))
218
+ const folded = renderValue(instance, opts)
219
+
220
+ // THE TWO REPORTS ARE JOINED TO THE FOLD BY PATH (P7), which is what
221
+ // lets the fold stay the pure total function D6 asks for: the
222
+ // dispatch stamps ride the VALUE, the instance the fold reads is
223
+ // that value re-sourced through its hash form, and a piece is at the
224
+ // same path in both. Nothing to report on `error`: there are no
225
+ // units to attribute pieces to.
226
+ if (rec && 'error' !== folded.verdict) {
227
+ const marks = emitted(node)
228
+ const trace = traceOf(marks, instance, folded.units)
229
+ // AN EMPTY TRACE IS NO TRACE, in both ports: Go omits an empty
230
+ // slice, and a report shape that differed by port would be the one
231
+ // thing the shared rows exist to refuse. A run that emitted no
232
+ // piece has nothing to attribute, and the coverage report says so
233
+ // in its own words.
234
+ if (0 < trace.length) {
235
+ folded.trace = trace
236
+ }
237
+ if (true === opts.coverage) {
238
+ const cov = coverOf(root, node, reads as Set<string>, opts, marks,
239
+ instance, folded.units)
240
+ if (undefined === cov) {
241
+ const nil: any = makeNilErr(actx, 'no_path', root, undefined,
242
+ 'coverageAt')
243
+ actx.err.push(nil)
244
+ return errorReport([failureFinding(actx, opts.path, root)])
245
+ }
246
+ folded.coverage = cov
247
+ }
248
+ }
249
+ return folded
250
+ }
251
+
252
+
253
+ // ---------------------------------------------------------------------
254
+ // THE TRACE AND THE COVERAGE REPORT (RENDER.0.md D11, P7).
255
+
256
+ // The one walk order both ports walk in: a list by index, a map by key
257
+ // in code-point order. `fn` answers whether to descend.
258
+ function walkVals(root: any, fn: (v: any, path: string[]) => boolean): void {
259
+ const walk = (v: any, path: string[]): void => {
260
+ if (null == v || true !== v.isVal || !fn(v, path)) {
261
+ return
262
+ }
263
+ if (true === v.isList && null != v.peg) {
264
+ for (let i = 0; i < v.peg.length; i++) {
265
+ walk(v.peg[i], [...path, String(i)])
266
+ }
267
+ }
268
+ else if (true === v.isMap && null != v.peg) {
269
+ for (const k of Object.keys(v.peg).sort(cmpCodePoint)) {
270
+ // AN ALIAS DECLARATION IS NOT A MEMBER, here for the reason
271
+ // every fold has it (./val/members.ts): `%wire = …` holds a
272
+ // value the document never generates, so it is neither a piece
273
+ // to trace nor model that could be called dead.
274
+ if (!v.aliasKeys.includes(k)) {
275
+ walk(v.peg[k], [...path, k])
276
+ }
277
+ }
278
+ }
279
+ }
280
+ walk(root, [])
281
+ }
282
+
283
+
284
+ // A path as an address: `$`, then a dot before every segment.
285
+ function addr(path: string[]): string {
286
+ return '$' + path.map((seg) => '.' + seg).join('')
287
+ }
288
+
289
+
290
+ // Every piece a dispatch stamped, under the anchored value, in
291
+ // document order. The path is relative to the anchor, which is where
292
+ // the instance the fold reads is rooted too.
293
+ function emitted(node: any): { path: string, mark: any }[] {
294
+ const out: { path: string, mark: any }[] = []
295
+ walkVals(node, (v: any, path: string[]) => {
296
+ if (null != v.emitted) {
297
+ out.push({ path: addr(path), mark: v.emitted })
298
+ }
299
+ return true
300
+ })
301
+ return out
302
+ }
303
+
304
+
305
+ // The trace: one entry per stamped piece that a RENDERED unit holds. A
306
+ // piece is IN the unit whose path prefixes its own, which is the whole
307
+ // of the question -- no path is parsed, and a stamp that lies under no
308
+ // unit at all (a rule set held under a key of its own, and referred to
309
+ // from a unit) simply matches nothing. A unit the run did not render
310
+ // (`--unit` names one) has no bytes for a piece of it to be in, so it
311
+ // is not among the prefixes either.
312
+ function traceOf(marks: { path: string, mark: any }[], instance: any,
313
+ units: RenderUnit[]): RenderTrace[] {
314
+ const pre: { at: string, path: string }[] = []
315
+ unitList(instance).forEach((u: any, i: number) => {
316
+ if (units.some((r) => r.path === u.path)) {
317
+ pre.push({ at: '$.code.units.' + i, path: u.path })
318
+ }
319
+ })
320
+ const out: RenderTrace[] = []
321
+ for (const m of marks) {
322
+ const hit = pre.find((p) => m.path === p.at || m.path.startsWith(p.at + '.'))
323
+ if (undefined === hit) {
324
+ continue
325
+ }
326
+ out.push({ unit: hit.path, piece: m.path, node: m.mark.node, rule: m.mark.rule })
327
+ }
328
+ return out
329
+ }
330
+
331
+
332
+ // Every proper ancestor of an address, `$` included.
333
+ function ancestors(a: string): string[] {
334
+ const parts = a.split('.')
335
+ const out: string[] = []
336
+ for (let i = 1; i < parts.length; i++) {
337
+ out.push(parts.slice(0, i).join('.'))
338
+ }
339
+ return out
340
+ }
341
+
342
+
343
+ // Is the value at `a` covered by the set -- the address itself in it,
344
+ // or an address above it? An address ABOVE it covers the whole subtree:
345
+ // a reference that read `$.schema` read everything under it, and a rule
346
+ // that emitted a unit emitted every declaration in it.
347
+ function covered(set: Set<string>, a: string): boolean {
348
+ if (set.has(a)) {
349
+ return true
350
+ }
351
+ for (const up of ancestors(a)) {
352
+ if (set.has(up)) {
353
+ return true
354
+ }
355
+ }
356
+ return false
357
+ }
358
+
359
+
360
+ // THE COVERAGE REPORT (P7). Dead model is measured over the DOCUMENT
361
+ // ROOT, or under `coverageAt` when a document keeps its model under one
362
+ // key (X-3, decided here): the read set is absolute, so a narrower
363
+ // measure is a narrower walk, not a different origin. The render's own
364
+ // output -- `code` under the anchor -- is not model and is never
365
+ // walked into: nothing reads it, so every document would otherwise
366
+ // report it dead.
367
+ function coverOf(root: any, node: any, reads: Set<string>,
368
+ opts: RenderOptions, marks: { path: string, mark: any }[], instance: any,
369
+ units: RenderUnit[]): RenderCoverage | undefined {
370
+ // THE ANCHOR IS THE ONE render() ALREADY FOUND, so `code` under it is
371
+ // named without asking a second time: `--at` is resolved before the
372
+ // vet, and an anchor that named nothing never reached here.
373
+ const codeAddr = addr(node.path.concat('code'))
374
+
375
+ let from: any = root
376
+ let base: string[] = []
377
+ if (null != opts.coverageAt && '' !== opts.coverageAt) {
378
+ const found: any = anchorAt(root, opts.coverageAt)
379
+ if (null == found) {
380
+ return undefined
381
+ }
382
+ from = found
383
+ base = found.path
384
+ }
385
+
386
+ // The two questions asked of the read set, as sets: is this address
387
+ // read (or under one that is), and does a read lie BELOW it?
388
+ const above = new Set<string>(reads)
389
+ const below = new Set<string>()
390
+ for (const r of reads) {
391
+ for (const up of ancestors(r)) {
392
+ below.add(up)
393
+ }
394
+ }
395
+
396
+ const dead: string[] = []
397
+ walkVals(from, (_v: any, path: string[]) => {
398
+ const a = addr(base.concat(path))
399
+ if (a === codeAddr || covered(above, a)) {
400
+ return false
401
+ }
402
+ // THE ROOT OF THE MEASURE IS NEVER ITSELF DEAD MODEL, and is
403
+ // descended into whatever the read set holds. A document that is
404
+ // only a transform reads nothing above its own model, and naming
405
+ // the root there would report the whole document dead while its
406
+ // one live subtree sat inside it.
407
+ if (below.has(a) || 0 === path.length) {
408
+ return true
409
+ }
410
+ dead.push(a)
411
+ return false
412
+ })
413
+
414
+ // A SILENT HOLE: a declaration of a rendered unit that no stamp
415
+ // touches -- neither its own, nor one on the unit above it, nor one
416
+ // on a piece inside it.
417
+ const stamped = new Set<string>(marks.map((m) => m.path))
418
+ const inside = new Set<string>()
419
+ for (const m of marks) {
420
+ for (const up of ancestors(m.path)) {
421
+ inside.add(up)
422
+ }
423
+ }
424
+ const unruled: { unit: string, path: string }[] = []
425
+ unitList(instance).forEach((unit: any, i: number) => {
426
+ if (!units.some((u) => u.path === unit.path)) {
427
+ return
428
+ }
429
+ const decls: any[] = unit.decls
430
+ decls.forEach((_d: any, j: number) => {
431
+ const a = '$.code.units.' + i + '.decls.' + j
432
+ if (!covered(stamped, a) && !inside.has(a)) {
433
+ unruled.push({ unit: unit.path, path: a })
434
+ }
435
+ })
436
+ })
437
+
438
+ return { read: [...reads].sort(cmpCodePoint), dead, unruled }
439
+ }
440
+
441
+
442
+ // The bundled text profile, evaluated once: the profile of a unit
443
+ // whose declarations are fragments and text escapes only.
444
+ const bundled: Record<string, any> = {}
445
+
446
+ // A bundled profile, evaluated once: the meet of aontu:lang/<lang>
447
+ // with the vocabulary, so its defaults are in it.
448
+ function bundledProfile(lang: string): any {
449
+ if (!BUNDLED_LANGS.includes(lang)) {
450
+ return undefined
451
+ }
452
+ if (undefined === bundled[lang]) {
453
+ bundled[lang] = new Aontu().generate('@"aontu:lang/' + lang + '"').profile
454
+ }
455
+ return bundled[lang]
456
+ }
457
+
458
+
459
+ // PROFILE SELECTION, per unit (RENDER.0.md D5): a caller-supplied
460
+ // profile whose `lang` is the unit's; else the bundled profile of that
461
+ // `lang`; else `aontu:lang/text`, if and only if every declaration in
462
+ // the unit is a fragment or a text escape; else nothing, which the
463
+ // caller reports as `render_profile`. The unit's inline `profile` is
464
+ // merged over whichever base was found.
465
+ function profileFor(lang: string, given: any[] | undefined, fragOnly: boolean): any {
466
+ const supplied = (given ?? []).find((p: any) => p?.lang === lang)
467
+ if (undefined !== supplied) {
468
+ return supplied
469
+ }
470
+ const own = bundledProfile(lang)
471
+ if (undefined !== own) {
472
+ return own
473
+ }
474
+ return fragOnly ? bundledProfile('text') : undefined
475
+ }
476
+
477
+
478
+ function isMap(v: any): boolean {
479
+ return null != v && 'object' === typeof v && !Array.isArray(v)
480
+ }
481
+
482
+
483
+ // An inline profile merged over its base, map by map, the inline
484
+ // value winning at a leaf; keys in code-point order, so the merge is
485
+ // the same in both ports.
486
+ function mergeProfile(base: any, over: any): any {
487
+ const out: any = { ...base }
488
+ for (const k of Object.keys(over).sort(cmpCodePoint)) {
489
+ out[k] = isMap(base[k]) && isMap(over[k]) ?
490
+ mergeProfile(base[k], over[k]) : over[k]
491
+ }
492
+ return out
493
+ }
494
+
495
+
496
+ // THE FOLD (RENDER.0.md D6). `pad(at)` is `indent.unit` repeated
497
+ // `indent.width × at` times; a line is `pad + text + LF`, and an empty
498
+ // text emits no pad; a blank is its terminators alone; a raw block's
499
+ // lines each get the pad unless `reindent: false`, which emits them
500
+ // at column 0 verbatim -- and common leading indentation is never
501
+ // stripped. A reference inline is its name, verbatim (a
502
+ // declaration-capable profile puts it through its identifier rules,
503
+ // P5). Nothing is trimmed (D3): the text is the transform's.
504
+ // A profile with no indent -- a caller-supplied map the vocabulary
505
+ // never filled -- takes the vocabulary's own default, two spaces.
506
+ function pad(profile: any, at: number): string {
507
+ const indent = profile.indent ?? { unit: ' ', width: 2 }
508
+ return (indent.unit ?? ' ').repeat((indent.width ?? 2) * at)
509
+ }
510
+
511
+ function line(profile: any, at: number, text: string): string {
512
+ return ('' === text ? '' : pad(profile, at)) + text + '\n'
513
+ }
514
+
515
+ // A reference inline is its name: through the profile's identifier
516
+ // rules under a lowering, verbatim under text.
517
+ function inline(piece: any, ctx: LowerCtx | undefined): string {
518
+ if ('string' === typeof piece) {
519
+ return piece
520
+ }
521
+ return undefined === ctx ? piece.name : ident(piece.name, 'record', ctx, '', false)
522
+ }
523
+
524
+ function foldPiece(
525
+ piece: any, profile: any, unit: string, path: string, lossy: RenderLoss[],
526
+ ctx?: LowerCtx
527
+ ): string {
528
+ if ('string' === typeof piece) {
529
+ return line(profile, 0, piece)
530
+ }
531
+ if ('line' === piece.k) {
532
+ return line(profile, piece.at ?? 0, piece.of.map((p: any) => inline(p, ctx)).join(''))
533
+ }
534
+ if ('blank' === piece.k) {
535
+ return '\n'.repeat(piece.n ?? 1)
536
+ }
537
+ lossy.push({
538
+ unit, path, tier: 3, construct: 'raw',
539
+ reason: 'verbatim text: the renderer re-indents it and checks nothing else',
540
+ })
541
+ const at: number = piece.at ?? 0
542
+ const reindent: boolean = piece.reindent ?? true
543
+ const lines: string[] = piece.text.split('\n')
544
+ if ('' === lines[lines.length - 1]) {
545
+ lines.pop()
546
+ }
547
+ return lines.map((l: string) => reindent ? line(profile, at, l) : l + '\n').join('')
548
+ }
549
+
550
+
551
+ // A PROFILE DOCUMENT (RENDER.0.md D5), evaluated the way `render`
552
+ // evaluates its own: under the caller's include options, then vetted
553
+ // against aontu:profile as a settled value and met with that vocabulary
554
+ // so its defaults (`indent.width: 2`, ...) are in it. The answer is the
555
+ // `profile` map the fold reads -- what `--profile <file>` hands to
556
+ // RenderOptions.profiles -- or the findings that refused the document:
557
+ // one that does not stand up, or one the vocabulary rejects.
558
+ export function renderProfile(src: string, options?: RenderOptions):
559
+ { profile?: any, errors?: VetFinding[] } {
560
+ const opts = options ?? {}
561
+ const aontu = new Aontu(includeOpts(opts))
562
+ const actx = aontu.ctx({ collect: true })
563
+ const root: any = aontu.unify(src, { path: opts.path, collect: true }, actx)
564
+ if (0 < actx.err.length || true === root?.isNil) {
565
+ return { errors: [failureFinding(actx, opts.path, root)] }
566
+ }
567
+ const report = vet(PROFILE_VOCABULARY, hcanon(root))
568
+ if ('valid' !== report.verdict) {
569
+ return { errors: report.findings }
570
+ }
571
+ // The meet, keyed as render's is: the vocabulary requires `profile`,
572
+ // so a value the vet admitted has one.
573
+ const instance = new Aontu().generate(
574
+ PROFILE_VOCABULARY + '\nprofile: ' + hcanon(root.peg.profile))
575
+ return { profile: instance.profile }
576
+ }
577
+
578
+
579
+ // The instance's unit list, or none: `code` is the vocabulary's own
580
+ // key and is always there, `units` is not. One reader, so the fold,
581
+ // the trace and the coverage report all see the same list.
582
+ function unitList(instance: any): any[] {
583
+ return Array.isArray(instance?.code?.units) ? instance.code.units : []
584
+ }
585
+
586
+
587
+ // The fold alone, over `generate()` output: the instance is
588
+ // `{code: {units: [...]}}` as the vocabulary shapes it, with its
589
+ // defaults filled -- which is what `render` hands over, and what a
590
+ // caller of this function is responsible for.
591
+ export function renderValue(instance: any, options?: RenderOptions): RenderReport {
592
+ const opts = options ?? {}
593
+ const errors: VetFinding[] = []
594
+ const lossy: RenderLoss[] = []
595
+ const units: RenderUnit[] = []
596
+ const list: any[] = unitList(instance)
597
+
598
+ const seen: string[] = []
599
+ let selected = 0
600
+ list.forEach((unit: any, i: number) => {
601
+ const upath = '$.code.units.' + i
602
+ const path: string = unit.path
603
+ const lang: string = unit.lang
604
+
605
+ // A UNIT PATH IS RELATIVE, DESCENDS, AND IS ITS OWN (RENDER.0.md
606
+ // D8): an absolute path, a `..` segment or a repeat of another
607
+ // unit's path is refused before anything is written.
608
+ if (path.startsWith('/')) {
609
+ errors.push(finding('render_path', 'parse', upath + '.path',
610
+ 'the unit path ' + path + ' is absolute.'))
611
+ return
612
+ }
613
+ if (path.split('/').includes('..')) {
614
+ errors.push(finding('render_path', 'parse', upath + '.path',
615
+ 'the unit path ' + path + ' climbs out of the output directory.'))
616
+ return
617
+ }
618
+ if (seen.includes(path)) {
619
+ errors.push(finding('render_path', 'parse', upath + '.path',
620
+ 'the unit path ' + path + ' repeats another unit\'s.'))
621
+ return
622
+ }
623
+ seen.push(path)
624
+
625
+ if (undefined !== opts.unit && opts.unit !== path) {
626
+ return
627
+ }
628
+ selected++
629
+
630
+ const decls: any[] = unit.decls
631
+ const fragOnly = decls.every((d: any) => 'frag' === d.k || 'text' === d.k)
632
+ const base = profileFor(lang, opts.profiles, fragOnly)
633
+ if (undefined === base) {
634
+ errors.push(finding('render_profile', 'parse', upath + '.lang',
635
+ 'no profile renders ' + lang + ': a declaration needs a lowering, and ' +
636
+ 'only fragments and text escapes render under aontu:lang/text.'))
637
+ return
638
+ }
639
+ const profile = null == unit.profile ? base : mergeProfile(base, unit.profile)
640
+
641
+ // THE LOWERING (D5, P5), when the profile names one: the unit's
642
+ // header -- banner, package clause, imports -- and each declaration
643
+ // as pieces the fold takes, a blank line between two lowered
644
+ // declarations. A fragment or a text escape owns its own blanks.
645
+ const family: string | undefined = profile.lowering
646
+ const ctx: LowerCtx | undefined = undefined === family ? undefined
647
+ : { profile, family, unit: path, lossy }
648
+
649
+ let text = ''
650
+ if (undefined !== ctx) {
651
+ const header = lowerHeader(unit, instance?.code?.source, ctx)
652
+ for (const piece of header) {
653
+ text += foldPiece(piece, profile, path, upath, lossy, ctx)
654
+ }
655
+ if (0 < header.length && 0 < decls.length) {
656
+ text += '\n'
657
+ }
658
+ }
659
+ let lowered = false
660
+ decls.forEach((decl: any, j: number) => {
661
+ const dpath = upath + '.decls.' + j
662
+ if ('frag' === decl.k) {
663
+ lowered = false
664
+ lossy.push({
665
+ unit: path, path: dpath, tier: 2, construct: 'frag',
666
+ reason: 'a fragment says nothing about ' + lang + ' syntax',
667
+ })
668
+ decl.of.forEach((piece: any, n: number) => {
669
+ text += foldPiece(piece, profile, path, dpath + '.of.' + n, lossy, ctx)
670
+ })
671
+ }
672
+ else if ('text' === decl.k) {
673
+ lowered = false
674
+ if (decl.lang !== lang) {
675
+ errors.push(finding('render_lang', 'conflict', dpath + '.lang',
676
+ 'the text escape is ' + decl.lang + ' in a ' + lang + ' unit.'))
677
+ return
678
+ }
679
+ lossy.push({
680
+ unit: path, path: dpath, tier: 3, construct: 'text',
681
+ reason: 'verbatim ' + lang + ': the renderer checks nothing in it',
682
+ })
683
+ text += decl.text
684
+ }
685
+ else if (undefined !== ctx) {
686
+ if (lowered) {
687
+ text += '\n'
688
+ }
689
+ for (const piece of lowerDecl(decl, dpath, ctx)) {
690
+ text += foldPiece(piece, profile, path, dpath, lossy, ctx)
691
+ }
692
+ lowered = true
693
+ }
694
+ else {
695
+ errors.push(finding('render_profile', 'parse', dpath + '.k',
696
+ 'a ' + decl.k + ' declaration has no lowering under the ' +
697
+ profile.lang + ' profile.'))
698
+ }
699
+ })
700
+
701
+ units.push({ path, lang, text })
702
+ })
703
+
704
+ if (undefined !== opts.unit && 0 === selected) {
705
+ errors.push(finding('render_unit', 'reference', '$.code.units',
706
+ 'no unit has the path ' + opts.unit + '.'))
707
+ }
708
+
709
+ if (true === opts.strict) {
710
+ for (const loss of lossy) {
711
+ if (3 === loss.tier) {
712
+ errors.push(finding('render_strict', 'conflict', loss.path,
713
+ 'the ' + loss.construct + ' in ' + loss.unit +
714
+ ' is an opaque escape, refused under strict.'))
715
+ }
716
+ }
717
+ }
718
+
719
+ if (0 < errors.length) {
720
+ return errorReport(errors)
721
+ }
722
+ return {
723
+ verdict: 0 < lossy.length ? 'lossy' : 'ok',
724
+ units,
725
+ lossy,
726
+ }
727
+ }