hclang 0.37.3 → 0.38.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.
@@ -226,7 +226,8 @@ export const HC_SOURCES = new Map([
226
226
  "",
227
227
  "=== Schema Retrieval and Captures (implemented, #310)",
228
228
  "",
229
- "The `<>` property retrieves the schema attached to the binding:",
229
+ "The `<^>` property retrieves the schema attached to the binding; `.<>` observes",
230
+ "the runtime type:",
230
231
  "```",
231
232
  "; enum123.<^>",
232
233
  "# <1, 2, 3>",
@@ -690,14 +691,17 @@ export const HC_SOURCES = new Map([
690
691
  "; [.a 1] & {_}",
691
692
  "# []",
692
693
  "```",
693
- "`.#` and `.##` count the elements too, the immediate ones and the terminals",
694
- "below them, so neither counts a property. A terminal is an element that is not",
695
- "an aggregate, or an aggregate with no elements: the empty frame is one terminal,",
696
- "at the root or nested. A nested count contributes its own Size, including zero",
697
- "(`[[3], 0].##` is 3); other atoms contribute one. Every aggregate counts this",
698
- "way, a group as well as an array. A count is its own size, and any other value",
699
- "has none (#411, issue",
700
- "occurrence/figure 010.02)",
694
+ "`.#` counts immediate elements or represented words; properties do not count.",
695
+ "A missing Count rule falls back to native Size, including numbers, text, blobs,",
696
+ "bytes and opaque atoms. Explicit list, schema and all Count rules take precedence; `()` has no Count. `.##` measures represented",
697
+ "quantity: lists sum complete child Sizes, with Size 1 for an empty list. Numeric",
698
+ "magnitude, Unicode text length, blob bits and payload bytes have their own native",
699
+ "Sizes; schemas retain their description/alternative quantities. Other opaque",
700
+ "values have Size 1. `.###` alternates child Sizes on non-schema lists, or returns",
701
+ "Count parity (`.# mod 2`) on every other value with a Count; schemas have nil",
702
+ "residual, and `<>` observes as `[]`. `.####` derives a Demi, an instance of",
703
+ "the class in `hc/demi.hc`, returning nil at zero Count or nil residual and",
704
+ "propagating failed observations.",
701
705
  "```",
702
706
  "; [.meta 1; 2, 3] .#",
703
707
  "# 2",
@@ -710,7 +714,7 @@ export const HC_SOURCES = new Map([
710
714
  "; 5.#",
711
715
  "# 5",
712
716
  "; “abc”.#",
713
- "# ()",
717
+ "# 3",
714
718
  "```",
715
719
  "**Decision.** Canonical rendering puts the properties first, then the elements.",
716
720
  "This reverses the spelling this file carried before. It makes print order agree",
@@ -1159,6 +1163,271 @@ export const HC_SOURCES = new Map([
1159
1163
  "",
1160
1164
  ].join("\n"),
1161
1165
  ],
1166
+ [
1167
+ "hc/demi.hc",
1168
+ [
1169
+ "#!/usr/bin/env hc",
1170
+ "```",
1171
+ "Demi (occurrence/figure 011.20)",
1172
+ "",
1173
+ "A Demi is a closed two-channel state: a phase and two loads, left and right.",
1174
+ "Applying a Demi to a Frame deposits that Frame's Size into the active load and",
1175
+ "flips the phase, so a Demi follows alternating construction one observation at",
1176
+ "a time. It is what the fourth hash answers: `x.####` is the Demi of x's Count,",
1177
+ "Size and residual, with left load (Size + residual)/2 and right load",
1178
+ "(Size − residual)/2.",
1179
+ "",
1180
+ "`Demi` is an ordinary HC class: a constructor closure answering a fresh",
1181
+ "aggregate whose fields are its state and whose methods are the class. Nothing",
1182
+ "about it is native. The fourth hash keeps only its derivation and builds its",
1183
+ "answer with this constructor, which the evaluator reads from this file, compiled",
1184
+ "in, the first time `.####` needs one. So this file is both the definition every",
1185
+ "evaluator uses and its specification, and it works without a resource root.",
1186
+ "Import it to construct Demis directly: `Demis <- './hc/demi.hc'`, then",
1187
+ "`Demis.Demi [2, 0, 0]`.",
1188
+ "",
1189
+ "**State.** `Demi [phase, left, right]` takes three Counts. The phase is the",
1190
+ "least positive Count of its parity (011.18g): 2 when even, left next, and 1",
1191
+ "when odd, right next. It is a Count rather than all or nil because a field",
1192
+ "cannot hold nil, and a Count keeps the odd phase present: a Demi in phase 1 is",
1193
+ "a value, unlike the nil `.####` answers for a Frame with no Demi. Anything else",
1194
+ "is refused with `invalid-demi`, a missing name, as Figures refuses an",
1195
+ "unsupported host. The fields are the whole state, so two Demis are `=` exactly",
1196
+ "when their fields are.",
1197
+ "",
1198
+ "**Observers.** A Demi declares its own Count, Size and residual (011.20): its",
1199
+ "phase, its total load L+R, and the signed difference L−R. An aggregate",
1200
+ "otherwise observes its elements, and a Demi has none, so without these it",
1201
+ "would observe as 0, 1, 0. Its fourth hash derives from them like any Frame's,",
1202
+ "so `d.####` rebuilds the same Demi.",
1203
+ "",
1204
+ "**Application**, `d x`: observe x's Size once, deposit it into the active load,",
1205
+ "flip the phase. A Size of zero still flips. If x has no Size, its failure is",
1206
+ "the answer rather than a deposit. It is a mutating method, `apply_`, so",
1207
+ "through a name, `d x` is a functional update: it answers a new Demi and leaves",
1208
+ "d unchanged, holding exactly the same three fields.",
1209
+ "",
1210
+ "**Scaling**, `d.scale_ k`: multiply both loads by a Count k, keeping the",
1211
+ "phase. It is the numerical shadow of Star: `(x * y).####` is",
1212
+ "`x.####.scale_ (y.##)` for a nonempty host x. Scaling is a method because a",
1213
+ "class cannot declare an operator, so `d * k` is ordinary Star, which refuses",
1214
+ "an aggregate with properties.",
1215
+ "",
1216
+ "**Text.** A Demi prints as what it is, an aggregate of fields and methods, and",
1217
+ "that reads back as the same Demi. As text it reads `Demi(<>,12,3)`, with the",
1218
+ "phase spelled as the orientation it stands for.",
1219
+ "",
1220
+ "**Methods read their own state through `_^`.** A bare name inside a method is",
1221
+ "looked up on the argument first (spec 7), and a Demi is applied to arbitrary",
1222
+ "Frames, so a bare `left` could read the argument's field. `_^` is the receiver",
1223
+ "from a method's body, and `_^^` from a block one level in, because carets",
1224
+ "count lexically (spec a06). What a branch needs is bound as a local at method",
1225
+ "level, where nested blocks read it.",
1226
+ "```",
1227
+ ".Demi {.p (_ .0); .l (_ .1); .r (_ .2);",
1228
+ " ((((p = 2) : {p = 1}) ? {p ~ (0.<>)}) ? {(l ~ (0.<>)) ? {r ~ (0.<>)}}) ? {[",
1229
+ " .phase p;",
1230
+ " .left l;",
1231
+ " .right r;",
1232
+ " .# {_^.phase};",
1233
+ " .## {_^.left + _^.right};",
1234
+ " .### {_^.left - _^.right};",
1235
+ " .apply_ {.s (_ .##); .l (_^ .left); .r (_^ .right);",
1236
+ " (s ~ (0.<>)) ? {((_^^ .phase) = 2) ? {@left (l + s); @phase 1;} : {@right (r + s); @phase 2;}; _^^} : {s}};",
1237
+ " .scale_ {.k _; .l (_^ .left); .r (_^ .right);",
1238
+ " (k ~ (0.<>)) ? {@left (l * k); @right (r * k); _^^} : {invalid-scale}};",
1239
+ " .toText {“Demi(” (((_^ .phase) = 2) ? {“<>”} : {“()”}) “,” (_^ .left) “,” (_^ .right) “)”}",
1240
+ " ]} : {invalid-demi}};",
1241
+ "```",
1242
+ "## Construction",
1243
+ "",
1244
+ "A Demi holds exactly its three fields. Each instance is its own: two built",
1245
+ "from the same constructor share nothing",
1246
+ "```",
1247
+ "; .d (Demi [2, 0, 0]);",
1248
+ "; [d.phase, d.left, d.right]",
1249
+ "# [2, 0, 0]",
1250
+ "; .a (Demi [2, 5, 3]); .b (Demi [1, 7, 0]);",
1251
+ "; [“” a, “” b, a.left, b.left]",
1252
+ "# [“Demi(<>,5,3)”, “Demi((),7,0)”, 5, 7]",
1253
+ "```",
1254
+ "Anything but three Counts with phase 1 or 2 is refused",
1255
+ "```",
1256
+ "; Demi [3, 0, 0]",
1257
+ "# $!.name-missing “$:Frame.0.invalid-demi”;",
1258
+ "; [Demi [2, (0 - 1), 0], Demi [2, (5 - 3), 0], Demi [2, 0], Demi 5, Demi [(5 - 3), 0, 0]]",
1259
+ "# [$!.name-missing “$:Frame.0.invalid-demi”;, $!.name-missing “$:Frame.0.invalid-demi”;, $!.name-missing “$:Frame.0.invalid-demi”;, $!.name-missing “$:Frame.0.invalid-demi”;, $!.name-missing “$:Frame.0.invalid-demi”;]",
1260
+ "```",
1261
+ "## Application",
1262
+ "",
1263
+ "Each application deposits the argument's Size into the active load and flips",
1264
+ "the phase. The receiver is left as it was",
1265
+ "```",
1266
+ "; “” (d [5, 3])",
1267
+ "# “Demi((),8,0)”",
1268
+ "; “” d",
1269
+ "# “Demi(<>,0,0)”",
1270
+ "; “” (((d 5) 3) 7)",
1271
+ "# “Demi((),12,3)”",
1272
+ "```",
1273
+ "A Size of zero deposits nothing and still flips, in both phases",
1274
+ "```",
1275
+ "; [(d 0).phase, ((d 0) 0).phase, (d 0).left, ((d 0) 0).right]",
1276
+ "# [1, 2, 0, 0]",
1277
+ "```",
1278
+ "Any Frame is applied by its Size, measured without running it: text, the",
1279
+ "empty aggregate and all (Size 1 each), nested aggregates, a closure (one per",
1280
+ "word, so `{5 + 3}` is 9), empty text, and loads too large for a machine integer",
1281
+ "```",
1282
+ "; “” ((((((d “hello”) []) <>) [[1, 2], [3]]) {5 + 3}) “”)",
1283
+ "# “Demi(<>,15,7)”",
1284
+ "; “” ((d 123456789012345678901234567890) 987654321098765432109876543210)",
1285
+ "# “Demi(<>,123456789012345678901234567890,987654321098765432109876543210)”",
1286
+ "```",
1287
+ "A Frame without a Size is not deposited: its failure is the answer",
1288
+ "```",
1289
+ "; d ([].nope)",
1290
+ "# $!.name-missing “...",
1291
+ "; “” d",
1292
+ "# “Demi(<>,0,0)”",
1293
+ "```",
1294
+ "Deposit reads the receiver through `_^`, so an argument that holds fields of",
1295
+ "the same names deposits by its Size and nothing else",
1296
+ "```",
1297
+ "; “” (d [.left 50; .phase 1; .s 100; 4])",
1298
+ "# “Demi((),4,0)”",
1299
+ "```",
1300
+ "A Demi captured by a closure, mapped, or reduced is applied the same way, and",
1301
+ "the captured one stays as it was",
1302
+ "```",
1303
+ "; .start (Demi [2, 0, 0]); .step {start _};",
1304
+ "; [“” (step 5), “” (step 3), “” start]",
1305
+ "# [“Demi((),5,0)”, “Demi((),3,0)”, “Demi(<>,0,0)”]",
1306
+ "; [d, a] & {“” (_ 5)}",
1307
+ "# [“Demi((),5,0)”, “Demi((),10,3)”]",
1308
+ "; “” ([5, 3, 7] | (Demi [2, 0, 0]))",
1309
+ "# “Demi((),12,3)”",
1310
+ "```",
1311
+ "Through a mutable name, application writes the Demi in place",
1312
+ "```",
1313
+ "; .m_ (Demi [2, 0, 0]);",
1314
+ "; m_ 5;",
1315
+ "; “” m_",
1316
+ "# “Demi((),5,0)”",
1317
+ "```",
1318
+ "## Observers",
1319
+ "",
1320
+ "A Demi's Count is its phase, its Size the total load and its residual the",
1321
+ "signed difference, including a present zero-load Demi in either phase",
1322
+ "```",
1323
+ "; .e (Demi [1, 12, 3]);",
1324
+ "; [e.#, e.##, e.###]",
1325
+ "# [1, 15, 9]",
1326
+ "; [d.#, d.##, d.###, (Demi [1, 0, 0]).#]",
1327
+ "# [2, 0, 0, 1]",
1328
+ "```",
1329
+ "So its fourth hash is the same Demi, however often it is taken. It is equal,",
1330
+ "not identical: each observation builds a new instance",
1331
+ "```",
1332
+ "; [e.#### = e, e.#### === e, e.#### == e, ((e.####).####).#### = e]",
1333
+ "# [<>, (), <>, <>]",
1334
+ "; [d.#### = d, (Demi [1, 0, 0]).#### = (Demi [1, 0, 0])]",
1335
+ "# [<>, <>]",
1336
+ "```",
1337
+ "A Demi inside an aggregate contributes its declared Size",
1338
+ "```",
1339
+ "; [[e, e].##, [e, d].###, [e].#### = (Demi [1, 15, 0])]",
1340
+ "# [30, 15, <>]",
1341
+ "```",
1342
+ "## The fourth hash",
1343
+ "",
1344
+ "`.####` answers an instance of this class, built from the same source, so it",
1345
+ "compares equal to one built here",
1346
+ "```",
1347
+ "; [[5, 3].#### = (Demi [2, 5, 3]), “hello”.#### = (Demi [1, 3, 2]), [0].#### = (Demi [1, 0, 0])]",
1348
+ "# [<>, <>, <>]",
1349
+ "; “” [5, 3, 7].####",
1350
+ "# “Demi((),12,3)”",
1351
+ "```",
1352
+ "It is nil where there is no Demi: an empty host, Count zero, no Count, or no",
1353
+ "residual. Properties are not elements, sharing counts each occurrence, and a",
1354
+ "group observes as its elements",
1355
+ "```",
1356
+ "; [[].####, 0.####, ().####, <2,3,5>.####]",
1357
+ "# [(), (), (), ()]",
1358
+ "; .shared [1, 2];",
1359
+ "; [[.a 100; 5, 3].#### = [5, 3].####, [shared, shared].#### = (Demi [2, 3, 3]), (5, 3).#### = (Demi [2, 5, 3])]",
1360
+ "# [<>, <>, <>]",
1361
+ "```",
1362
+ "## Observing commutes with applying",
1363
+ "",
1364
+ "For a nonempty host X, observing X Y is applying X's Demi to Y, and both equal",
1365
+ "the observation of the array X Y constructs",
1366
+ "```",
1367
+ "; .X [5, “ab”, [1, 2]];",
1368
+ "; [(X 7).#### = (X.#### 7), (X 7).#### = [5, “ab”, [1, 2], 7].####, (X {5 + 3}).#### = (X.#### {5 + 3})]",
1369
+ "# [<>, <>, <>]",
1370
+ "```",
1371
+ "The empty host is the boundary. `[].####` is nil, a choice of convention",
1372
+ "(011.15g) rather than a theorem, and applying nil answers the argument, so",
1373
+ "the equation as written fails there. Lifting the empty host to the zero-load",
1374
+ "Demi in phase 2 restores it: that is the initialized-router reading, and it is",
1375
+ "also what a reduce starts from",
1376
+ "```",
1377
+ "; [([] 7).#### = ([].#### 7), ([] 7).#### = ((Demi [2, 0, 0]) 7), ([] 7).#### = ([7] | (Demi [2, 0, 0]))]",
1378
+ "# [(), <>, <>]",
1379
+ "; [] | (Demi [2, 0, 0]) = (Demi [2, 0, 0])",
1380
+ "# <>",
1381
+ "```",
1382
+ "## Scaling and Star",
1383
+ "",
1384
+ "Scaling multiplies both loads and keeps the phase: zero annihilates, one is",
1385
+ "the identity, and scaling composes",
1386
+ "```",
1387
+ "; [“” (e.scale_ 2), “” (e.scale_ 0), (e.scale_ 1) = e, ((e.scale_ 2).scale_ 3) = (e.scale_ 6)]",
1388
+ "# [“Demi((),24,6)”, “Demi((),0,0)”, <>, <>]",
1389
+ "; e.scale_ (0 - 2)",
1390
+ "# $!.name-missing “$:Frame.0.invalid-scale”;",
1391
+ "```",
1392
+ "It is the shadow of Star on a nonempty host",
1393
+ "```",
1394
+ "; [([5, 3] * 3).#### = ([5, 3].####.scale_ 3), ([[[]], []] * [[], []]).#### = ([[[]], []].####.scale_ ([[], []].##))]",
1395
+ "# [<>, <>]",
1396
+ "```",
1397
+ "No operator is overloaded: `+` is ordinary addition, which a Demi is not a",
1398
+ "number for, and `*` is ordinary Star, which refuses an aggregate with fields",
1399
+ "```",
1400
+ "; [e + 3, e * 3]",
1401
+ "# [(), $!.star-metadata *]",
1402
+ "```",
1403
+ "## A precise regression: a load read at the wrong depth",
1404
+ "",
1405
+ "Carets count lexically, so inside a branch `_^` is the method's own scope, not",
1406
+ "the receiver. Reading a load there fails, `$!.name-missing`. Before 011.20,",
1407
+ "`+` turned that failure into nil, and writing nil leaves a field as it was, so",
1408
+ "the deposit silently did nothing while the phase still flipped. Now the",
1409
+ "failure reaches the field, where it shows",
1410
+ "```",
1411
+ "; .Wrong {[.phase 2; .left 0; .apply_ {.s (_ .##); (_^.phase = 2) ? {@left (_^.left + s); @phase 1;};}]};",
1412
+ "; .w ((Wrong ()) 5);",
1413
+ "; [w.phase, w.left]",
1414
+ "# [1, $!.name-missing “...",
1415
+ "; .Right {[.phase 2; .left 0; .apply_ {.s (_ .##); (_^.phase = 2) ? {@left (_^^.left + s); @phase 1;};}]};",
1416
+ "; .r ((Right ()) 5);",
1417
+ "; [r.phase, r.left]",
1418
+ "# [1, 5]",
1419
+ "```",
1420
+ "## Importing",
1421
+ "",
1422
+ "Imported, the file binds the same class. The import is an example line, so",
1423
+ "the evaluator, which reads this file without a root, never runs it",
1424
+ "```",
1425
+ "; Demis <- './hc/demi.hc';",
1426
+ "; [(Demis.Demi [2, 5, 3]) = [5, 3].####, “” ((Demis.Demi [2, 0, 0]) 4)]",
1427
+ "# [<>, “Demi((),4,0)”]",
1428
+ "",
1429
+ ].join("\n"),
1430
+ ],
1162
1431
  [
1163
1432
  "hc/figures.hc",
1164
1433
  [
@@ -1186,9 +1455,15 @@ export const HC_SOURCES = new Map([
1186
1455
  "Flat repetition is `x.## [y]`. A tally, when wanted, is an explicit",
1187
1456
  "construction, such as `x & {[[]]}` for one fresh mark per immediate element.",
1188
1457
  "Native `.##` uses each child's native Size, including numeric magnitude and",
1189
- "text length. Native `.###` also accepts mixed arrays and evaluated groups.",
1458
+ "text length. Native `.###` also accepts mixed arrays, groups, and non-schema list syntax/closures. Every other",
1459
+ "value with a Count answers its parity (`.# mod 2`, a FrameInt), including valid zero, so equal quantities",
1460
+ "observe alike whatever their kind or numeric type; schemas answer nil. `()` has no Count; `<>` observes as `[]`.",
1461
+ "Missing Count rules fall back to Size, including sized atoms. Explicit Counts take precedence.",
1462
+ "Stored errors and failed child quantities propagate rather than acquiring a load.",
1190
1463
  "Star keeps its narrower array/Count composition domain.",
1191
1464
  "",
1465
+ "For Counts, Gap and Spin now use parity too: `gap 7` is 1 and `spin 2 4` is 0.",
1466
+ "",
1192
1467
  "Only two derived mathematical abbreviations remain: Gap = |signed residual|",
1193
1468
  "and Spin = signed residual / positive Count. They define no Figure domain.",
1194
1469
  "Incidence is native `point ~~~ line`; collective incidence uses ordinary",
@@ -1300,7 +1575,7 @@ export const HC_SOURCES = new Map([
1300
1575
  "; [[[], [[]]], [[[], []], []], [[[[], [], []]]]].###",
1301
1576
  "# 2",
1302
1577
  "; [[1, []].###, [[], “ab”].###, [[], ([], [])].###, 5.###]",
1303
- "# [0, -1, -1, ()]",
1578
+ "# [0, -1, -1, 1]",
1304
1579
  "```",
1305
1580
  "Native Size also measures mixed values, independently of structural Star.",
1306
1581
  "Numeric magnitude truncates exactly; text length uses native Unicode code-point iteration,",
@@ -1315,7 +1590,7 @@ export const HC_SOURCES = new Map([
1315
1590
  "; [[5, “hello”].##, [5, “hello”].###, (5, 3).###, [5, 3, 2, 7].###]",
1316
1591
  "# [10, 0, 2, -3]",
1317
1592
  "; [([5, “hello”].### ? {<>} : {()}), (5.### ? {<>} : {()})]",
1318
- "# [<>, ()]",
1593
+ "# [<>, <>]",
1319
1594
  "; { .x <[].<>> _; x.### } [[], [“nested atom”]]",
1320
1595
  "# -10",
1321
1596
  "```",
@@ -1359,6 +1634,37 @@ export const HC_SOURCES = new Map([
1359
1634
  "; [.tag 1;] * [[]]",
1360
1635
  "# $!.star-metadata *",
1361
1636
  "```",
1637
+ "The fourth observer derives a Demi from Count, Size and residual.",
1638
+ "A zero Count or absent residual gives no Demi; errors propagate. A schema used",
1639
+ "as an explicit element contributes Size normally, even though its own Demi is nil.",
1640
+ "A present Demi has Size L+R and residual L−R. Its Count is the least positive",
1641
+ "representative of its stored parity: 2 for all/even and 1 for nil/odd. The same",
1642
+ "universal derivation therefore reconstructs its data value on repeated fourth",
1643
+ "observation, including present zero loads, without a special fourth-hash rule.",
1644
+ "A present Demi is an instance of the HC class in `hc/demi.hc` (011.20), and",
1645
+ "reads as text `Demi(phase,left,right)`. Applying a Demi to Y deposits Y's Size",
1646
+ "and flips the phase, so for a nonempty Figure host X, (X Y).#### is",
1647
+ "X.#### Y; for an empty host, start from the zero-load Demi in phase 2 instead,",
1648
+ "because [].#### is nil. Scaling is the method `scale_`, the shadow of Star:",
1649
+ "(X * Y).#### is X.####.scale_ (Y.##) for a nonempty host. Count is a terminal",
1650
+ "quantity: positive Counts agree with pure Figures of that terminal Size, but 0",
1651
+ "has Size 0 while [] has Size 1. Mixed values may have present zero-load Demis,",
1652
+ "including [0].####.",
1653
+ "```",
1654
+ "; [[].####, 0.####, “” “hello”.####, <2,3,5>.####]",
1655
+ "# [(), (), “Demi((),3,2)”, ()]",
1656
+ "; [(10 - 5).#### = 5.####, (0 - 5).#### = 5.####, (5.0).#### = 5.####, “hello”.#### = 5.####]",
1657
+ "# [<>, <>, <>, <>]",
1658
+ "; [<>.#, <>.##, <>.###, ().##]",
1659
+ "# [0, 1, 0, 1]",
1660
+ "; [1, 2, 3, 7] & {“” _.####}",
1661
+ "# [“Demi((),1,0)”, “Demi(<>,1,1)”, “Demi((),2,1)”, “Demi((),4,3)”]",
1662
+ "; [[0], [“hello”], [<2,3,5>,2], {5 + 3}] & {“” _.####}",
1663
+ "# [“Demi((),0,0)”, “Demi((),5,0)”, “Demi(<>,3,2)”, “Demi((),8,1)”]",
1664
+ "; [“” ([[],[]].#### 3), “” (7.####.scale_ 2), ([[],[]] 3).#### = ([[],[]].#### 3)]",
1665
+ "# [“Demi((),4,1)”, “Demi((),8,6)”, <>]",
1666
+ "",
1667
+ "```",
1362
1668
  "Importing skips the examples and ends on a native true value.",
1363
1669
  "```",
1364
1670
  "[] = []",
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The Demi class, loaded from HC for the fourth hash.
3
+ *
4
+ * `.####` answers a Demi, and a Demi is an HC class, `Demi` in `hc/demi.hc`,
5
+ * not a native one (occurrence/figure 011.20). The frames package derives the
6
+ * phase and loads natively but cannot run HC, so this module installs the
7
+ * constructor it calls (`installDemiConstructor`).
8
+ *
9
+ * The class is read from the compiled-in bundle, not through a resource root,
10
+ * so `.####` works in a bare `evaluate`, which has no root and imports nothing.
11
+ * The file is evaluated the first time a Demi is constructed, once per
12
+ * process, the way an import evaluates a testdoc: its example lines are
13
+ * dropped and the first failure fails the whole. It runs in a namespace of its
14
+ * own, with no host bindings and no root, so it can read nothing but the
15
+ * global operators, and nothing a program declares can reach it. Its outcome
16
+ * is kept, failure included, so it is never evaluated twice. A Demi requested
17
+ * while the file is still loading is `$!.demi-prologue-reentrant`, because
18
+ * the class cannot be defined by itself.
19
+ *
20
+ * What stays native is only what HC cannot say: reading `#`, `##` and `###`
21
+ * in a fixed order with their absence and error rules, and checking that the
22
+ * loads are whole. Everything a Demi does is in the HC source.
23
+ *
24
+ * @module
25
+ */
26
+ import { EvaluationScope, Frame, FrameArray, FrameExpr, installDemiConstructor, } from "../frames.js";
27
+ import { HC_SOURCES } from "../bundle/hc-sources.js";
28
+ import { evaluateSourceText } from "./resource-import.js";
29
+ /** The bundled file that defines the class. */
30
+ export const DEMI_SOURCE = "hc/demi.hc";
31
+ /** The name the file declares the constructor under. */
32
+ export const DEMI_CLASS = "Demi";
33
+ let loaded;
34
+ let loading = false;
35
+ /**
36
+ * Evaluates class source in a namespace of its own, with no host bindings and
37
+ * no root, answering its `Demi` or the failure. Uncached: `demiClass` keeps
38
+ * the one result the process uses.
39
+ *
40
+ * @param source The source text, or undefined when the bundle lacks it.
41
+ * @returns The constructor, or an error.
42
+ */
43
+ export function loadDemiClass(source) {
44
+ if (source === undefined) {
45
+ return Frame.error(`$!.demi-prologue-missing ${DEMI_SOURCE}`);
46
+ }
47
+ const namespace = new FrameArray([]);
48
+ const result = evaluateSourceText(source, EvaluationScope.root(namespace));
49
+ if (result.isFailedResult() || result.observationError())
50
+ return result;
51
+ const constructor = namespace.getOwn(DEMI_CLASS);
52
+ return constructor.is.missing
53
+ ? Frame.error(`$!.demi-prologue-missing ${DEMI_CLASS}`)
54
+ : constructor;
55
+ }
56
+ /**
57
+ * The `Demi` constructor closure, evaluated from the bundle on first use.
58
+ *
59
+ * @returns The constructor, or the error that loading it answered.
60
+ */
61
+ export function demiClass() {
62
+ if (loaded)
63
+ return loaded;
64
+ if (loading)
65
+ return Frame.error("$!.demi-prologue-reentrant");
66
+ loading = true;
67
+ try {
68
+ loaded = loadDemiClass(HC_SOURCES.get(DEMI_SOURCE));
69
+ }
70
+ finally {
71
+ loading = false;
72
+ }
73
+ return loaded;
74
+ }
75
+ /**
76
+ * Constructs a Demi with the HC class: `Demi [phase, left, right]`.
77
+ *
78
+ * @param phase 2 when even, 1 when odd.
79
+ * @param left The left load.
80
+ * @param right The right load.
81
+ * @returns The new instance, or the class's failure.
82
+ */
83
+ export function constructDemi(phase, left, right) {
84
+ const constructor = demiClass();
85
+ if (constructor.isFailedResult() || constructor.observationError()) {
86
+ return constructor;
87
+ }
88
+ const state = new FrameArray([phase, left, right]);
89
+ return FrameExpr.answeredValue(constructor.call(state)).referent();
90
+ }
91
+ installDemiConstructor(constructDemi);
@@ -1,4 +1,6 @@
1
1
  import { Frame, FrameCount, FrameString, FrameSymbol, } from "../frames.js";
2
+ // Installs the Demi class that `.####` constructs (011.20).
3
+ import "./demi-prologue.js";
2
4
  import { EvalPipe, makeSourcePipe } from "./eval-pipe.js";
3
5
  import { evaluateResourceSource } from "./resource-import.js";
4
6
  import { sigilizer } from "./sigilizer.js";
@@ -1,4 +1,4 @@
1
- import { Frame, FrameExpr, FrameGroup, FrameLazy, FrameResource, FrameSymbol, hasCharacterContent, } from "../frames.js";
1
+ import { Frame, FrameExpr, FrameGroup, FrameLazy, FrameResource, FrameString, FrameSymbol, hasCharacterContent, } from "../frames.js";
2
2
  import { EvalPipe, makeSourcePipe } from "./eval-pipe.js";
3
3
  import { LexPipe } from "./lex-pipe.js";
4
4
  import { ParsePipe } from "./parse-pipe.js";
@@ -120,6 +120,22 @@ function evaluateResourceSourceWithChain(resource, scope, activeImports) {
120
120
  ...activeImports,
121
121
  { hostNamespace: scope.hostNamespace, resource: spelling },
122
122
  ];
123
+ return evaluateElements(resource.elements(), scope, nextActiveImports);
124
+ }
125
+ /**
126
+ * Evaluates HC source text as an import would: example lines dropped, the first
127
+ * failed form failing the whole, and the last answer returned. Declarations
128
+ * land in the scope's write target. Used for source the program carries rather
129
+ * than reads, such as the Demi class (`demi-prologue.ts`).
130
+ *
131
+ * @param source The source text.
132
+ * @param scope The scope it evaluates in.
133
+ * @returns The last answer, or the first failure.
134
+ */
135
+ export function evaluateSourceText(source, scope) {
136
+ return evaluateElements([new FrameString(source)], scope, []);
137
+ }
138
+ function evaluateElements(elements, scope, nextActiveImports) {
123
139
  const progress = new ImportProgress();
124
140
  const lexer = makeSourcePipe(EvalPipe.scoped(progress, scope), {
125
141
  importSource: (nestedResource, nestedScope) => evaluateResourceSourceWithChain(nestedResource, nestedScope, nextActiveImports),
@@ -134,7 +150,6 @@ function evaluateResourceSourceWithChain(resource, scope, activeImports) {
134
150
  return progress.firstFailure;
135
151
  };
136
152
  const examples = new ExampleFilter();
137
- const elements = resource.elements();
138
153
  for (const element of elements) {
139
154
  if (element.isFailedResult())
140
155
  return element;
@@ -103,7 +103,10 @@ export class BoundMethod extends Frame {
103
103
  // the lookup order, and a shared body's captured scope is whichever instance
104
104
  // was built last, so a method would read another instance's fields.
105
105
  const result = this.method.call(argument, Frame.nil, state);
106
- if (result.isFailedResult())
106
+ // A mutating method answers its receiver, unless it answered an error. A
107
+ // diagnostic note such as `$!.name-missing` is one too, though it is not
108
+ // flagged, so it is answered rather than replaced by the receiver (011.20).
109
+ if (result.isFailedResult() || result.referent().isError())
107
110
  return result;
108
111
  return this.isMutating() ? state.receiver : result;
109
112
  }
@@ -0,0 +1,64 @@
1
+ import { Frame } from "./frame.js";
2
+ import { FrameCount } from "./frame-count.js";
3
+ import { FrameInt } from "./frame-int.js";
4
+ let construct;
5
+ /**
6
+ * Installs what `.####` answers a present Demi with. The Demi is an HC class,
7
+ * `Demi` in `hc/demi.hc`, so the frames package, which cannot run HC, takes
8
+ * its constructor from the evaluator (`lib/execute/demi-prologue.ts`).
9
+ *
10
+ * @param constructor The constructor, called once per present observation.
11
+ */
12
+ export function installDemiConstructor(constructor) {
13
+ construct = constructor;
14
+ }
15
+ /**
16
+ * The fourth hash, `.####`, derived only from the existing observers: Count n,
17
+ * Size s and residual r give the loads (s+r)/2 and (s−r)/2, and n's parity
18
+ * the phase. It never folds, executes or caches the source, and reads each
19
+ * observer at most once.
20
+ *
21
+ * In order: a failure of the source or of any observer is answered as it is;
22
+ * no Count (nil) or Count zero is nil; nil residual is nil; observations that
23
+ * are not exact Counts and an integer are `$!.demi-observations`; and loads
24
+ * that are negative or not whole are `$!.demi-coherence`. Only then is the
25
+ * Demi constructed (011.18b–m).
26
+ *
27
+ * @param source The observed Frame.
28
+ * @returns A Demi, nil, or an error.
29
+ */
30
+ export function observeDemi(source) {
31
+ const failure = source.observationError();
32
+ if (failure)
33
+ return failure;
34
+ const n = source.sizeFor(Frame.kCOUNT);
35
+ if (n.observationError())
36
+ return n;
37
+ if (n === Frame.nil)
38
+ return Frame.nil; // no Count, no Demi (011.18k)
39
+ if (!(n instanceof FrameCount) || typeof n.data !== "bigint" || n.data < 0n) {
40
+ return Frame.error("$!.demi-count");
41
+ }
42
+ if (n.data === 0n)
43
+ return Frame.nil;
44
+ const s = source.sizeFor(Frame.kLEAVES);
45
+ if (s.observationError())
46
+ return s;
47
+ const r = source.sizeFor(Frame.kRESIDUAL);
48
+ if (r.observationError())
49
+ return r;
50
+ if (r === Frame.nil)
51
+ return Frame.nil;
52
+ if (!(s instanceof FrameCount) || !(r instanceof FrameInt) ||
53
+ typeof s.data !== "bigint" || typeof r.data !== "bigint" || s.data < 0n)
54
+ return Frame.error("$!.demi-observations");
55
+ const sum = s.data + r.data;
56
+ const difference = s.data - r.data;
57
+ if (sum < 0n || difference < 0n || sum % 2n !== 0n || difference % 2n !== 0n) {
58
+ return Frame.error("$!.demi-coherence");
59
+ }
60
+ if (!construct)
61
+ return Frame.error("$!.demi-unavailable");
62
+ return construct(new FrameCount(n.data % 2n === 0n ? 2n : 1n), new FrameCount(sum / 2n), new FrameCount(difference / 2n));
63
+ }
64
+ Frame.demi = observeDemi;
@@ -135,8 +135,8 @@ export class FrameArray extends FrameList {
135
135
  return true;
136
136
  }
137
137
  /**
138
- * An evaluated array exposes ordered data for residual; properties and
139
- * declared parents are excluded.
138
+ * An array exposes its ordered stored contents for residual; properties
139
+ * and declared parents are excluded. Source forms are not executed.
140
140
  */
141
141
  supportsResidual() {
142
142
  return true;
@@ -265,6 +265,86 @@ export class FrameArray extends FrameList {
265
265
  return this;
266
266
  return new BoundMethod(method, this, false, methodEffect(FrameArray.TEXT_KEY)).call(Frame.nil);
267
267
  }
268
+ /**
269
+ * An aggregate observes its elements, so a class that keeps its state in
270
+ * fields observes as its empty element list: Count 0, Size 1, residual 0.
271
+ * One that declares a method named `#`, `##` or `###`, on itself or a
272
+ * declared parent, answers that method's result instead, the way one that
273
+ * declares `apply` decides its own application (011.20). Nothing declares
274
+ * one by default, so every other aggregate observes exactly as before.
275
+ *
276
+ * The answer must be the kind the operator answers: a Count for `#` and
277
+ * `##`, an exact integer for `###`. Anything else is
278
+ * `$!.declared-observation`, an error the method answered is answered as it
279
+ * is, and a method that observes its own receiver the same way, directly
280
+ * or through other declared observations, is `$!.cyclic-observation`.
281
+ * Nesting deeper than `OBSERVATION_DEPTH_LIMIT`, as a method that observes
282
+ * a fresh instance of its own class does, is `$!.observation-depth`.
283
+ *
284
+ * The method runs immutably, so it cannot write its receiver. It is still
285
+ * code the class wrote: it runs on every observation, with no caching, and
286
+ * may act on anything else it can reach, a mutable handle in scope
287
+ * included. Observation is pure only for classes that keep it pure.
288
+ *
289
+ * @param key A size operator.
290
+ * @returns The declared answer, or undefined when none is declared.
291
+ */
292
+ declaredObservation(key) {
293
+ if (!FrameArray.OBSERVATION_KEYS.includes(key))
294
+ return undefined;
295
+ const method = this.declaredMethod(key);
296
+ if (!method)
297
+ return undefined;
298
+ const active = FrameArray.observing.get(this) ?? new Set();
299
+ if (active.has(key))
300
+ return Frame.error(`$!.cyclic-observation .${key}`);
301
+ if (FrameArray.observationDepth >= FrameArray.OBSERVATION_DEPTH_LIMIT) {
302
+ return Frame.error(`$!.observation-depth .${key}`);
303
+ }
304
+ active.add(key);
305
+ FrameArray.observing.set(this, active);
306
+ FrameArray.observationDepth++;
307
+ let answer;
308
+ try {
309
+ answer = new BoundMethod(method, this, false, methodEffect(key)).call(Frame.nil).referent();
310
+ }
311
+ finally {
312
+ FrameArray.observationDepth--;
313
+ active.delete(key);
314
+ if (active.size === 0)
315
+ FrameArray.observing.delete(this);
316
+ }
317
+ const failure = answer.observationError();
318
+ if (failure)
319
+ return failure;
320
+ const data = answer.data;
321
+ const valid = key === Frame.kRESIDUAL
322
+ ? answer.className() === "FrameInt" || answer instanceof FrameCount
323
+ : answer instanceof FrameCount;
324
+ return valid && typeof data === "bigint"
325
+ ? answer
326
+ : Frame.error(`$!.declared-observation .${key}`);
327
+ }
328
+ /** A declared Count, Size or residual first; the list's own rule otherwise. */
329
+ sizeFor(key) {
330
+ const failure = this.observationError();
331
+ if (failure && Frame.SIZE_OPERATORS.includes(key))
332
+ return failure;
333
+ return this.declaredObservation(key) ?? super.sizeFor(key);
334
+ }
335
+ /**
336
+ * A declared Size is also what this aggregate contributes inside another,
337
+ * so `[d, d].##` adds the declared Sizes rather than one terminal for each.
338
+ */
339
+ nativeSize(path) {
340
+ const failure = this.observationError();
341
+ if (failure)
342
+ return failure;
343
+ const declared = this.declaredObservation(Frame.kLEAVES);
344
+ if (declared === undefined)
345
+ return super.nativeSize(path);
346
+ return declared instanceof FrameCount ? declared.data : declared;
347
+ }
268
348
  /**
269
349
  * A method declared under `key` on this aggregate or its declared parents.
270
350
  *
@@ -382,3 +462,43 @@ Object.defineProperty(FrameArray, "TEXT_KEY", {
382
462
  writable: true,
383
463
  value: "toText"
384
464
  });
465
+ /**
466
+ * The size operators an aggregate may declare its own answer to (011.20):
467
+ * Count, Size and residual. `.####` is not among them, because it is always
468
+ * derived from these three, so a class that declares them gets it for free.
469
+ */
470
+ Object.defineProperty(FrameArray, "OBSERVATION_KEYS", {
471
+ enumerable: true,
472
+ configurable: true,
473
+ writable: true,
474
+ value: [
475
+ Frame.kCOUNT,
476
+ Frame.kLEAVES,
477
+ Frame.kRESIDUAL,
478
+ ]
479
+ });
480
+ /** Declared observations in progress, so one that reads itself fails. */
481
+ Object.defineProperty(FrameArray, "observing", {
482
+ enumerable: true,
483
+ configurable: true,
484
+ writable: true,
485
+ value: new Map()
486
+ });
487
+ /**
488
+ * How deeply declared observations may nest. A cycle through the same
489
+ * receivers is caught exactly; one that builds a fresh receiver each step
490
+ * is not, so nesting is bounded too, far above any real class's need.
491
+ */
492
+ Object.defineProperty(FrameArray, "OBSERVATION_DEPTH_LIMIT", {
493
+ enumerable: true,
494
+ configurable: true,
495
+ writable: true,
496
+ value: 32
497
+ });
498
+ /** Declared observations now running, across every receiver. */
499
+ Object.defineProperty(FrameArray, "observationDepth", {
500
+ enumerable: true,
501
+ configurable: true,
502
+ writable: true,
503
+ value: 0
504
+ });
@@ -4,6 +4,16 @@ export class FrameAtom extends Frame {
4
4
  constructor(meta = NilContext) {
5
5
  super(meta);
6
6
  }
7
+ /**
8
+ * A void atom, such as a comment, keeps an explicit Count zero; only nil
9
+ * itself has no Count (011.18k).
10
+ */
11
+ sizeFor(key) {
12
+ if (key === Frame.kCOUNT && this.is.void) {
13
+ return this.observationError() ?? Frame.count(0n);
14
+ }
15
+ return super.sizeFor(key);
16
+ }
7
17
  string_prefix() {
8
18
  return "";
9
19
  }
@@ -32,13 +32,18 @@ export class FrameCount extends FrameInt {
32
32
  }
33
33
  }
34
34
  /**
35
- * A count is its own size, so `.#` and `.##` both answer it (#411). A count
36
- * is not a Figure, so `.###` answers nil, as for any atom (010.04). The
37
- * spelling is the literal `Frame.kRESIDUAL`, since this module imports
38
- * `Frame` as a type only.
35
+ * A count is its own immediate count and Size (#411). Its residual, Count
36
+ * parity n mod 2, comes from the base Frame rule (011.18k, 011.18m).
37
+ * Unknown keys must not inherit the old accidental Count fallback.
39
38
  */
40
39
  sizeFor(key) {
41
- return key === "###" ? super.sizeFor(key) : this;
40
+ switch (key) {
41
+ case Frame.kCOUNT:
42
+ case Frame.kLEAVES:
43
+ return this;
44
+ default:
45
+ return super.sizeFor(key);
46
+ }
42
47
  }
43
48
  promoteOne() {
44
49
  return new FrameInt(this.data);
@@ -112,11 +112,14 @@ export class FrameExpr extends FrameList {
112
112
  const value = item.in(resumedScope(item, scope));
113
113
  if (value.is.error === true)
114
114
  return value;
115
+ if (index === 0 && value.isSymbol() && value.is.address &&
116
+ Frame.SIZE_OPERATORS.includes(value.spelling()))
117
+ return value;
115
118
  // An explicit nil receiver still has a Size. The initial nil accumulator
116
119
  // is not a receiver, so a leading .## remains an address (#411).
117
120
  if (index > 0 && sum.is.void && value.isSymbol() &&
118
121
  value.is.address &&
119
- [Frame.kLEAVES, Frame.kRESIDUAL].includes(value.spelling())) {
122
+ Frame.SIZE_OPERATORS.includes(value.spelling())) {
120
123
  return value.called_by(sum);
121
124
  }
122
125
  if (index > 0 && value.is.operator === true) {
@@ -216,3 +216,4 @@ Object.defineProperty(FrameInt, "NUMBER_CHAR", {
216
216
  writable: true,
217
217
  value: /\d/
218
218
  });
219
+ Frame.signed = (value) => new FrameInt(value);
@@ -98,9 +98,9 @@ export class FrameLazy extends FrameExpr {
98
98
  /**
99
99
  * `.#` counts the body's represented words (#429). `.##` sums their native
100
100
  * Sizes without execution or evaluation-site registration; an empty body
101
- * retains Size 1. A closure's words are executable syntax, so it has no
102
- * ordered data plane for `.###` and answers nil (010.08). The operator
103
- * reaches a closure as its argument and is answered before its body runs.
101
+ * retains Size 1. Residual alternates complete stored-word Sizes; Demi
102
+ * derives from those observations (011.18c). The operator reaches a closure
103
+ * as its argument and is answered before its body runs.
104
104
  */
105
105
  sizeOperator(argument) {
106
106
  if (argument instanceof FrameSymbol && argument.is.address === true &&
@@ -144,13 +144,22 @@ export class FrameList extends Frame {
144
144
  }
145
145
  /** Immediate count is unchanged; Size and residual share native child sizes. */
146
146
  sizeFor(key) {
147
+ const failure = this.observationError();
148
+ if (failure && Frame.SIZE_OPERATORS.includes(key))
149
+ return failure;
147
150
  if (key === Frame.kCOUNT) {
148
- return new FrameCount(BigInt(this.countedElements().length));
151
+ const elements = this.sizeElements();
152
+ return elements instanceof Frame
153
+ ? elements
154
+ : new FrameCount(BigInt(elements.length));
149
155
  }
150
156
  return key === Frame.kRESIDUAL ? this.residual() : super.sizeFor(key);
151
157
  }
152
158
  /** Empty aggregates retain one terminal; shared descendants count per occurrence. */
153
159
  nativeSize(path) {
160
+ const failure = this.observationError();
161
+ if (failure)
162
+ return failure;
154
163
  if (path.has(this))
155
164
  return Frame.error("$!.cyclic-aggregate .##");
156
165
  path.add(this);
@@ -173,21 +182,24 @@ export class FrameList extends Frame {
173
182
  path.delete(this);
174
183
  }
175
184
  }
176
- /** Only concrete ordered data hosts opt in, never executable/matcher syntax. */
185
+ /** Lists observe stored contents; schemas retain their separate semantics. */
177
186
  supportsResidual() {
178
- return false;
187
+ return true;
179
188
  }
180
189
  /** Alternate over immediate positions, using each child's complete Size. */
181
190
  residual() {
182
- if (!this.supportsResidual() || this.is.source === true)
191
+ if (!this.supportsResidual())
183
192
  return Frame.nil;
193
+ const elements = this.sizeElements();
194
+ if (elements instanceof Frame)
195
+ return elements;
184
196
  const path = new Set([this]);
185
197
  let signed = 0n;
186
198
  let positive = true;
187
- for (const element of this.countedElements()) {
199
+ for (const element of elements) {
188
200
  const size = element.referent().nativeSize(path);
189
201
  if (typeof size !== "bigint")
190
- return Frame.nil;
202
+ return size;
191
203
  signed += positive ? size : -size;
192
204
  positive = !positive;
193
205
  }
@@ -27,8 +27,8 @@ const recognizeName = (symbol, source = "") => {
27
27
  return { disposition: ScanDisposition.CompleteRedispatch };
28
28
  }
29
29
  // `#` begins a comment except where it spells a size operator, `.#`, `.##`
30
- // or `.###` (#411, 010.04), which nothing extends: `.foo#bar` still ends at
31
- // its `#`, and `.####` is `.###` before a comment.
30
+ // `.###` or `.####` (011.18). A fifth hash starts a comment;
31
+ // `.foo#bar` still ends at its first hash.
32
32
  if (Frame.SIZE_OPERATORS.includes(source + char)) {
33
33
  return { disposition: ScanDisposition.Consume };
34
34
  }
@@ -51,6 +51,14 @@ export class FrameNote extends FrameAtom {
51
51
  this.setLabel(data, source);
52
52
  this.id += this.data;
53
53
  }
54
+ /** A diagnostic failure is an error value, though not flagged as one. */
55
+ isError() {
56
+ return super.isError() || this.isDiagnosticFailure();
57
+ }
58
+ /** Observations preserve diagnostic failures as values. */
59
+ observationError() {
60
+ return this.isDiagnosticFailure() ? this : super.observationError();
61
+ }
54
62
  /** Diagnostic notes that represent failures, rather than test progress. */
55
63
  isDiagnosticFailure() {
56
64
  return ["!", "<>", ">", "-"].includes(this.data);
@@ -81,7 +81,16 @@ export function projectBigIntRatio(numerator, denominator) {
81
81
  }
82
82
  /** Shared rank-based numeric dispatch and unary/apply behavior. */
83
83
  export class FrameNumeric extends FrameAtom {
84
+ observationError() {
85
+ return super.observationError() ??
86
+ (this.rank === NUMERIC_RANK.number && !Number.isFinite(this.valueOf())
87
+ ? Frame.error("$!.nonquantifiable-size .##")
88
+ : undefined);
89
+ }
84
90
  nativeSize(path) {
91
+ const failure = this.observationError();
92
+ if (failure)
93
+ return failure;
85
94
  // Dimensional and dotted values have no implicit unit or magnitude.
86
95
  if (this.rank === null)
87
96
  return super.nativeSize(path);
@@ -62,6 +62,9 @@ export class FrameSchema extends FrameList {
62
62
  }
63
63
  return this;
64
64
  }
65
+ supportsResidual() {
66
+ return false;
67
+ }
65
68
  nativeSize() {
66
69
  // Empty enumeration means the total type, not an empty finite domain.
67
70
  // Inspect the installed matcher only; never traverse/compile candidates.
@@ -528,6 +528,9 @@ export class Frame extends MetaFrame {
528
528
  */
529
529
  call(argument, parameter = Frame.nil, _receiverState) {
530
530
  if (this.is.void) {
531
+ const key = Frame.quantityOperator(argument);
532
+ if (key)
533
+ return this.sizeFor(key);
531
534
  return Frame.isBooleanNegation(argument) ? Frame.all : argument;
532
535
  }
533
536
  return argument.called_by(this, parameter);
@@ -653,19 +656,60 @@ export class Frame extends MetaFrame {
653
656
  return this;
654
657
  }
655
658
  /**
656
- * What this frame answers for a size operator, `.#`, `.##` or `.###`
657
- * (#411). Size counts represented quantity; opaque atoms count once.
658
- * Immediate count and signed residual are partial, with kind-specific rules.
659
+ * Whether this value is itself an error: one flagged as such, or a
660
+ * diagnostic note such as `$!.name-missing`, which `FrameNote` answers for.
661
+ * Unlike `isFailedResult`, it never looks inside an aggregate, and unlike
662
+ * `observationError`, a non-finite number or a cycle is not one: those fail
663
+ * to be measured, not to be computed (011.20).
664
+ */
665
+ isError() {
666
+ return this.is.error === true;
667
+ }
668
+ /** A failure carried by this value, without executing or enumerating it. */
669
+ observationError() {
670
+ return this.is.error || this.is.cyclicReference ? this : undefined;
671
+ }
672
+ /**
673
+ * Native Count, Size, residual and derived Demi. Missing Count falls back to
674
+ * Size, and missing residual to Count parity; kinds with their own rules
675
+ * (lists, schemas, Demi, all) supply them explicitly (011.18k, 011.18m).
676
+ * Nil has no Count, so no residual or Demi.
659
677
  */
660
678
  sizeFor(key) {
661
- if (key !== Frame.kLEAVES)
679
+ if (!Frame.SIZE_OPERATORS.includes(key))
662
680
  return Frame.nil;
663
- const size = this.nativeSize(new Set());
664
- return typeof size === "bigint" ? Frame.count(size) : size;
681
+ const failure = this.observationError();
682
+ if (failure)
683
+ return failure;
684
+ // The internal lookup sentinel is never a value: observing it is the
685
+ // same failure HC reports for a missing name (011.18m).
686
+ if (this.is.missing)
687
+ return Frame.error("$!.name-missing");
688
+ switch (key) {
689
+ case Frame.kCOUNT:
690
+ if (this.is.void)
691
+ return Frame.nil; // nil has no Count (011.18k)
692
+ return this.sizeFor(Frame.kLEAVES);
693
+ case Frame.kLEAVES: {
694
+ const size = this.nativeSize(new Set());
695
+ return typeof size === "bigint" ? Frame.count(size) : size;
696
+ }
697
+ case Frame.kRESIDUAL: {
698
+ const n = this.sizeFor(Frame.kCOUNT);
699
+ if (n.observationError())
700
+ return n;
701
+ const data = n.data;
702
+ return typeof data === "bigint" ? Frame.signed(data % 2n) : Frame.nil;
703
+ }
704
+ case Frame.kDEMI:
705
+ return Frame.demi(this);
706
+ default:
707
+ return Frame.nil;
708
+ }
665
709
  }
666
710
  /** Nonnegative represented quantity; path tracks recursive containment only. */
667
711
  nativeSize(_path) {
668
- return this.is.cyclicReference ? this : 1n;
712
+ return this.observationError() ?? 1n;
669
713
  }
670
714
  /**
671
715
  * What integer repetition `n x` answers when this frame, x, has a rule of
@@ -953,7 +997,7 @@ export class Frame extends MetaFrame {
953
997
  return undefined;
954
998
  }
955
999
  const key = argument.spelling();
956
- return key === Frame.kLEAVES || key === Frame.kRESIDUAL ? key : undefined;
1000
+ return Frame.SIZE_OPERATORS.includes(key) ? key : undefined;
957
1001
  }
958
1002
  /**
959
1003
  * Negation is decided by the symbol's name, never by how it prints.
@@ -1006,9 +1050,9 @@ Object.defineProperty(Frame, "kLEAVES", {
1006
1050
  value: "##"
1007
1051
  });
1008
1052
  /**
1009
- * kRESIDUAL is the size operator `.###`, a Figure's signed alternating sum
1010
- * of its immediate elements' terminal counts, as a FrameInt (issue
1011
- * occurrence/figure 010.04).
1053
+ * kRESIDUAL is `.###`: a FrameInt alternating sum of immediate child native
1054
+ * Sizes on non-schema lists, or Count parity on any other Frame with a Count
1055
+ * (occurrence/figure 011.18k, 011.18m). Schemas and nil have nil residual.
1012
1056
  */
1013
1057
  Object.defineProperty(Frame, "kRESIDUAL", {
1014
1058
  enumerable: true,
@@ -1016,6 +1060,13 @@ Object.defineProperty(Frame, "kRESIDUAL", {
1016
1060
  writable: true,
1017
1061
  value: "###"
1018
1062
  });
1063
+ /** Derived nullable Demi, an instance of the HC class in `hc/demi.hc` (011.20). */
1064
+ Object.defineProperty(Frame, "kDEMI", {
1065
+ enumerable: true,
1066
+ configurable: true,
1067
+ writable: true,
1068
+ value: "####"
1069
+ });
1019
1070
  /**
1020
1071
  * The size operators, the only names spelled with `#` (#411). Each answers
1021
1072
  * for its receiver through `sizeFor`, never through name lookup.
@@ -1028,6 +1079,7 @@ Object.defineProperty(Frame, "SIZE_OPERATORS", {
1028
1079
  Frame.kCOUNT,
1029
1080
  Frame.kLEAVES,
1030
1081
  Frame.kRESIDUAL,
1082
+ Frame.kDEMI,
1031
1083
  ]
1032
1084
  });
1033
1085
  /**
@@ -1071,6 +1123,14 @@ Object.defineProperty(Frame, "all", {
1071
1123
  dataString() {
1072
1124
  return "<>";
1073
1125
  }
1126
+ sizeFor(key) {
1127
+ if (key === Frame.kCOUNT) {
1128
+ return this.observationError() ?? Frame.count(0n);
1129
+ }
1130
+ if (key === Frame.kRESIDUAL)
1131
+ return Frame.signed(0n); // 011.18k
1132
+ return super.sizeFor(key);
1133
+ }
1074
1134
  call(argument) {
1075
1135
  const key = Frame.quantityOperator(argument);
1076
1136
  if (key)
package/esm/lib/frames.js CHANGED
@@ -26,6 +26,7 @@ export { FrameScopeAnchor, } from "./frames/frame-scope-anchor.js";
26
26
  export { FrameNumeric, NUMERIC_RANK, } from "./frames/frame-numeric.js";
27
27
  export { FrameInt } from "./frames/frame-int.js";
28
28
  export { FrameCount } from "./frames/frame-count.js";
29
+ export { installDemiConstructor, observeDemi, } from "./frames/fourth-hash.js";
29
30
  export { FrameDecimal } from "./frames/frame-decimal.js";
30
31
  export { FrameSequence } from "./frames/frame-sequence.js";
31
32
  export { FrameTypedNumber } from "./frames/frame-typed-number.js";
@@ -3,17 +3,35 @@ import { Frame } from "../frames/frame.js";
3
3
  import { FrameNumeric } from "../frames/frame-numeric.js";
4
4
  import { FrameArray } from "../frames/frame-array.js";
5
5
  import { FrameCount } from "../frames/frame-count.js";
6
+ /** Applies a numeric operation, or answers nil for any other pair. */
6
7
  const numeric = (source, block, operation) => {
7
8
  return source instanceof FrameNumeric && block instanceof FrameNumeric
8
9
  ? operation(source, block)
9
10
  : Frame.nil;
10
11
  };
11
- export const Add = (source, block) => numeric(source, block, (left, right) => left.add(right));
12
- export const Subtract = (source, block) => numeric(source, block, (left, right) => left.subtract(right));
12
+ /**
13
+ * Arithmetic answers an operand that is already an error, left first, rather
14
+ * than nil, so a failed read such as `$!.name-missing` reaches whatever uses
15
+ * the result. As nil it vanished: a write of nil leaves a field unchanged, so a
16
+ * misread load looked like an update that never landed (011.20). Ordering
17
+ * still answers nil, because an error is truthy under `?`, and a comparison
18
+ * that answered one would take the branch.
19
+ */
20
+ const arithmetic = (source, block, operation) => failure(source) ?? failure(block) ?? numeric(source, block, operation);
21
+ /** An operand that is an error value (`Frame.isError`), unwrapped. */
22
+ const failure = (operand) => {
23
+ const value = operand.referent();
24
+ return value.isError() ? value : undefined;
25
+ };
26
+ export const Add = (source, block) => arithmetic(source, block, (left, right) => left.add(right));
27
+ export const Subtract = (source, block) => arithmetic(source, block, (left, right) => left.subtract(right));
13
28
  /** Star constructs a frame; numeric pairs retain the existing arithmetic ladder. */
14
29
  export const Multiply = (source, block) => {
15
30
  const left = source.referent();
16
31
  const right = block.referent();
32
+ const refused = failure(left) ?? failure(right);
33
+ if (refused)
34
+ return refused;
17
35
  if (left instanceof FrameNumeric && right instanceof FrameNumeric) {
18
36
  return left.multiply(right);
19
37
  }
@@ -23,9 +41,9 @@ export const Multiply = (source, block) => {
23
41
  return FrameArray.starCount(left, block);
24
42
  return Frame.error("$!.star-domain *");
25
43
  };
26
- export const Divide = (source, block) => numeric(source, block, (left, right) => left.divide(right));
27
- export const Modulo = (source, block) => numeric(source, block, (left, right) => left.modulo(right));
28
- export const Power = (source, block) => numeric(source, block, (left, right) => left.power(right));
44
+ export const Divide = (source, block) => arithmetic(source, block, (left, right) => left.divide(right));
45
+ export const Modulo = (source, block) => arithmetic(source, block, (left, right) => left.modulo(right));
46
+ export const Power = (source, block) => arithmetic(source, block, (left, right) => left.power(right));
29
47
  export const Equals = (source, block) => {
30
48
  return source.equals(block);
31
49
  };
@@ -1 +1 @@
1
- export const VERSION = "0.37.3";
1
+ export const VERSION = "0.38.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hclang",
3
- "version": "0.37.3",
3
+ "version": "0.38.0",
4
4
  "description": "Homoiconic C command-line interpreter and REPL",
5
5
  "keywords": [
6
6
  "language",