lemmascript 0.6.5 → 0.6.7

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.
package/README.md CHANGED
@@ -4,6 +4,8 @@ A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` s
4
4
 
5
5
  See [SPEC.md](SPEC.md), [DESIGN.md](DESIGN.md), and [GETTING_STARTED.md](GETTING_STARTED.md).
6
6
 
7
+ For changes to LemmaScript itself, see [CONTRIBUTING.md](CONTRIBUTING.md).
8
+
7
9
  This is a **Tech Preview**: the core idea is there, but support, semantics, and ergonomics are still evolving.
8
10
 
9
11
  See our [blog post](https://midspiral.com/blog/lemmascript-a-verification-toolchain-for-typescript/).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -19,15 +19,27 @@
19
19
  * State is explicit (§6.1): detection that mints binders or consults type
20
20
  * declarations takes a `CondCtx`; nothing module-level.
21
21
  */
22
- import { freshName } from "./names.js";
22
+ import { freshName, freshNameWhere, isUserName } from "./names.js";
23
23
  import { unionDeclOfTy, discriminantOf } from "./typedecls.js";
24
+ /** Allocate within this context, retaining a path's name on repeated
25
+ * detection. Semantic-only callers need no registry. */
26
+ function freshBinder(ctx, hint, key) {
27
+ const names = ctx.binders ??= { names: new Map(), used: new Set() };
28
+ const existing = key === undefined ? undefined : names.names.get(key);
29
+ if (existing !== undefined)
30
+ return existing;
31
+ const binder = freshNameWhere(hint, name => isUserName(name) || names.used.has(name));
32
+ names.used.add(binder);
33
+ if (key !== undefined)
34
+ names.names.set(key, binder);
35
+ return binder;
36
+ }
24
37
  export function freshOcBinder(ctx) {
25
- return freshName(`_oc${ctx.oc.n++}_val`);
38
+ return freshBinder(ctx, `_oc${ctx.oc.n++}_val`);
26
39
  }
27
- /** Pure access paths: var(x) or field(purePath, name). Walks down to the
28
- * var root, collecting field names. Returns `_root_field1..._val` (or
29
- * `_root_val` for a bare var); null for non-path shapes. */
30
- export function binderHintFor(e) {
40
+ /** Pure access paths: the raw var root followed by its field names;
41
+ * null for non-path shapes. */
42
+ function pathParts(e) {
31
43
  const fields = [];
32
44
  let cur = e;
33
45
  while (cur.kind === "field") {
@@ -36,9 +48,24 @@ export function binderHintFor(e) {
36
48
  }
37
49
  if (cur.kind !== "var")
38
50
  return null;
51
+ return [cur.name, ...fields];
52
+ }
53
+ export function binderHintFor(e) {
54
+ const parts = pathParts(e);
55
+ if (!parts)
56
+ return null;
39
57
  // \result is stored as the IR var name "\\result"; sanitize for a valid identifier.
40
- const root = cur.name === "\\result" ? "result" : cur.name;
41
- return fields.length === 0 ? `_${root}_val` : `_${root}_${fields.join("_")}_val`;
58
+ const root = parts[0] === "\\result" ? "result" : parts[0];
59
+ return `_${[root, ...parts.slice(1)].join("_")}_val`;
60
+ }
61
+ /** The hint is deliberately readable, not a path identity: `a_b` and `a.b`
62
+ * share it. Key the allocation by the complete path instead. */
63
+ export function freshPathBinder(e, ctx) {
64
+ const hint = binderHintFor(e);
65
+ return hint === null ? null : freshBinder(ctx, hint, JSON.stringify(["path", ...pathParts(e)]));
66
+ }
67
+ export function bindPresentFact(f, ctx) {
68
+ return { ...f, binder: freshPathBinder(f.scrutinee, ctx) };
42
69
  }
43
70
  /** Detect optional checks: `e !== undefined`, `e === undefined`, `!e`, or a
44
71
  * bare optional `e` — for a pure-access-path optional-typed `e`. `!e` and
@@ -95,29 +122,24 @@ export const bound = (f) => ({ kind: "var", name: f.binder, ty: f.innerTy });
95
122
  * the tree with that conjunct removed:
96
123
  * `(x !== undefined && b) && c` → { check, restCond: b && c }.
97
124
  *
98
- * Search order is shallowest-first, left-biased — both immediate operands
99
- * before either nested chain — so the conjunct found is not necessarily the
100
- * source-leftmost one. That is sound because every `parse` passed here
101
- * (`leadingPresent`, `leadingIsArray`) matches only pure, total checks on an
102
- * already-typed path, so hoisting one above the others is observationally
103
- * neutral. The one thing it does change: the residual now sits inside the
104
- * match arm, so a conjunct that would have run before a failing check no
105
- * longer runs at all.
106
- * Harmless while conditions stay pure — revisit if that ever stops holding. */
125
+ * Search matching conjuncts in source order. A later check may read a field
126
+ * whose root an earlier check unwraps, so the left subtree must be searched
127
+ * before the right operand. Keep the remaining conjuncts in their original
128
+ * relative order. */
107
129
  export function extractConjunct(cond, parse) {
108
130
  if (cond.kind !== "binop" || cond.op !== "&&")
109
131
  return null;
110
132
  const left = parse(cond.left);
111
133
  if (left)
112
134
  return { check: left, restCond: cond.right };
113
- const right = parse(cond.right);
114
- if (right)
115
- return { check: right, restCond: cond.left };
116
135
  if (cond.left.kind === "binop" && cond.left.op === "&&") {
117
136
  const inner = extractConjunct(cond.left, parse);
118
137
  if (inner)
119
138
  return { check: inner.check, restCond: { ...cond, left: inner.restCond } };
120
139
  }
140
+ const right = parse(cond.right);
141
+ if (right)
142
+ return { check: right, restCond: cond.left };
121
143
  if (cond.right.kind === "binop" && cond.right.op === "&&") {
122
144
  const inner = extractConjunct(cond.right, parse);
123
145
  if (inner)
@@ -125,9 +147,8 @@ export function extractConjunct(cond, parse) {
125
147
  }
126
148
  return null;
127
149
  }
128
- /** The positive presence fact an `&&` chain contributes, plus the residual.
129
- * "Leading" describes the rewrite, not the source: this fact becomes the
130
- * outermost match, wherever in the chain it was written. */
150
+ /** The first positive presence fact in source order, plus the residual.
151
+ * It becomes the outermost match, keeping later path checks in its arm. */
131
152
  export function leadingPresent(cond) {
132
153
  return extractConjunct(cond, e => {
133
154
  const f = presentFact(e);
@@ -146,10 +167,9 @@ export function noneDetector(leaf, ctx) {
146
167
  if (leaf.kind === "binop" && leaf.op === "!==") {
147
168
  const oc = leaf.left.kind === "optChain" ? leaf.left : leaf.right.kind === "optChain" ? leaf.right : null;
148
169
  if (oc && oc.kind === "optChain" && oc.obj.ty.kind === "optional") {
149
- const hint = binderHintFor(oc.obj);
150
- if (hint === null)
170
+ const binder = freshPathBinder(oc.obj, ctx);
171
+ if (binder === null)
151
172
  return null;
152
- const binder = freshName(hint);
153
173
  const unwrapped = applyChain({ kind: "var", name: binder, ty: oc.obj.ty.inner }, oc.chain);
154
174
  restoreDiscriminantFlag(unwrapped, ctx.decls);
155
175
  const lit = leaf.left === oc ? leaf.right : leaf.left;
@@ -157,8 +177,9 @@ export function noneDetector(leaf, ctx) {
157
177
  }
158
178
  }
159
179
  // `!x` / `x === undefined`.
160
- const f = presentFact(leaf);
161
- if (f && f.negated) {
180
+ const detected = presentFact(leaf);
181
+ if (detected && detected.negated) {
182
+ const f = bindPresentFact(detected, ctx);
162
183
  const residual = canBeFalsy(f)
163
184
  ? { kind: "unop", op: "!", expr: { kind: "var", name: f.binder, ty: f.innerTy }, ty: { kind: "bool" } }
164
185
  : null;
@@ -222,7 +243,7 @@ export function binderHintForMapAccess(m, k, ctx) {
222
243
  // mHint is `_m_val`, kHint is `_k_val` — stitch into `_m_k_val`.
223
244
  const mStem = mHint.replace(/_val$/, "");
224
245
  const kStem = kHint.replace(/^_/, "").replace(/_val$/, "");
225
- return freshName(`${mStem}_${kStem}_val`);
246
+ return freshBinder(ctx, `${mStem}_${kStem}_val`, JSON.stringify(["map", pathParts(m), pathParts(k)]));
226
247
  }
227
248
  return freshOcBinder(ctx);
228
249
  }
@@ -342,7 +363,8 @@ export function negVariantFact(cond, ctx) {
342
363
  /** Reify a presence fact in statement position: the falsy gate (for
343
364
  * truthiness checks over falsy-capable inners) tests the bound value inside
344
365
  * the Some arm, routing falsy inners to `none`. */
345
- export function presentMatchStmts(f, some, none) {
366
+ export function presentMatchStmts(f, some, none, ctx) {
367
+ f = bindPresentFact(f, ctx);
346
368
  return {
347
369
  kind: "someMatch",
348
370
  scrutinee: f.scrutinee, binderTy: f.innerTy,
@@ -352,7 +374,8 @@ export function presentMatchStmts(f, some, none) {
352
374
  };
353
375
  }
354
376
  /** Reify a presence fact in expression position; same falsy gate. */
355
- export function presentMatchExpr(f, some, none, ty) {
377
+ export function presentMatchExpr(f, some, none, ty, ctx) {
378
+ f = bindPresentFact(f, ctx);
356
379
  return {
357
380
  kind: "someMatch",
358
381
  scrutinee: f.scrutinee, binderTy: f.innerTy,
@@ -49,6 +49,13 @@ export const OPTION_SPECS = {
49
49
  fileOverride: false,
50
50
  description: "Record lsc check and regen runs in .lemmascript/.",
51
51
  },
52
+ "unread-annotations": {
53
+ type: "enum",
54
+ values: ["off", "warn", "error"],
55
+ default: "warn",
56
+ fileOverride: true,
57
+ description: "What lsc does with a //@ annotation it does not read: ignore it, warn, or fail.",
58
+ },
52
59
  };
53
60
  export const DEFAULT_OPTIONS = Object.freeze(Object.fromEntries(Object.entries(OPTION_SPECS).map(([key, spec]) => [key, spec.default])));
54
61
  const KNOWN_KEYS = Object.keys(OPTION_SPECS);
@@ -110,13 +117,14 @@ function parseDirectiveValue(key, text, source) {
110
117
  return parseOptionValue(key, text, source);
111
118
  }
112
119
  /**
113
- * Find comment lines, marking those that occur before any code.
120
+ * Find comment lines and the comment on each, marking those that occur before
121
+ * any code.
114
122
  *
115
123
  * Use the parsed syntax tree to skip strings, regexes, and template text.
116
124
  * Without those boundaries, the scanner can read /[/*]/ as a block comment
117
125
  * or treat a template's closing backtick as the start of another template.
118
126
  */
119
- function* fileCommentLines(sourceText) {
127
+ export function* fileCommentLines(sourceText) {
120
128
  // Normalize once so a leading BOM also works before a shebang.
121
129
  sourceText = sourceText.replace(/^\uFEFF/, "");
122
130
  const lines = sourceText.split(/\r\n|[\n\r\u2028\u2029]/);
@@ -139,8 +147,9 @@ function* fileCommentLines(sourceText) {
139
147
  if (token === ts.SyntaxKind.SingleLineCommentTrivia || token === ts.SyntaxKind.MultiLineCommentTrivia) {
140
148
  const firstLine = sourceFile.getLineAndCharacterOfPosition(scanner.getTokenStart()).line;
141
149
  const lastLine = sourceFile.getLineAndCharacterOfPosition(scanner.getTokenEnd() - 1).line;
150
+ const comment = scanner.getTokenText();
142
151
  for (let index = firstLine; index <= lastLine; index++) {
143
- yield { text: lines[index], index, inLeadingRegion };
152
+ yield { text: lines[index], comment, index, inLeadingRegion };
144
153
  }
145
154
  }
146
155
  else if (token !== ts.SyntaxKind.WhitespaceTrivia && token !== ts.SyntaxKind.NewLineTrivia &&
@@ -152,6 +161,20 @@ function* fileCommentLines(sourceText) {
152
161
  }
153
162
  }
154
163
  }
164
+ const OPTION_DIRECTIVE = /^[ \t]*\/\/@[ \t]+option(?:[ \t]+(.*?))?[ \t]*$/;
165
+ const ALIAS_DIRECTIVE = /^[ \t]*\/\/@[ \t]+([A-Za-z][A-Za-z0-9-]*)[ \t]*$/;
166
+ /** The option a legacy alias such as `//@ safe-slice` sets, if `line` is one. */
167
+ function aliasedOption(line) {
168
+ const alias = line.match(ALIAS_DIRECTIVE)?.[1];
169
+ if (alias === undefined)
170
+ return undefined;
171
+ return KNOWN_KEYS.find(key => "directiveAliases" in OPTION_SPECS[key] &&
172
+ OPTION_SPECS[key].directiveAliases.includes(alias));
173
+ }
174
+ /** Whether `parseFileOptions` reads `line` as an option directive or a legacy alias. */
175
+ export function isOptionDirective(line) {
176
+ return OPTION_DIRECTIVE.test(line) || aliasedOption(line) !== undefined;
177
+ }
155
178
  /** Parse top-of-file `//@ option key value` directives and legacy aliases. */
156
179
  export function parseFileOptions(sourceText, source) {
157
180
  const seen = new Map();
@@ -166,7 +189,7 @@ export function parseFileOptions(sourceText, source) {
166
189
  };
167
190
  const parseLine = (lineText, index, inLeadingRegion) => {
168
191
  const line = index + 1;
169
- const optionMatch = lineText.match(/^[ \t]*\/\/@[ \t]+option(?:[ \t]+(.*?))?[ \t]*$/);
192
+ const optionMatch = lineText.match(OPTION_DIRECTIVE);
170
193
  if (optionMatch) {
171
194
  if (!inLeadingRegion)
172
195
  fail(`${source}:${line}`, "//@ option directives must appear before the first source statement");
@@ -183,21 +206,11 @@ export function parseFileOptions(sourceText, source) {
183
206
  setOption(rawKey, parseDirectiveValue(rawKey, rawValue, `${source}:${line}`), line);
184
207
  return;
185
208
  }
186
- const aliasMatch = lineText.match(/^[ \t]*\/\/@[ \t]+([A-Za-z][A-Za-z0-9-]*)[ \t]*$/);
187
- if (!aliasMatch)
188
- return;
189
- const alias = aliasMatch[1];
190
- for (const key of KNOWN_KEYS) {
191
- const aliases = "directiveAliases" in OPTION_SPECS[key]
192
- ? OPTION_SPECS[key].directiveAliases
193
- : [];
194
- if (!aliases.includes(alias))
195
- continue;
196
- // Legacy aliases retain their pre-config placement behavior. New generic
197
- // option directives are deliberately restricted to the file preamble.
209
+ // Legacy aliases retain their pre-config placement behavior. New generic
210
+ // option directives are deliberately restricted to the file preamble.
211
+ const key = aliasedOption(lineText);
212
+ if (key)
198
213
  setOption(key, true, line);
199
- return;
200
- }
201
214
  };
202
215
  for (const { text, index, inLeadingRegion } of fileCommentLines(sourceText)) {
203
216
  parseLine(text, index, inLeadingRegion);
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Dafny emitter — IR → Dafny text.
3
3
  */
4
- import { exactIntegerLiteral, usesName, usesNameInDecl, usesNameInStmts } from "./ir.js";
4
+ import { decimalNumberLiteral, exactIntegerLiteral, usesName, usesNameInDecl, usesNameInStmts } from "./ir.js";
5
5
  import { freshNameWhere, userNames } from "./names.js";
6
6
  import { renameFreeVar } from "./transform.js";
7
7
  import { DEFAULT_OPTIONS, resolveOptions } from "./config.js";
@@ -268,7 +268,7 @@ function wrapQuantifier(sub) {
268
268
  function emitExpr(e) {
269
269
  switch (e.kind) {
270
270
  case "var": return e.name === "undefined" ? "None" : escapeName(e.name);
271
- case "num": return `${e.value}`;
271
+ case "num": return decimalNumberLiteral(e.value);
272
272
  // Already canonical decimal; Dafny's `int` is mathematical, so no `n` suffix.
273
273
  case "bigint": return e.value;
274
274
  case "bool": return e.value ? "true" : "false";
@@ -454,8 +454,10 @@ function emitExpr(e) {
454
454
  if (ty === "string") {
455
455
  if (e.method === "indexOf") {
456
456
  needPreamble("StringIndexOf");
457
- if (args.length === 2)
458
- return `StringIndexOfFrom(${obj}, ${args[0]}, ${args[1]})`;
457
+ if (args.length === 2) {
458
+ needPreamble("StringSearchPosition");
459
+ return `StringIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]}))`;
460
+ }
459
461
  return `StringIndexOf(${obj}, ${args[0]})`;
460
462
  }
461
463
  if (e.method === "split") {
@@ -484,8 +486,14 @@ function emitExpr(e) {
484
486
  return `${obj}[${args[0]}..]`;
485
487
  return `${obj}[${args[0]}..${args[1]}]`;
486
488
  }
487
- if (e.method === "endsWith")
489
+ if (e.method === "endsWith") {
490
+ if (args.length === 2) {
491
+ needPreamble("StringSearchPosition");
492
+ needPreamble("StringEndsWithAt");
493
+ return `StringEndsWithAt(${obj}, ${args[0]}, ${args[1]})`;
494
+ }
488
495
  return `(|${obj}| >= |${args[0]}| && ${obj}[|${obj}|-|${args[0]}|..] == ${args[0]})`;
496
+ }
489
497
  if (e.method === "trim") {
490
498
  needPreamble("StringTrim");
491
499
  return `StringTrim(${obj})`;
@@ -508,10 +516,20 @@ function emitExpr(e) {
508
516
  }
509
517
  if (e.method === "includes") {
510
518
  needPreamble("StringIndexOf");
519
+ if (args.length === 2) {
520
+ needPreamble("StringSearchPosition");
521
+ return `(StringIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]})) >= 0)`;
522
+ }
511
523
  return `(StringIndexOf(${obj}, ${args[0]}) >= 0)`;
512
524
  }
513
- if (e.method === "startsWith")
525
+ if (e.method === "startsWith") {
526
+ if (args.length === 2) {
527
+ needPreamble("StringSearchPosition");
528
+ needPreamble("StringStartsWithAt");
529
+ return `StringStartsWithAt(${obj}, ${args[0]}, ${args[1]})`;
530
+ }
514
531
  return `(|${obj}| >= |${args[0]}| && ${obj}[..|${args[0]}|] == ${args[0]})`;
532
+ }
515
533
  if (e.method === "charCodeAt")
516
534
  return `(${obj}[${args[0]}] as int)`;
517
535
  if (e.method === "repeat") {
@@ -1271,6 +1289,21 @@ function SafeSlice<T>(s: seq<T>, lo: int, hi: int): seq<T>
1271
1289
  var hi' := NormalizeSliceIndex(|s|, hi);
1272
1290
  if hi' < lo' then [] else s[lo'..hi']
1273
1291
  }`;
1292
+ const STRING_SEARCH_POSITION = `function StringSearchPosition(s: string, position: int): nat
1293
+ ensures StringSearchPosition(s, position) <= |s|
1294
+ {
1295
+ if position < 0 then 0 else if position > |s| then |s| else position
1296
+ }`;
1297
+ const STRING_STARTS_WITH_AT = `function StringStartsWithAt(s: string, sub: string, position: int): bool
1298
+ {
1299
+ var start := StringSearchPosition(s, position);
1300
+ |sub| <= |s| - start && s[start..start + |sub|] == sub
1301
+ }`;
1302
+ const STRING_ENDS_WITH_AT = `function StringEndsWithAt(s: string, sub: string, position: int): bool
1303
+ {
1304
+ var end := StringSearchPosition(s, position);
1305
+ |sub| <= end && s[end - |sub|..end] == sub
1306
+ }`;
1274
1307
  const STRING_INDEX_OF = `function StringIndexOf(s: string, sub: string): int
1275
1308
  ensures StringIndexOf(s, sub) == -1
1276
1309
  || (0 <= StringIndexOf(s, sub) <= |s| - |sub| && s[StringIndexOf(s, sub)..StringIndexOf(s, sub) + |sub|] == sub)
@@ -1524,6 +1557,9 @@ const PREAMBLE_CODE = [
1524
1557
  ["SeqJoin", SEQ_JOIN],
1525
1558
  ["SafeSlice", SAFE_SLICE],
1526
1559
  ["StringIndexOf", STRING_INDEX_OF],
1560
+ ["StringSearchPosition", STRING_SEARCH_POSITION],
1561
+ ["StringStartsWithAt", STRING_STARTS_WITH_AT],
1562
+ ["StringEndsWithAt", STRING_ENDS_WITH_AT],
1527
1563
  ["StringSplit", STRING_SPLIT],
1528
1564
  ["SeqSort", SEQ_SORT],
1529
1565
  ["SeqSortBy", SEQ_SORT_BY],