lemmascript 0.6.12 → 0.6.14

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.
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Place-driven mutation write-back lowering for `transform.ts`
3
+ * (`midspiral/LemmaScript#387`, Milestone 3a / `robertpenner/LemmaScript#49`).
4
+ *
5
+ * Consumes the self-verified `PlacePath` representation in `places.ts` and
6
+ * maintains the active stack of narrowing write-back frames (`someMatch`
7
+ * unwraps and `switch`/`tagMatch` union variants) so in-place mutations
8
+ * (`push`, `unshift`, `sort`, `pop`, `set`, `add`, `delete`, index updates,
9
+ * and record-field assignments) always propagate back to the owning lexical
10
+ * storage variable instead of mutating a discarded copy or match binder.
11
+ */
12
+ import { extendFieldPlace, extendUnwrapPlace, extendVariantPlace, makeVarPlace, } from "./places.js";
13
+ export function makeUnwrapFrame(binder, rootVar, fields) {
14
+ let place = makeVarPlace(rootVar);
15
+ for (const f of fields)
16
+ place = extendFieldPlace(place, f);
17
+ place = extendUnwrapPlace(place);
18
+ return { kind: "unwrap", binder, rootVar, fields, place };
19
+ }
20
+ export function makeVariantFrame(unionVar, typeName, ctorName, fields) {
21
+ const place = extendVariantPlace(makeVarPlace(unionVar), ctorName);
22
+ return { kind: "variant", unionVar, typeName, ctorName, fields, place };
23
+ }
24
+ /** True for in-place mutating collection methods modeled by functional write-back. */
25
+ export function isMutatingCollectionMethod(recvTy, method) {
26
+ if ((recvTy.kind === "map" || recvTy.kind === "set") &&
27
+ (method === "set" || method === "add" || method === "delete")) {
28
+ return true;
29
+ }
30
+ if (recvTy.kind === "array" && (method === "push" || method === "unshift" || method === "sort")) {
31
+ return true;
32
+ }
33
+ return false;
34
+ }
35
+ /** Build a nested record-update expression rooted at `rootVar` for `fields`
36
+ * (length >= 1), setting the innermost field to `newVal`. */
37
+ export function buildNestedFieldExpr(rootVar, fields, newVal) {
38
+ const baseFor = (len) => {
39
+ let cur = { kind: "var", name: rootVar };
40
+ for (let i = 0; i < len; i++) {
41
+ cur = { kind: "field", obj: cur, field: fields[i], datatypeField: true };
42
+ }
43
+ return cur;
44
+ };
45
+ let curVal = newVal;
46
+ for (let i = fields.length - 1; i >= 0; i--) {
47
+ curVal = {
48
+ kind: "record",
49
+ spread: baseFor(i),
50
+ fields: [{ name: fields[i], value: curVal }],
51
+ };
52
+ }
53
+ return curVal;
54
+ }
55
+ function optionSome(value) {
56
+ return { kind: "constructor", name: "some", type: "Option", args: [value] };
57
+ }
58
+ /**
59
+ * Given a variable `mutatedTarget` that was just assigned in the lowered IR,
60
+ * walk `frames` from innermost to outermost and emit the cascading write-back
61
+ * assignments that synchronize every enclosing narrowing binder and the owning
62
+ * lexical storage variable.
63
+ */
64
+ export function emitWriteBacksForTarget(mutatedTarget, frames) {
65
+ const out = [];
66
+ let current = mutatedTarget;
67
+ for (let i = frames.length - 1; i >= 0; i--) {
68
+ const frame = frames[i];
69
+ if (frame.kind === "unwrap" && frame.binder === current) {
70
+ const wrapped = optionSome({ kind: "var", name: frame.binder });
71
+ if (frame.fields.length === 0) {
72
+ out.push({ kind: "assign", target: frame.rootVar, value: wrapped });
73
+ }
74
+ else {
75
+ out.push({
76
+ kind: "assign",
77
+ target: frame.rootVar,
78
+ value: buildNestedFieldExpr(frame.rootVar, frame.fields, wrapped),
79
+ });
80
+ }
81
+ current = frame.rootVar;
82
+ continue;
83
+ }
84
+ if (frame.kind === "variant" && frame.fields.some(f => f.binder === current)) {
85
+ const reconstructed = {
86
+ kind: "app",
87
+ fn: frame.ctorName,
88
+ ctorOf: frame.typeName,
89
+ args: frame.fields.map(f => ({ kind: "var", name: f.binder })),
90
+ };
91
+ out.push({ kind: "assign", target: frame.unionVar, value: reconstructed });
92
+ current = frame.unionVar;
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ /** Find the innermost active `unwrap` frame whose scrutinee matches `(rootVar, fields)`. */
98
+ export function findActiveUnwrapFrame(rootVar, fields, frames) {
99
+ for (let i = frames.length - 1; i >= 0; i--) {
100
+ const frame = frames[i];
101
+ if (frame.kind === "unwrap" &&
102
+ frame.rootVar === rootVar &&
103
+ frame.fields.length === fields.length &&
104
+ frame.fields.every((f, idx) => f === fields[idx])) {
105
+ return frame;
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+ /** Resolve a source dotted path like `["b", "count"]`, `["u", "v"]`, or
111
+ * `["u", "box", "count"]` through any enclosing `unwrap` and `variant` frames.
112
+ * Returns:
113
+ * - `currentRoot`: the deepest active binder/variable reached,
114
+ * - `remainingFields`: any field steps remaining below `currentRoot`,
115
+ * - `leafUnwrapFrame`: if the entire path ended at an active `unwrap` frame
116
+ * (so non-optional writes update `leafUnwrapFrame.binder` and cascade,
117
+ * while `undefined`/optional writes update `leafUnwrapFrame.rootVar`),
118
+ * - `leafVariantBinder`: if the entire path ended directly at a union
119
+ * variant field binder (e.g. `u.v` -> `i_u_v`). */
120
+ export function resolveWriteTargetThroughFrames(rootVar, fields, frames) {
121
+ let currentRoot = rootVar;
122
+ let idx = 0;
123
+ let lastUnwrap = null;
124
+ let lastVariantBinder = null;
125
+ // Iteratively step through active `unwrap` (0-field or prefix-field) and
126
+ // `variant` (1-field) frames until no more frames match.
127
+ while (true) {
128
+ // 1. Bare unwrap on `currentRoot` (e.g. `b` -> `_b_val`, or `u` -> `_u_val`).
129
+ const bareUnwrap = findActiveUnwrapFrame(currentRoot, [], frames);
130
+ if (bareUnwrap) {
131
+ currentRoot = bareUnwrap.binder;
132
+ lastUnwrap = bareUnwrap;
133
+ lastVariantBinder = null;
134
+ continue;
135
+ }
136
+ if (idx >= fields.length)
137
+ break;
138
+ // 2. Variant field projection on `currentRoot` (e.g. `u.v` -> `i_u_v`, `u.box` -> `i_u_box`).
139
+ let matchedVariant = null;
140
+ for (let i = frames.length - 1; i >= 0; i--) {
141
+ const frame = frames[i];
142
+ if (frame.kind === "variant" && frame.unionVar === currentRoot) {
143
+ const hit = frame.fields.find(f => f.fieldName === fields[idx]);
144
+ if (hit) {
145
+ matchedVariant = hit.binder;
146
+ break;
147
+ }
148
+ }
149
+ }
150
+ if (matchedVariant) {
151
+ currentRoot = matchedVariant;
152
+ idx += 1;
153
+ lastUnwrap = null;
154
+ lastVariantBinder = matchedVariant;
155
+ continue;
156
+ }
157
+ // 3. Field-prefix unwrap on `currentRoot` (e.g. `_b_val.items` -> `_b_val_items_val`).
158
+ let matchedLen = 0;
159
+ let matchedUnwrap = null;
160
+ for (let len = fields.length - idx; len >= 1; len--) {
161
+ const sub = fields.slice(idx, idx + len);
162
+ const hit = findActiveUnwrapFrame(currentRoot, sub, frames);
163
+ if (hit) {
164
+ matchedLen = len;
165
+ matchedUnwrap = hit;
166
+ break;
167
+ }
168
+ }
169
+ if (matchedUnwrap) {
170
+ currentRoot = matchedUnwrap.binder;
171
+ idx += matchedLen;
172
+ lastUnwrap = matchedUnwrap;
173
+ lastVariantBinder = null;
174
+ continue;
175
+ }
176
+ break;
177
+ }
178
+ return {
179
+ currentRoot,
180
+ remainingFields: fields.slice(idx),
181
+ leafUnwrapFrame: idx === fields.length ? lastUnwrap : null,
182
+ leafVariantBinder: idx === fields.length ? lastVariantBinder : null,
183
+ };
184
+ }
185
+ /** Collect every variable name assigned anywhere in lowered IR `Stmt[]`
186
+ * (both `assign` and Lean monadic `bind`). */
187
+ export function collectAssignedIrTargets(stmts) {
188
+ const assigned = new Set();
189
+ const walk = (ss) => {
190
+ for (const s of ss) {
191
+ if ((s.kind === "assign" || s.kind === "bind") && s.target !== "_" && !s.target.includes(".")) {
192
+ assigned.add(s.target);
193
+ }
194
+ else if (s.kind === "if") {
195
+ walk(s.then);
196
+ walk(s.else);
197
+ }
198
+ else if (s.kind === "while" || s.kind === "forin") {
199
+ walk(s.body);
200
+ }
201
+ else if (s.kind === "match") {
202
+ for (const a of s.arms)
203
+ walk(a.body);
204
+ }
205
+ }
206
+ };
207
+ walk(stmts);
208
+ return assigned;
209
+ }
210
+ /** Describe a non-Place receiver for a clear fail-closed diagnostic. */
211
+ export function describeReceiver(recv) {
212
+ switch (recv.kind) {
213
+ case "var": return recv.name;
214
+ case "field": return `${describeReceiver(recv.obj)}.${recv.field}`;
215
+ case "call": return `${describeReceiver(recv.fn)}(...)`;
216
+ case "index": return `${describeReceiver(recv.obj)}[...]`;
217
+ default: return `<${recv.kind}>`;
218
+ }
219
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Pure Place representation for unified mutation write-back
3
+ * (`midspiral/LemmaScript#387`, Milestone 3a / `robertpenner/LemmaScript#49`).
4
+ *
5
+ * Kept strictly inside the LemmaScript subset so its structural contracts
6
+ * (root identity, depth/step-length correspondence, non-overlap soundness) are
7
+ * self-verified via `npx lsc check --backend=dafny tools/src/places.ts`.
8
+ */
9
+ //@ pure
10
+ export function makeVarPlace(name) {
11
+ return { root: name, steps: [] };
12
+ }
13
+ //@ pure
14
+ //@ ensures \result.root == p.root
15
+ //@ ensures \result.steps.length == p.steps.length + 1
16
+ export function extendFieldPlace(p, field) {
17
+ return { root: p.root, steps: [...p.steps, { kind: "field", field }] };
18
+ }
19
+ //@ pure
20
+ //@ ensures \result.root == p.root
21
+ //@ ensures \result.steps.length == p.steps.length + 1
22
+ export function extendIndexPlace(p, idxTag) {
23
+ return { root: p.root, steps: [...p.steps, { kind: "index", idxTag }] };
24
+ }
25
+ //@ pure
26
+ //@ ensures \result.root == p.root
27
+ //@ ensures \result.steps.length == p.steps.length + 1
28
+ export function extendMapKeyPlace(p, keyTag) {
29
+ return { root: p.root, steps: [...p.steps, { kind: "mapKey", keyTag }] };
30
+ }
31
+ //@ pure
32
+ //@ ensures \result.root == p.root
33
+ //@ ensures \result.steps.length == p.steps.length + 1
34
+ export function extendUnwrapPlace(p) {
35
+ return { root: p.root, steps: [...p.steps, { kind: "unwrap" }] };
36
+ }
37
+ //@ pure
38
+ //@ ensures \result.root == p.root
39
+ //@ ensures \result.steps.length == p.steps.length + 1
40
+ export function extendVariantPlace(p, tag) {
41
+ return { root: p.root, steps: [...p.steps, { kind: "variant", tag }] };
42
+ }
43
+ //@ pure
44
+ //@ ensures \result == p.root
45
+ export function placeRoot(p) {
46
+ return p.root;
47
+ }
48
+ //@ pure
49
+ //@ ensures \result >= 0
50
+ //@ ensures \result == p.steps.length
51
+ export function placeDepth(p) {
52
+ return p.steps.length;
53
+ }
54
+ //@ pure
55
+ //@ ensures \result == (p.steps.length == 0)
56
+ export function placeIsVar(p) {
57
+ return p.steps.length === 0;
58
+ }
59
+ /** Sound step-compatibility check: returns false only when two steps are
60
+ * provably distinct (different field names or different union variant tags,
61
+ * or incompatible step kinds at the same position). */
62
+ //@ pure
63
+ export function stepsMayMatch(a, b) {
64
+ if (a.kind === "field") {
65
+ if (b.kind === "field")
66
+ return a.field === b.field;
67
+ return false;
68
+ }
69
+ if (a.kind === "variant") {
70
+ if (b.kind === "variant")
71
+ return a.tag === b.tag;
72
+ return false;
73
+ }
74
+ if (a.kind === "unwrap") {
75
+ return b.kind === "unwrap";
76
+ }
77
+ if (a.kind === "index") {
78
+ return b.kind === "index";
79
+ }
80
+ return b.kind === "mapKey";
81
+ }
82
+ /** Sound overlap predicate on PlacePaths:
83
+ * - Different roots can never overlap (returns false).
84
+ * - Same root: if any shared prefix position has incompatible steps
85
+ * (for example `.a` vs `.b`, or variant `"circle"` vs `"square"`),
86
+ * returns false. Otherwise conservatively returns true. */
87
+ //@ ensures a.root != b.root ==> !\result
88
+ export function placesMayOverlap(a, b) {
89
+ if (a.root !== b.root)
90
+ return false;
91
+ const limit = a.steps.length < b.steps.length ? a.steps.length : b.steps.length;
92
+ let i = 0;
93
+ while (i < limit) {
94
+ //@ invariant 0 <= i && i <= limit
95
+ if (!stepsMayMatch(a.steps[i], b.steps[i])) {
96
+ return false;
97
+ }
98
+ i = i + 1;
99
+ }
100
+ return true;
101
+ }
102
+ /** True iff `p` contains at least one `unwrap` step (Option/Nullish payload). */
103
+ export function placeHasUnwrap(p) {
104
+ let i = 0;
105
+ while (i < p.steps.length) {
106
+ //@ invariant 0 <= i && i <= p.steps.length
107
+ if (p.steps[i].kind === "unwrap")
108
+ return true;
109
+ i = i + 1;
110
+ }
111
+ return false;
112
+ }
113
+ /** True iff `p` contains at least one `variant` step (discriminated union payload). */
114
+ export function placeHasVariant(p) {
115
+ let i = 0;
116
+ while (i < p.steps.length) {
117
+ //@ invariant 0 <= i && i <= p.steps.length
118
+ if (p.steps[i].kind === "variant")
119
+ return true;
120
+ i = i + 1;
121
+ }
122
+ return false;
123
+ }