hclang 0.40.0 → 0.41.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.
@@ -4134,7 +4134,43 @@ export const HC_SOURCES = new Map([
4134
4134
  "; join-name (.middle “Q”)",
4135
4135
  "# $!invalid-argument-list (.middle “Q”, $!missing-required-argument .last;)",
4136
4136
  "```",
4137
- "The return type is usually inferred, but can be specified explicitly using a trailing `^^`.",
4137
+ "The return type is usually inferred, but can be specified explicitly using a",
4138
+ "trailing `^^`. The result a successful call exposes must conform to that schema,",
4139
+ "and a result that does not is refused rather than returned:",
4140
+ "```",
4141
+ "; .small (.x) ^ {x} ^^ <1, 2, 3>;",
4142
+ "; small (.x 2)",
4143
+ "# 2",
4144
+ "; small (.x 9)",
4145
+ "# $!.type-error <1, 2, 3> 9",
4146
+ "```",
4147
+ "A return contract checks only the exposed result; it neither freezes, copies,",
4148
+ "nor converts the underlying object, and a closure whose body already failed",
4149
+ "surfaces that failure rather than a contract complaint.",
4150
+ "",
4151
+ "",
4152
+ "#### Effect Boundaries",
4153
+ "",
4154
+ "Where `^` and `^^` describe one call, the arrow `->` describes a continuing",
4155
+ "relationship. In `A -> B` the callback `B` is registered on the value `A`",
4156
+ "manages, and a later committed mutation of that value, by any actor through any",
4157
+ "alias, is a new invocation of `B`. The arrow is an effect boundary, not a write",
4158
+ "permission: it answers `A` unchanged and never grants the right to write it.",
4159
+ "Here each committed write of the cell bumps a shared counter the callback holds,",
4160
+ "while the cell itself keeps the value that was written to it:",
4161
+ "```",
4162
+ "; .log_ [.count 0; .tick_ {@count (count + 1);}];",
4163
+ "; .cell_ [.v 1; .put_ {@v _;}];",
4164
+ "; cell_ -> {log_.tick_ ()};",
4165
+ "; cell_.put_ 7;",
4166
+ "; cell_.v",
4167
+ "# 7",
4168
+ "; log_.count",
4169
+ "# 1",
4170
+ "```",
4171
+ "A refused or uncommitted write triggers nothing, and a functional update on an",
4172
+ "immutable handle writes a copy the arrow never observed, so only a real",
4173
+ "committed mutation of the managed value is a new consequence.",
4138
4174
  "",
4139
4175
  "",
4140
4176
  "#### Type Values",
@@ -0,0 +1,92 @@
1
+ /** Subscribers registered on one managed value, in registration order. */
2
+ const subscribers = new WeakMap();
3
+ /** Managed values whose callbacks are currently running, to bound reentrancy. */
4
+ const firing = new WeakSet();
5
+ /** Committed nested mutations of a firing value, each owed one more round. */
6
+ const pending = new Map();
7
+ /** The most delivery rounds one outermost commit may cause (nested included). */
8
+ export const EFFECT_DELIVERY_LIMIT = 65_536;
9
+ /**
10
+ * The invoker is installed once by the runtime so this module need not import
11
+ * closure machinery (which would close an import cycle through `frame.ts`).
12
+ * Until it is installed, a registered callback is simply not called.
13
+ */
14
+ let invoke;
15
+ /** Installs the one callback-invocation strategy (called at startup). */
16
+ export function installEffectInvoker(invoker) {
17
+ invoke = invoker;
18
+ }
19
+ /**
20
+ * Registers `callback` as an effect-boundary observer of `managed`.
21
+ *
22
+ * Idempotent per (managed, callback) pair so re-declaring the same arrow does
23
+ * not multiply invocations. Returns the managed value so the arrow operator can
24
+ * answer it unchanged.
25
+ */
26
+ export function registerEffect(managed, callback) {
27
+ const existing = subscribers.get(managed);
28
+ if (!existing) {
29
+ subscribers.set(managed, [callback]);
30
+ return managed;
31
+ }
32
+ if (!existing.includes(callback))
33
+ existing.push(callback);
34
+ return managed;
35
+ }
36
+ /** Whether a value carries any effect-boundary subscribers. */
37
+ export function hasEffectSubscribers(managed) {
38
+ return subscribers.has(managed);
39
+ }
40
+ /**
41
+ * Whether `observer` itself is registered on `managed` by an `A -> B` arrow,
42
+ * so a committed mutation of `managed` invokes it. Another callback on the
43
+ * same value does not count (PR #475 review).
44
+ */
45
+ export function isEffectObserver(managed, observer) {
46
+ return subscribers.get(managed)?.includes(observer) ?? false;
47
+ }
48
+ /**
49
+ * Notifies a managed value's subscribers that it committed a mutation.
50
+ *
51
+ * The single seam called from the mutation commit points. It is a no-op for the
52
+ * overwhelming majority of frames, which carry no subscribers, so ordinary
53
+ * construction and mutation pay only a `WeakMap.has` check. A commit to a value
54
+ * already firing is deferred to a later round rather than dropped.
55
+ */
56
+ export function notifyEffect(managed) {
57
+ if (!subscribers.has(managed) || !invoke)
58
+ return;
59
+ if (firing.has(managed)) {
60
+ pending.set(managed, (pending.get(managed) ?? 0) + 1);
61
+ return;
62
+ }
63
+ firing.add(managed);
64
+ let thrown;
65
+ try {
66
+ let due = 1;
67
+ for (let rounds = 1; due > 0; rounds++) {
68
+ if (rounds > EFFECT_DELIVERY_LIMIT) {
69
+ throw new RangeError(`$!.effect-delivery-limit ${EFFECT_DELIVERY_LIMIT}`);
70
+ }
71
+ due--;
72
+ // Snapshot each round, so an arrow registered by a callback joins the
73
+ // next round rather than the one being delivered.
74
+ for (const callback of [...subscribers.get(managed)]) {
75
+ try {
76
+ invoke(callback, managed);
77
+ }
78
+ catch (error) {
79
+ thrown ??= { error };
80
+ }
81
+ }
82
+ due += pending.get(managed) ?? 0;
83
+ pending.delete(managed);
84
+ }
85
+ }
86
+ finally {
87
+ firing.delete(managed);
88
+ pending.delete(managed);
89
+ }
90
+ if (thrown)
91
+ throw thrown.error;
92
+ }
@@ -6,6 +6,7 @@ import { FrameSymbol } from "./frame-symbol.js";
6
6
  import { NilContext } from "./context.js";
7
7
  import { EvaluationScope } from "./evaluation-scope.js";
8
8
  import { renderSourceTerm } from "./frame-list.js";
9
+ import { isFrameMatcher } from "./frame-match.js";
9
10
  // Both maps describe per-evaluation bound copies. The parsed/shared closure is
10
11
  // never a key, so evaluating one template in two scopes cannot rebind either
11
12
  // result or mutate the template's lexical ancestry.
@@ -23,6 +24,16 @@ export class FrameLazy extends FrameExpr {
23
24
  writable: true,
24
25
  value: void 0
25
26
  });
27
+ // The optional `^^` output contract, complementary to the `^` input
28
+ // signature above. A declared return schema gates the body's result the way
29
+ // `signature` gates the argument, and nothing else: it is a type assertion
30
+ // on the exposed value, not a freeze, copy, conversion, or callback.
31
+ Object.defineProperty(this, "returnContract", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: void 0
36
+ });
26
37
  }
27
38
  bindSignature(signature) {
28
39
  if (signature instanceof FrameGroup) {
@@ -30,6 +41,38 @@ export class FrameLazy extends FrameExpr {
30
41
  }
31
42
  return this;
32
43
  }
44
+ /**
45
+ * Records the `^^` return contract. The schema is kept as written and only
46
+ * consulted after the body runs, so copying the closure template, which the
47
+ * per-evaluation `bind` above does, carries the contract to the bound copy.
48
+ */
49
+ bindReturn(returnContract) {
50
+ this.returnContract = returnContract;
51
+ return this;
52
+ }
53
+ /** The declared `^^` output schema, or undefined when none was bound. */
54
+ returnSchema() {
55
+ return this.returnContract;
56
+ }
57
+ /**
58
+ * Checks a completed body result against the declared `^^` contract. An
59
+ * undeclared closure keeps HC's implicit constructive behavior and returns
60
+ * the result unchanged. A result that is already a failure is propagated
61
+ * without a second complaint, since the body never produced a value to
62
+ * expose. Otherwise a non-conforming result is refused as a `$!.type-error`,
63
+ * naming the declared schema and the offending value.
64
+ */
65
+ checkReturn(result) {
66
+ const contract = this.returnContract;
67
+ if (!contract)
68
+ return result;
69
+ if (result.is.error)
70
+ return result;
71
+ if (isFrameMatcher(contract) && !contract.match(result).matched) {
72
+ return Frame.error(`$!.type-error ${contract.toString()} ${result.toString()}`);
73
+ }
74
+ return result;
75
+ }
33
76
  string_open() {
34
77
  return FrameLazy.LAZY_BEGIN;
35
78
  }
@@ -144,7 +187,8 @@ export class FrameLazy extends FrameExpr {
144
187
  return prepared;
145
188
  const enclosing = capturedScopes.get(this) ?? this.legacyCapture();
146
189
  const scope = EvaluationScope.call(prepared, parameter, this, enclosing, receiverState);
147
- return FrameExpr.evaluateBody(this.data, scope, this.is.sequence === true);
190
+ const result = FrameExpr.evaluateBody(this.data, scope, this.is.sequence === true);
191
+ return this.checkReturn(result);
148
192
  }
149
193
  legacyCapture() {
150
194
  return this.up && !this.up.is.missing
@@ -14,7 +14,7 @@ import { FrameCurry } from "../ops/frame-curry.js";
14
14
  import { isFrameMatcher } from "./frame-match.js";
15
15
  import { NilContext } from "./context.js";
16
16
  import { EvaluationScope } from "./evaluation-scope.js";
17
- import { completeAtEnd, includeOrReserve, TIME_DELIMITER, } from "./atom-syntax.js";
17
+ import { completeAtEnd, includeOrEnd, includeOrReserve, TIME_DELIMITER, } from "./atom-syntax.js";
18
18
  import { ScanDisposition, } from "../scan.js";
19
19
  /**
20
20
  * The echo a declaration answers, which is a declaration and not an element.
@@ -488,6 +488,15 @@ Object.defineProperty(FrameOperator, "SYNTAX", {
488
488
  SIGIL_STARTS: FrameOperator.SIGIL_STARTS,
489
489
  recognize: (symbol, source = "") => {
490
490
  const char = symbol.toString();
491
+ // `->` is one operator, the effect-boundary arrow (006.17 §3-4). The
492
+ // hyphen that opens it is an ordinary operator start; the `>` that would
493
+ // otherwise redispatch to schema syntax is swallowed here so `a -> b`
494
+ // lexes as subject, arrow, callback rather than `a -` then an
495
+ // unterminated `<...>`. Only a lone trailing `-` claims the `>`; a longer
496
+ // operator run ending in `-` keeps the old boundary.
497
+ if (char === ">" && source === "-") {
498
+ return includeOrEnd(true);
499
+ }
491
500
  // Comparison brackets belong to the schema syntax, not to an operator.
492
501
  if (char === "<" || char === ">") {
493
502
  return { disposition: ScanDisposition.CompleteRedispatch };
@@ -1,5 +1,6 @@
1
1
  import { NilContext } from "./context.js";
2
2
  import { renderNested } from "./stringify.js";
3
+ import { hasEffectSubscribers, notifyEffect } from "./effect-registry.js";
3
4
  /** Visibility levels for logical frame bindings. */
4
5
  export var Visibility;
5
6
  (function (Visibility) {
@@ -253,12 +254,24 @@ export class MetaFrame {
253
254
  }
254
255
  /**
255
256
  * set adds a new key-value pair to the current context.
257
+ *
258
+ * This is the single commit point for a named-property mutation, so it is
259
+ * where an `A -> B` effect boundary observes a *committed* change (006.17
260
+ * §3-4): after the write lands, any callback registered on this value is a
261
+ * new invocation. Firing is a no-op for the common case of a value with no
262
+ * subscribers (a `WeakMap.has` check), and is skipped for a write that does
263
+ * not change the stored value, so a re-assignment of the same frame is not a
264
+ * mutation.
256
265
  */
257
266
  set(key, value) {
258
267
  if (this.meta === NilContext) {
259
268
  this.meta = {};
260
269
  }
270
+ const previous = this.meta[key];
261
271
  this.meta[key] = value;
272
+ if (previous !== value && hasEffectSubscribers(this)) {
273
+ notifyEffect(this);
274
+ }
262
275
  return this;
263
276
  }
264
277
  /** Whether this frame carries an explicitly declared parent. */
@@ -1006,6 +1019,11 @@ export class Frame extends MetaFrame {
1006
1019
  replaced = true;
1007
1020
  }
1008
1021
  }
1022
+ // An element-plane commit is a mutation too; a copy-on-write install lands
1023
+ // on a fresh copy that carries no subscribers, so it never fires here.
1024
+ if (replaced && hasEffectSubscribers(this)) {
1025
+ notifyEffect(this);
1026
+ }
1009
1027
  return replaced;
1010
1028
  }
1011
1029
  static quantityOperator(argument) {
@@ -0,0 +1,46 @@
1
+ import { isEffectObserver } from "./effect-registry.js";
2
+ /** Builds a plan from an explicit value→partition-id map. */
3
+ export function partitionPlan(placement) {
4
+ const ids = new Map(placement);
5
+ return { partitionOf: (value) => ids.get(value) };
6
+ }
7
+ /** Whether two placements name different partitions (a proposed boundary). */
8
+ function crosses(a, b) {
9
+ // Unplaced values are local; a boundary exists only between two named,
10
+ // distinct partitions.
11
+ return a !== undefined && b !== undefined && a !== b;
12
+ }
13
+ /**
14
+ * Checks a partition plan: accepts local mutable dependencies and transactional
15
+ * dependencies anywhere, and rejects a cross-partition *mutable* dependency
16
+ * that lacks an explicit effect boundary on its managed value.
17
+ *
18
+ * `arrows` lets a static (pre-evaluation) caller declare the explicit
19
+ * `[managed, observer]` effect boundaries of a plan; when omitted, coverage is
20
+ * read from the live effect registry, so an `A -> C` that actually ran makes
21
+ * C's dependency on A legal, and nothing else.
22
+ */
23
+ export function checkPartitions(edges, plan, arrows) {
24
+ const isCovered = (managed, observer) => arrows
25
+ ? arrows.some(([a, c]) => a === managed && c === observer)
26
+ : isEffectObserver(managed, observer);
27
+ const errors = [];
28
+ for (const edge of edges) {
29
+ if (edge.kind !== "mutable")
30
+ continue; // transactional never needs a boundary
31
+ const from = plan.partitionOf(edge.observer);
32
+ const to = plan.partitionOf(edge.managed);
33
+ if (!crosses(from, to))
34
+ continue; // local mutable dependency is fine
35
+ if (isCovered(edge.managed, edge.observer))
36
+ continue; // its own arrow
37
+ errors.push({
38
+ managed: edge.managed,
39
+ observer: edge.observer,
40
+ fromPartition: from,
41
+ toPartition: to,
42
+ reason: "$!.partition-error cross-partition mutable dependency without an effect boundary",
43
+ });
44
+ }
45
+ return { ok: errors.length === 0, errors };
46
+ }
package/esm/lib/frames.js CHANGED
@@ -50,4 +50,6 @@ export { Frame, } from "./frames/frame.js";
50
50
  export { MetaFrame, Visibility } from "./frames/meta-frame.js";
51
51
  export { ScanDisposition, } from "./scan.js";
52
52
  export { contextEqual, contextString, NilContext, } from "./frames/context.js";
53
+ export { hasEffectSubscribers, installEffectInvoker, isEffectObserver, notifyEffect, registerEffect, } from "./frames/effect-registry.js";
54
+ export { checkPartitions, partitionPlan, } from "./frames/partition-check.js";
53
55
  Frame.globals = Ops;
@@ -3,6 +3,20 @@ import { Frame } from "../frames/frame.js";
3
3
  import { FrameLazy } from "../frames/frame-lazy.js";
4
4
  import { FrameLiteral } from "../frames/frame-symbol.js";
5
5
  import { isFrameMatcher } from "../frames/frame-match.js";
6
+ import { installEffectInvoker, registerEffect, } from "../frames/effect-registry.js";
7
+ // Install the one strategy the effect registry uses to invoke a registered
8
+ // callback. A callback is an ordinary closure, so a committed mutation calls it
9
+ // with the managed value as its argument — a *new invocation*, never an
10
+ // alteration of a value it returned earlier. Installed here, where FrameLazy is
11
+ // already imported, so `frame.ts` need not depend on closure machinery.
12
+ installEffectInvoker((callback, managed) => callback.call(managed, Frame.nil));
13
+ /** The closure a declaration echo now names, if it names one. */
14
+ const boundClosure = (source) => {
15
+ if (!(source instanceof FrameLiteral) || !source.binding)
16
+ return undefined;
17
+ const bound = source.binding.target.get(source.binding.key);
18
+ return bound instanceof FrameLazy ? bound : undefined;
19
+ };
6
20
  /** Test whether a value belongs to a first-class type or schema. */
7
21
  export const HasType = (source, type) => {
8
22
  if (type === Frame.all)
@@ -23,3 +37,45 @@ export const BindType = (source, body) => {
23
37
  }
24
38
  return source;
25
39
  };
40
+ /**
41
+ * Attach an output-type contract to a declared closure, the `^^` complement of
42
+ * the `^` input signature. The left operand is the declaration echo produced
43
+ * by `^` (or by the declaration itself), whose name now holds the closure; the
44
+ * right operand is the schema the closure's result must conform to. Binding a
45
+ * return contract neither freezes nor rewrites the closure beyond recording the
46
+ * schema it will check at call time, and the echo is returned unchanged so a
47
+ * `^^` can follow a `^` in one left-associative expression. A `^^` with no
48
+ * closure to bind, or a left operand that is not a live declaration, is left
49
+ * alone rather than erroring, matching how `^` ignores a shape it cannot bind.
50
+ */
51
+ export const BindReturn = (source, returnType) => {
52
+ const closure = boundClosure(source);
53
+ if (closure) {
54
+ closure.bindReturn(returnType);
55
+ }
56
+ return source;
57
+ };
58
+ /**
59
+ * Register an effect boundary: `A -> B` (occurrence/history 006.17 §3-4).
60
+ *
61
+ * `A` is the managed value on the left; `B` is the callback on the right. This
62
+ * records `B` as an observer of `A`'s managed referent so that a *subsequent
63
+ * committed mutation of that value, by any actor through any alias*, is a new
64
+ * invocation of `B`. The arrow is an effect boundary, not a write-authority
65
+ * boundary: registration neither grants nor withholds write permission, does
66
+ * not freeze/copy/convert `A`, and is independent of whether any handle to `A`
67
+ * is mutable.
68
+ *
69
+ * The managed identity is `A`'s referent — the same frame a mutating write
70
+ * lands its `set`/`replaceMember` on — so a handle (`a_`) and the value it
71
+ * wraps register one and the same subscription. The arrow answers `A`
72
+ * unchanged, so it composes left-associatively like `^`/`^^` and leaves the
73
+ * one-shot/return spellings untouched. A left operand with no mutable identity
74
+ * (a bare scalar) registers against its own frame; nothing fires until that
75
+ * frame is actually mutated, which a scalar never is.
76
+ */
77
+ export const Arrow = (source, callback) => {
78
+ const managed = source.referent();
79
+ registerEffect(managed, callback);
80
+ return source;
81
+ };
package/esm/lib/ops.js CHANGED
@@ -3,7 +3,7 @@ import { FrameOps } from "./ops/frame-ops.js";
3
3
  import { MapElements, MapMembers, ReduceElements, ReduceMembers, SpliceElements, } from "./ops/iterators.js";
4
4
  import { Add, Divide, Equals, GreaterThan, GreaterThanOrEqual, Identical, LessThan, LessThanOrEqual, Modulo, Multiply, Power, Subtract, TypeEquals, } from "./ops/math.js";
5
5
  import { IdenticalMember, Member, TypedMember } from "./ops/membership.js";
6
- import { BindType } from "./ops/type-operations.js";
6
+ import { Arrow, BindReturn, BindType } from "./ops/type-operations.js";
7
7
  export { FrameCurry } from "./ops/frame-curry.js";
8
8
  export const Ops = new FrameOps({
9
9
  "&": MapElements,
@@ -32,4 +32,6 @@ export const Ops = new FrameOps({
32
32
  "~~": TypedMember,
33
33
  "~~~": IdenticalMember,
34
34
  "^": BindType,
35
+ "^^": BindReturn,
36
+ "->": Arrow,
35
37
  });
@@ -1 +1 @@
1
- export const VERSION = "0.40.0";
1
+ export const VERSION = "0.41.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hclang",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "description": "Homoiconic C command-line interpreter and REPL",
5
5
  "keywords": [
6
6
  "language",