hclang 0.43.0 → 0.44.1

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.
@@ -94,6 +94,30 @@ export class BoundMethod extends Frame {
94
94
  isMutating() {
95
95
  return this.effect.mutating;
96
96
  }
97
+ /** The frame this method was bound to, before any functional-update copy. */
98
+ receiverFrame() {
99
+ return this.receiverTarget;
100
+ }
101
+ /** Whether the handle this method was reached through claims mutability. */
102
+ hasMutableReceiver() {
103
+ return this.mutable;
104
+ }
105
+ /** The shared closure this binding runs. */
106
+ methodBody() {
107
+ return this.method;
108
+ }
109
+ /**
110
+ * The scope a call would run the body in, with the receiver capability a
111
+ * call would select, without running the body (`access-footprint.ts`). The
112
+ * selection is the real one: a functional update's scope reads its instance
113
+ * copy as receiver, so a walk over it sees writes land on the copy.
114
+ */
115
+ scopeForCall(argument) {
116
+ const state = this.receiverStateForCall();
117
+ if (state instanceof Frame)
118
+ return state;
119
+ return this.method.scopeForCall(argument, Frame.nil, state);
120
+ }
97
121
  call(argument, _parameter = Frame.nil) {
98
122
  const state = this.receiverStateForCall();
99
123
  if (state instanceof Frame)
@@ -103,6 +127,20 @@ export class BoundMethod extends Frame {
103
127
  // the lookup order, and a shared body's captured scope is whichever instance
104
128
  // was built last, so a method would read another instance's fields.
105
129
  const result = this.method.call(argument, Frame.nil, state);
130
+ return this.answer(result, state);
131
+ }
132
+ /** `call`, one statement at a time (`FrameLazy.steps`). */
133
+ *steps(argument, _parameter = Frame.nil) {
134
+ const state = this.receiverStateForCall();
135
+ if (state instanceof Frame) {
136
+ yield state;
137
+ return state;
138
+ }
139
+ const result = yield* this.method.steps(argument, Frame.nil, state);
140
+ return this.answer(result, state);
141
+ }
142
+ /** What a call answers once the body has: the receiver, or the value. */
143
+ answer(result, state) {
106
144
  // A mutating method answers its receiver, unless it answered an error. A
107
145
  // diagnostic failure such as `$!.name-missing` carries the same flag.
108
146
  // Preserve referent checks for programmatic reference wrappers (011.20).
@@ -0,0 +1,118 @@
1
+ import { Frame } from "./frame.js";
2
+ import { FrameArray } from "./frame-array.js";
3
+ import { FrameCount } from "./frame-count.js";
4
+ import { FrameLazy } from "./frame-lazy.js";
5
+ import { FrameString } from "./frame-string.js";
6
+ import { BoundMethod } from "./bound-method.js";
7
+ import { dispatch, } from "./event-dispatch.js";
8
+ /**
9
+ * The dispatcher as a host-namespace value, so an HC program can hand its
10
+ * own closures to `dispatch` and observe what each policy does to them
11
+ * (occurrence/figure 015.24j: the VACT witness has to reach the dispatcher
12
+ * under test from the testdoc that constructs its state).
13
+ *
14
+ * A harness that installs `dispatchNamespace()` under `DISPATCH_KEY` in its
15
+ * host namespace gives HC source four callables:
16
+ *
17
+ * $$.dispatch.sequential [e₁, e₂, …]
18
+ * $$.dispatch.certified-sequential [e₁, e₂, …]
19
+ * $$.dispatch.interleave [e₁, e₂, …]
20
+ * $$.dispatch.footprint [e₁, e₂, …]
21
+ *
22
+ * Each `eᵢ` is a bound closure or bound method, called with nil, or a pair
23
+ * `[callable, argument]`. The answer is one aggregate: its elements are the
24
+ * events' results in program order, and its properties the schedule the
25
+ * policy chose, `trace` as `“i:n …”` (the nth statement of event i, in the
26
+ * order they ran), `waited` as each event's indexes waited for, and
27
+ * `escapes` as the count of shared frames each event wrote outside its
28
+ * potential footprint, which the guard keeps at zero under `footprint`. The
29
+ * HC state the events touch is the program's own, so the program reads the
30
+ * final state itself, with its own observer, after the dispatch answers.
31
+ *
32
+ * This is a bridge, not a language feature: the policies are host values
33
+ * reached through `$$`, which a bare name never searches, and nothing here
34
+ * changes how HC evaluates, and it grants no authority: every event is a
35
+ * closure the program already holds, run with the authority it already has.
36
+ * It is installed in every program the CLI runs (`cli/hc.ts`), in every
37
+ * `HCLang` session and so the playground (`lib/execute/hc-lang.ts`), and by
38
+ * the companion Deno test; a host that does not install it has no
39
+ * `dispatch`, and `$$.dispatch` answers `$!.name-missing` there.
40
+ *
41
+ * @module
42
+ */
43
+ /** The key the dispatch namespace is bound under in a host namespace. */
44
+ export const DISPATCH_KEY = "dispatch";
45
+ const POLICIES = [
46
+ "sequential",
47
+ "certified-sequential",
48
+ "interleave",
49
+ "footprint",
50
+ ];
51
+ /** One policy as a callable host value. */
52
+ class DispatchPolicyFrame extends Frame {
53
+ constructor(policy) {
54
+ super();
55
+ Object.defineProperty(this, "policy", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: policy
60
+ });
61
+ }
62
+ toString() {
63
+ return `$$.${DISPATCH_KEY}.${this.policy}`;
64
+ }
65
+ /** A host value is itself; evaluating it performs no dispatch. */
66
+ in() {
67
+ return this;
68
+ }
69
+ call(argument) {
70
+ const events = eventsOf(argument);
71
+ if (!Array.isArray(events))
72
+ return events;
73
+ return reportFrame(dispatch(events, this.policy));
74
+ }
75
+ }
76
+ /** The events an HC argument denotes, or the error that refuses it. */
77
+ function eventsOf(argument) {
78
+ const items = argument.referent();
79
+ if (!(items instanceof FrameArray)) {
80
+ return Frame.error(`$!.dispatch-events ${items.className()}`);
81
+ }
82
+ const events = [];
83
+ for (const [index, item] of items.asArray().entries()) {
84
+ const value = item.referent();
85
+ const label = String(index);
86
+ if (isCallable(value)) {
87
+ events.push({ label, target: value });
88
+ continue;
89
+ }
90
+ if (value instanceof FrameArray) {
91
+ const [target, argument] = value.asArray();
92
+ const callee = target?.referent();
93
+ if (callee && isCallable(callee)) {
94
+ events.push({ label, target: callee, argument: argument ?? Frame.nil });
95
+ continue;
96
+ }
97
+ }
98
+ return Frame.error(`$!.dispatch-event ${label} ${value.className()}`);
99
+ }
100
+ return events;
101
+ }
102
+ const isCallable = (frame) => frame instanceof FrameLazy || frame instanceof BoundMethod;
103
+ /** The report as one aggregate: results as elements, schedule as properties. */
104
+ function reportFrame(report) {
105
+ const result = new FrameArray(report.outcomes.map((o) => o.result));
106
+ result.set("trace", new FrameString(report.trace.join(" ")));
107
+ result.set("waited", new FrameArray(report.outcomes.map((o) => new FrameArray(o.waitedFor.map((label) => FrameCount.for(label))))));
108
+ result.set("escapes", new FrameArray(report.outcomes.map((o) => FrameCount.for(String(o.escapes.length)))));
109
+ return result;
110
+ }
111
+ /** A fresh namespace holding the three policies, for a host to install. */
112
+ export function dispatchNamespace() {
113
+ const namespace = new Frame();
114
+ for (const policy of POLICIES) {
115
+ namespace.set(policy, new DispatchPolicyFrame(policy));
116
+ }
117
+ return namespace;
118
+ }
@@ -1,3 +1,4 @@
1
+ import { guardAccess, noteWrite, UncertifiedAccess, } from "./reference-tracking.js";
1
2
  /** Subscribers registered on one managed value, in registration order. */
2
3
  const subscribers = new WeakMap();
3
4
  /** Managed values whose callbacks are currently running, to bound reentrancy. */
@@ -24,19 +25,34 @@ export function installEffectInvoker(invoker) {
24
25
  * answer it unchanged.
25
26
  */
26
27
  export function registerEffect(managed, callback) {
28
+ // Refused before the subscriber list changes, so a refusal registers nothing.
29
+ guardAccess(managed, "write");
27
30
  const existing = subscribers.get(managed);
28
31
  if (!existing) {
29
32
  subscribers.set(managed, [callback]);
33
+ noteWrite(managed);
30
34
  return managed;
31
35
  }
32
- if (!existing.includes(callback))
33
- existing.push(callback);
36
+ if (existing.includes(callback))
37
+ return managed;
38
+ existing.push(callback);
39
+ noteWrite(managed);
34
40
  return managed;
35
41
  }
36
42
  /** Whether a value carries any effect-boundary subscribers. */
37
43
  export function hasEffectSubscribers(managed) {
38
44
  return subscribers.has(managed);
39
45
  }
46
+ /**
47
+ * The callbacks a committed mutation of `managed` would invoke, in order.
48
+ * Read by the footprint walk (`access-footprint.ts`): a write to a managed
49
+ * value runs its callbacks, so their effects belong to the writer's event.
50
+ * The list can change only by a registration, which is a write of `managed`,
51
+ * so a certificate that writes `managed` cannot see it change while it runs.
52
+ */
53
+ export function effectSubscribersOf(managed) {
54
+ return subscribers.get(managed) ?? [];
55
+ }
40
56
  /**
41
57
  * Whether `observer` itself is registered on `managed` by an `A -> B` arrow,
42
58
  * so a committed mutation of `managed` invokes it. Another callback on the
@@ -76,6 +92,9 @@ export function notifyEffect(managed) {
76
92
  invoke(callback, managed);
77
93
  }
78
94
  catch (error) {
95
+ // A refusal ends the event here: no sibling runs after it.
96
+ if (error instanceof UncertifiedAccess)
97
+ throw error;
79
98
  thrown ??= { error };
80
99
  }
81
100
  }
@@ -0,0 +1,192 @@
1
+ import { Frame } from "./frame.js";
2
+ import { FrameLazy } from "./frame-lazy.js";
3
+ import { BoundMethod } from "./bound-method.js";
4
+ import { AccessRecord, UncertifiedAccess, versionOf, withAccessRecord, } from "./reference-tracking.js";
5
+ import { footprintsConflict, isOpaque, isState, potentialFootprint, } from "./access-footprint.js";
6
+ /**
7
+ * The guard an admitted event runs under: its certificate, the footprint
8
+ * admission rested on. An opaque event was serialized against everything, so
9
+ * nothing it does can interfere and nothing is refused.
10
+ */
11
+ function guardFor(certificate) {
12
+ if (isOpaque(certificate))
13
+ return () => true;
14
+ return (frame, access) => !isState(frame) ||
15
+ (access === "write" ? certificate.writes : certificate.reads).has(frame);
16
+ }
17
+ /** The inferred footprint, widened by the caller's declaration if any. */
18
+ function widen(inferred, declared) {
19
+ if (!declared)
20
+ return inferred;
21
+ return {
22
+ reads: new Set([...inferred.reads, ...declared.reads]),
23
+ writes: new Set([...inferred.writes, ...declared.writes]),
24
+ unresolved: [...inferred.unresolved, ...declared.unresolved],
25
+ };
26
+ }
27
+ /**
28
+ * The shared state frames `record` touched that `footprint` did not allow:
29
+ * writes outside its writes, or reads outside its reads. Shared means not
30
+ * created by the event; state means what the walk would count as state.
31
+ */
32
+ export function accessesOutside(record, footprint, access = "writes") {
33
+ const touched = access === "writes"
34
+ ? record.sharedWrites()
35
+ : record.sharedReads();
36
+ const allowed = access === "writes" ? footprint.writes : footprint.reads;
37
+ return touched.filter((frame) => isState(frame) && !allowed.has(frame));
38
+ }
39
+ /**
40
+ * Runs `events` under `policy` and reports what each did and in what order.
41
+ */
42
+ export function dispatch(events, policy = "footprint") {
43
+ const trace = [];
44
+ const infer = (event) => potentialFootprint(event.target, event.argument ?? Frame.nil);
45
+ const states = events.map((event) => {
46
+ const inferred = infer(event);
47
+ return {
48
+ event,
49
+ record: new AccessRecord(),
50
+ waitedFor: new Set(),
51
+ inferred,
52
+ potential: widen(inferred, event.declared),
53
+ steps: 0,
54
+ done: false,
55
+ result: Frame.nil,
56
+ };
57
+ });
58
+ // A waiting event's names may have been rebound by an event that finished
59
+ // since, so its footprint is read again from its code until it starts.
60
+ const refresh = (state) => {
61
+ if (state.generator)
62
+ return;
63
+ state.inferred = infer(state.event);
64
+ state.potential = widen(state.inferred, state.event.declared);
65
+ };
66
+ const serial = policy === "sequential" || policy === "certified-sequential";
67
+ const guarded = policy === "footprint" || policy === "certified-sequential";
68
+ const mayStart = (index) => {
69
+ if (policy === "interleave")
70
+ return true;
71
+ const state = states[index];
72
+ refresh(state);
73
+ for (let other = 0; other < states.length; other++) {
74
+ if (other === index)
75
+ continue;
76
+ const peer = states[other];
77
+ if (peer.done)
78
+ continue;
79
+ // A later event matters only once it is running.
80
+ if (other > index && !peer.generator)
81
+ continue;
82
+ // An earlier event that has not started holds back every later one:
83
+ // its footprint is read when it starts and may name what a later event
84
+ // would already have written.
85
+ const conflicts = serial || !peer.generator ||
86
+ footprintsConflict(state.potential, peer.potential);
87
+ if (conflicts) {
88
+ state.waitedFor.add(peer.event.label);
89
+ return false;
90
+ }
91
+ }
92
+ return true;
93
+ };
94
+ let remaining = states.length;
95
+ while (remaining > 0) {
96
+ let progressed = false;
97
+ for (let index = 0; index < states.length; index++) {
98
+ const state = states[index];
99
+ if (state.done)
100
+ continue;
101
+ if (!state.generator) {
102
+ if (!mayStart(index))
103
+ continue;
104
+ state.generator = stepsOf(state.event.target, state.event.argument ?? Frame.nil);
105
+ // The certificate is frozen with the footprint admission rested on.
106
+ if (guarded)
107
+ state.record.guard = guardFor(state.potential);
108
+ }
109
+ const generator = state.generator;
110
+ progressed = true;
111
+ let step;
112
+ try {
113
+ step = withAccessRecord(state.record, () => generator.next());
114
+ }
115
+ catch (error) {
116
+ // Only this event's own guard ends it; a refusal by an enclosing
117
+ // event's guard belongs to that event's dispatcher.
118
+ if (!(error instanceof UncertifiedAccess) || error.record !== state.record)
119
+ throw error;
120
+ // Refused before the access happened: the event ends here, at the
121
+ // statement it was in, with nothing of that access committed.
122
+ state.refused = { frame: error.frame, access: error.access };
123
+ step = {
124
+ done: true,
125
+ value: Frame.error(`$!.uncertified-${error.access}`),
126
+ };
127
+ }
128
+ if (step.done) {
129
+ state.done = true;
130
+ state.result = step.value;
131
+ remaining--;
132
+ }
133
+ else {
134
+ state.steps++;
135
+ trace.push(`${state.event.label}:${state.steps}`);
136
+ }
137
+ // A serial policy runs each event to completion before looking further.
138
+ if (serial && !state.done)
139
+ index--;
140
+ }
141
+ if (!progressed) {
142
+ throw new Error("$!.dispatch-stalled: no event could start");
143
+ }
144
+ }
145
+ return {
146
+ policy,
147
+ trace,
148
+ outcomes: states.map((state) => {
149
+ // An opaque event claimed nothing, so nothing it did escapes a claim.
150
+ const opaque = isOpaque(state.potential);
151
+ const declared = state.event.declared;
152
+ return {
153
+ label: state.event.label,
154
+ result: state.result,
155
+ steps: state.steps,
156
+ inferred: state.inferred,
157
+ potential: state.potential,
158
+ actual: state.record,
159
+ escapes: opaque ? [] : accessesOutside(state.record, state.potential),
160
+ readEscapes: opaque
161
+ ? []
162
+ : accessesOutside(state.record, state.potential, "reads"),
163
+ undeclared: declared && !isOpaque(declared)
164
+ ? accessesOutside(state.record, declared)
165
+ : [],
166
+ waitedFor: [...state.waitedFor],
167
+ refused: state.refused,
168
+ };
169
+ }),
170
+ };
171
+ }
172
+ /** The statement steps of calling `target`; a callable without a body is one. */
173
+ export function stepsOf(target, argument = Frame.nil) {
174
+ if (target instanceof BoundMethod)
175
+ return target.steps(argument);
176
+ if (target instanceof FrameLazy)
177
+ return target.steps(argument);
178
+ return (function* () {
179
+ const result = target.call(argument, Frame.nil);
180
+ yield result;
181
+ return result;
182
+ })();
183
+ }
184
+ /** The version of `frame` an outcome read, or undefined if it never did. */
185
+ export function versionRead(outcome, frame) {
186
+ return outcome.actual.reads.get(frame);
187
+ }
188
+ /** The version of `frame` an outcome's last write produced, if it wrote it. */
189
+ export function versionWritten(outcome, frame) {
190
+ return outcome.actual.writes.get(frame);
191
+ }
192
+ export { versionOf };
@@ -12,21 +12,42 @@ let construct;
12
12
  export function installDemiConstructor(constructor) {
13
13
  construct = constructor;
14
14
  }
15
- /** The stored fields a Demi instance is reconstructed from, in order. */
16
- const DEMI_STATE = ["count", "left", "right"];
15
+ let recognizeRouter;
17
16
  /**
18
- * A stored field read as an exact nonnegative Count, or undefined.
17
+ * Installs how `.####` recognizes a channel router (007.27).
19
18
  *
20
- * Only the instance's own field is read (`get_here`), never a declared parent
21
- * or a method, so nothing runs.
19
+ * @param recognizer Answers a channel router's channels, or undefined.
22
20
  */
23
- function storedCount(source, key) {
24
- const value = source.get_here(key).referent();
21
+ export function installRouterRecognizer(recognizer) {
22
+ recognizeRouter = recognizer;
23
+ }
24
+ /** A Frame read as an exact nonnegative Count, or undefined. */
25
+ function exactCount(frame) {
26
+ const value = frame.referent();
25
27
  return value instanceof FrameCount && typeof value.data === "bigint" &&
26
28
  value.data >= 0n
27
29
  ? value
28
30
  : undefined;
29
31
  }
32
+ /**
33
+ * The stored loads of a Demi instance: its own `loads` field, a nonempty list
34
+ * whose elements are all exact Counts, or undefined.
35
+ *
36
+ * Only the instance's own field is read (`get_here`), never a declared parent
37
+ * or a method, and the list's elements are read as stored, so nothing runs.
38
+ */
39
+ function storedLoads(source) {
40
+ const value = source.get_here("loads").referent();
41
+ if (!value.ownsIdentity())
42
+ return undefined;
43
+ const elements = value.elements();
44
+ if (elements.length === 0)
45
+ return undefined;
46
+ const loads = elements.map(exactCount);
47
+ return loads.every((load) => load !== undefined)
48
+ ? loads
49
+ : undefined;
50
+ }
30
51
  /**
31
52
  * The intrinsic Demi path (007.25e). A constructed Demi is the one Frame whose
32
53
  * fourth hash the three observers cannot decide: `Demi [0, 0, 0]` reads 0, 0,
@@ -34,10 +55,12 @@ function storedCount(source, key) {
34
55
  * class declare its own `.####`, the fourth hash recognizes an instance of the
35
56
  * shipped class itself, and nothing else.
36
57
  *
37
- * A source is a Demi exactly when it has stored Counts `count`, `left` and
38
- * `right`, and it is `==` (same value and same type at every node, fields and
39
- * methods included) to the Demi the shipped constructor builds from those
40
- * three Counts. The answer is then that fresh reconstruction, never the source
58
+ * A source is a Demi exactly when it has a stored Count `count` and a stored
59
+ * nonempty list of Counts `loads`, and it is `==` (same value and same type at
60
+ * every node, fields and methods included) to the Demi the shipped constructor
61
+ * builds from them. A binary Demi stores `left` and `right` too, and the
62
+ * comparison covers them. The answer is then that fresh reconstruction, of
63
+ * the source's own arity, never the source
41
64
  * and never anything the source computed. No observer, method or closure of
42
65
  * the source runs, so a forged `#`, `##`, `###` or `####` cannot steer it, and
43
66
  * comparison is the language's own typed equality, not a spelling. Anything
@@ -54,15 +77,59 @@ function intrinsicDemi(source) {
54
77
  const host = source.referent();
55
78
  if (!host.ownsIdentity())
56
79
  return undefined;
57
- const [count, left, right] = DEMI_STATE.map((key) => storedCount(host, key));
58
- if (!count || !left || !right)
80
+ const count = exactCount(host.get_here("count"));
81
+ const loads = storedLoads(host);
82
+ if (!count || !loads)
59
83
  return undefined;
60
- const candidate = construct(new FrameCount(count.data), new FrameCount(left.data), new FrameCount(right.data));
84
+ const candidate = construct(new FrameCount(count.data), loads.map((load) => new FrameCount(load.data)));
61
85
  if (candidate.isFailedResult() || candidate.observationError()) {
62
86
  return undefined;
63
87
  }
64
88
  return candidate.typeEquals(host) === Frame.all ? candidate : undefined;
65
89
  }
90
+ /**
91
+ * The channel-router path (007.27). A router of k channels routes to channel
92
+ * C mod k, which only a Demi of k loads follows; the binary Demi the observers
93
+ * derive follows parity, so for k other than two it would not be the router's
94
+ * shadow. An instance of the shipped `RotorRouter` class with other than two
95
+ * channels therefore answers the channel Demi of its Count and channel loads,
96
+ * `Demi [C, [load0, …]]`, where a load is the summed Size of a channel's
97
+ * children and an empty channel's load is 0. The binary router keeps the
98
+ * derived path, which already answers `Demi(C, L, R)`.
99
+ *
100
+ * Its Count is the children it holds; at Count zero it has no Demi, as the
101
+ * empty binary router and the empty host have none. Each child's Size is read
102
+ * once, and a failed Size is answered as it is.
103
+ *
104
+ * @param source The observed Frame.
105
+ * @returns The router's channel Demi, nil, an error, or undefined when the
106
+ * source is not a channel router.
107
+ */
108
+ function channelRouterDemi(source) {
109
+ const channels = recognizeRouter?.(source);
110
+ if (!channels)
111
+ return undefined;
112
+ const count = channels.reduce((total, channel) => total + BigInt(channel.elements().length), 0n);
113
+ if (count === 0n)
114
+ return Frame.nil;
115
+ const loads = [];
116
+ for (const channel of channels) {
117
+ if (channel.elements().length === 0) {
118
+ loads.push(new FrameCount(0n));
119
+ continue;
120
+ }
121
+ const size = channel.sizeFor(Frame.kLEAVES);
122
+ if (size.observationError())
123
+ return size;
124
+ const load = exactCount(size);
125
+ if (!load)
126
+ return Frame.error("$!.demi-observations");
127
+ loads.push(new FrameCount(load.data));
128
+ }
129
+ if (!construct)
130
+ return Frame.error("$!.demi-unavailable");
131
+ return construct(new FrameCount(count), loads);
132
+ }
66
133
  /**
67
134
  * The fourth hash, `.####`. For a constructed Demi it is that Demi's own state
68
135
  * (`intrinsicDemi`), Count zero included. For every other Frame it is derived
@@ -92,6 +159,9 @@ export function observeDemi(source) {
92
159
  const intrinsic = intrinsicDemi(source);
93
160
  if (intrinsic)
94
161
  return intrinsic;
162
+ const routed = channelRouterDemi(source);
163
+ if (routed)
164
+ return routed;
95
165
  const n = source.sizeFor(Frame.kCOUNT);
96
166
  if (n.observationError())
97
167
  return n;
@@ -120,6 +190,9 @@ export function observeDemi(source) {
120
190
  }
121
191
  if (!construct)
122
192
  return Frame.error("$!.demi-unavailable");
123
- return construct(new FrameCount(n.data), new FrameCount(sum / 2n), new FrameCount(difference / 2n));
193
+ return construct(new FrameCount(n.data), [
194
+ new FrameCount(sum / 2n),
195
+ new FrameCount(difference / 2n),
196
+ ]);
124
197
  }
125
198
  Frame.demi = observeDemi;
@@ -8,9 +8,22 @@ import { FrameHandle } from "./frame-handle.js";
8
8
  import { FrameList } from "./frame-list.js";
9
9
  import { FrameNote } from "./frame-note.js";
10
10
  import { NilContext } from "./context.js";
11
+ import { guardAccess, noteElements, noteHolding, noteRead, noteWrite, PARENT_KEY, } from "./reference-tracking.js";
11
12
  export class FrameArray extends FrameList {
12
13
  constructor(data, meta = NilContext) {
13
14
  super(data, meta);
15
+ // An aggregate holds its elements from birth (reference-tracking.ts).
16
+ noteElements(this, data);
17
+ }
18
+ /**
19
+ * Assigning the element plane whole releases the elements held before and
20
+ * holds the new ones, element i under the key `i`.
21
+ */
22
+ adoptData(data) {
23
+ const previous = this.data;
24
+ super.adoptData(data);
25
+ if (previous !== data)
26
+ noteElements(this, data, previous);
14
27
  }
15
28
  /** Count leaves use the same Star rule at the root and inside an array. */
16
29
  static starCount(count, replacement) {
@@ -78,9 +91,9 @@ export class FrameArray extends FrameList {
78
91
  if (!node.elements().length)
79
92
  return replacement;
80
93
  const result = node.copy();
81
- result.data = node.itemsFor(result, (item) => node.repeatsTerm(item)
94
+ result.adoptData(node.itemsFor(result, (item) => node.repeatsTerm(item)
82
95
  ? go(item.walked().referent())
83
- : item);
96
+ : item));
84
97
  return result;
85
98
  };
86
99
  return go(this);
@@ -97,6 +110,7 @@ export class FrameArray extends FrameList {
97
110
  // of that field rather than a flag dance over the lexical pointer.
98
111
  if (this.hasDeclaredParent()) {
99
112
  result.parent = this.parent;
113
+ noteHolding(result, PARENT_KEY, this.parent);
100
114
  }
101
115
  // An aggregate accepts declarations while it is under construction, and
102
116
  // says so rather than leaving a name to infer it from the context stack.
@@ -105,7 +119,7 @@ export class FrameArray extends FrameList {
105
119
  // does not make it absorb declarations.
106
120
  result.declares = true;
107
121
  try {
108
- result.data = this.array_eval(input, result);
122
+ result.adoptData(this.array_eval(input, result));
109
123
  }
110
124
  finally {
111
125
  result.declares = false;
@@ -207,16 +221,28 @@ export class FrameArray extends FrameList {
207
221
  instanceCopy() {
208
222
  return this.copy();
209
223
  }
224
+ /** Reading the element plane is a read of this aggregate's state. */
225
+ elements() {
226
+ guardAccess(this, "read");
227
+ noteRead(this);
228
+ return super.elements();
229
+ }
210
230
  /** Elements are members too, so a held element can be replaced in place. */
211
231
  replaceMember(member, replacement) {
212
- let replaced = super.replaceMember(member, replacement);
213
- this.data = this.data.map((item) => {
232
+ const replaced = super.replaceMember(member, replacement);
233
+ let elementReplaced = false;
234
+ this.data.forEach((item, index) => {
214
235
  if (item !== member)
215
- return item;
216
- replaced = true;
217
- return replacement;
236
+ return;
237
+ if (!replaced && !elementReplaced)
238
+ guardAccess(this, "write");
239
+ this.data[index] = replacement;
240
+ noteHolding(this, String(index), replacement, member);
241
+ elementReplaced = true;
218
242
  });
219
- return replaced;
243
+ if (elementReplaced && !replaced)
244
+ noteWrite(this);
245
+ return replaced || elementReplaced;
220
246
  }
221
247
  lookup_here(key, origin) {
222
248
  if (Frame.isIndexKey(key)) {
@@ -413,7 +439,10 @@ export class FrameArray extends FrameList {
413
439
  /** Pushes a non-nil value, whatever application this aggregate declares. */
414
440
  collect(value, _context = Frame.nil) {
415
441
  if (!value.is.void) {
442
+ guardAccess(this, "write");
416
443
  this.data.push(value);
444
+ noteHolding(this, String(this.data.length - 1), value);
445
+ noteWrite(this);
417
446
  }
418
447
  return this;
419
448
  }
@@ -436,7 +465,9 @@ export class FrameArray extends FrameList {
436
465
  return this.data.length;
437
466
  }
438
467
  reset() {
439
- this.data = [];
468
+ guardAccess(this, "write");
469
+ this.adoptData([]);
470
+ noteWrite(this);
440
471
  }
441
472
  }
442
473
  Object.defineProperty(FrameArray, "BEGIN_ARRAY", {