lemmascript 0.6.13 → 0.6.15

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.
@@ -29,6 +29,12 @@ export const OPTION_SPECS = {
29
29
  fileOverride: false,
30
30
  description: "Directory for Dafny artifacts, relative to lemmascript.json.",
31
31
  },
32
+ "proof-files": {
33
+ type: "proof-files",
34
+ default: {},
35
+ fileOverride: false,
36
+ description: "Additional Dafny files to verify with each source, relative to lemmascript.json.",
37
+ },
32
38
  "string-semantics": {
33
39
  type: "enum",
34
40
  values: ["unicode-scalar", "javascript-utf16"],
@@ -66,7 +72,14 @@ function fail(source, message) {
66
72
  function isKnownKey(key) {
67
73
  return Object.hasOwn(OPTION_SPECS, key);
68
74
  }
69
- /** Validate one option against the registry and return its typed value. */
75
+ function relativePath(raw, key, source) {
76
+ if (typeof raw !== "string" || raw.trim().length === 0) {
77
+ fail(source, `option '${key}' must be a non-empty relative path`);
78
+ }
79
+ if (path.isAbsolute(raw))
80
+ fail(source, `option '${key}' must be relative to lemmascript.json`);
81
+ return raw;
82
+ }
70
83
  export function parseOptionValue(key, raw, source) {
71
84
  const spec = OPTION_SPECS[key];
72
85
  if (spec.type === "boolean") {
@@ -80,12 +93,27 @@ export function parseOptionValue(key, raw, source) {
80
93
  }
81
94
  return raw;
82
95
  }
83
- if (typeof raw !== "string" || raw.trim().length === 0) {
84
- fail(source, `option '${key}' must be a non-empty relative path`);
96
+ if (spec.type === "proof-files") {
97
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
98
+ fail(source, "'proof-files' must map source paths to arrays of .dfy paths");
99
+ }
100
+ const files = Object.create(null);
101
+ for (const [name, paths] of Object.entries(raw)) {
102
+ const file = path.normalize(relativePath(name, key, source));
103
+ if (Object.hasOwn(files, file))
104
+ fail(source, `duplicate source '${name}' in proof-files`);
105
+ if (!Array.isArray(paths))
106
+ fail(source, `proof-files['${name}'] must be an array of .dfy paths`);
107
+ files[file] = [...new Set(paths.map(value => {
108
+ const proof = relativePath(value, key, source);
109
+ if (path.extname(proof) !== ".dfy")
110
+ fail(source, `expected a .dfy file for '${name}', got '${proof}'`);
111
+ return path.normalize(proof);
112
+ }))];
113
+ }
114
+ return files;
85
115
  }
86
- if (path.isAbsolute(raw))
87
- fail(source, `option '${key}' must be relative to lemmascript.json`);
88
- return raw;
116
+ return relativePath(raw, key, source);
89
117
  }
90
118
  /** Validate a parsed lemmascript.json object, returning only explicitly set keys. */
91
119
  export function validateOptions(raw, source) {
@@ -261,6 +289,14 @@ export function loadConfigOptions(sourcePath, configPath) {
261
289
  CONFIG_CACHE.set(configFile, explicit);
262
290
  return { explicit: { ...explicit }, configFile };
263
291
  }
292
+ export function resolveDafnyProofFiles(sourcePath, configFile, options) {
293
+ if (!configFile)
294
+ return [];
295
+ const dir = path.dirname(configFile);
296
+ const source = path.relative(dir, sourcePath);
297
+ const files = options["proof-files"];
298
+ return Object.hasOwn(files, source) ? files[source].map(file => path.resolve(dir, file)) : [];
299
+ }
264
300
  /** Resolve the directory containing one source file's Dafny companions. */
265
301
  export function resolveDafnyArtifactDir(sourcePath, configFile, options) {
266
302
  const source = path.resolve(sourcePath);
@@ -160,10 +160,26 @@ export function dafnyVerifyArgs(content, timeLimit, extraFlags) {
160
160
  args.push("--allow-deprecation");
161
161
  return { args };
162
162
  }
163
- export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
163
+ export function readDafnyProofFiles(files, dfyPath, log) {
164
+ try {
165
+ return files.map(file => {
166
+ const text = readFileSync(file, "utf8");
167
+ const violations = proofAdditionViolations("", text, file);
168
+ if (violations.length)
169
+ throw new Error(violations.join("\n"));
170
+ return { file, text };
171
+ });
172
+ }
173
+ catch (error) {
174
+ log?.finish({ stage: "diff", exit: 1, dfyPath });
175
+ throw error;
176
+ }
177
+ }
178
+ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log, proofs = []) {
164
179
  console.log("Running dafny verify...");
165
180
  try {
166
- const { args, error } = dafnyVerifyArgs(readFileSync(dfyPath, "utf-8"), timeLimit, extraFlags);
181
+ const content = [readFileSync(dfyPath, "utf8"), ...proofs.map(p => p.text)].join("\n");
182
+ const { args, error } = dafnyVerifyArgs(content, timeLimit, extraFlags);
167
183
  if (error) {
168
184
  console.error(error);
169
185
  log?.finish({ stage: "resolve", exit: 1, dfyPath });
@@ -171,7 +187,7 @@ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
171
187
  }
172
188
  if (log)
173
189
  args.push(...log.dafnyArgs());
174
- args.push(dfyPath);
190
+ args.push(dfyPath, ...proofs.map(p => p.file));
175
191
  execFileSync("dafny", args, { cwd: dir, stdio: "inherit" });
176
192
  log?.finish({ stage: "ok", exit: 0, dfyPath, results: log.readResults() });
177
193
  return true;
@@ -188,7 +204,7 @@ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
188
204
  return false;
189
205
  }
190
206
  }
191
- export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log) {
207
+ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log, proofs = []) {
192
208
  // 1. Read old gen before overwriting (needed for base seeding)
193
209
  const oldGen = existsSync(genPath) ? readFileSync(genPath, "utf-8") : "";
194
210
  // 2. Always write new gen so user can inspect latest output
@@ -197,7 +213,7 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
197
213
  if (!existsSync(dfyPath)) {
198
214
  writeFileSync(dfyPath, text);
199
215
  console.log(`Created: ${path.basename(dfyPath)}`);
200
- if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
216
+ if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log, proofs)) {
201
217
  console.error(`FAILED: ${path.basename(dfyPath)} verification failed on first run.`);
202
218
  process.exit(1);
203
219
  }
@@ -261,7 +277,7 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
261
277
  process.exit(1);
262
278
  }
263
279
  // 7. Verify (skipped under --no-verify: caller verifies separately)
264
- if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
280
+ if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log, proofs)) {
265
281
  // The clean merge already incorporated this generation into the proof
266
282
  // file. Keep that generation as the next merge anchor even though the
267
283
  // verifier rejected the current proof state; otherwise the next regen
@@ -31,6 +31,7 @@ function tyToDafny(ty) {
31
31
  case "bool": return "bool";
32
32
  case "string": return "string";
33
33
  case "void": return "()";
34
+ case "null": return "()";
34
35
  case "array": return `seq<${tyToDafny(ty.elem)}>`;
35
36
  case "tuple": return `(${ty.elems.map(tyToDafny).join(", ")})`;
36
37
  case "map": return `map<${tyToDafny(ty.key)}, ${tyToDafny(ty.value)}>`;
@@ -39,6 +40,10 @@ function tyToDafny(ty) {
39
40
  needPreamble("OptionType");
40
41
  return `Option<${tyToDafny(ty.inner)}>`;
41
42
  }
43
+ case "nullish": {
44
+ needPreamble("NullishType");
45
+ return `Nullish<${tyToDafny(ty.inner)}>`;
46
+ }
42
47
  case "user": return escapeName(ty.name);
43
48
  case "fn": return `(${ty.params.map(tyToDafny).join(", ")}) -> ${tyToDafny(ty.result)}`;
44
49
  // Out-of-subset (`any`/`unknown`); opaque so real ops on it fail loudly
@@ -296,6 +301,8 @@ function emitExpr(e) {
296
301
  // signature, so request the preamble here.
297
302
  if (e.type === "Option")
298
303
  needPreamble("OptionType");
304
+ if (e.type === "Nullish")
305
+ needPreamble("NullishType");
299
306
  const head = qualifyCtor(e.name, e.type);
300
307
  if (!e.args || e.args.length === 0)
301
308
  return head;
@@ -583,6 +590,17 @@ function emitExpr(e) {
583
590
  return `StringRepeat(${obj}, ${args[0]})`;
584
591
  }
585
592
  }
593
+ // Nullish<T> discriminators (#304)
594
+ if (ty === "nullish") {
595
+ needPreamble("NullishType");
596
+ const recv = e.obj.kind === "var" || e.obj.kind === "field" ? obj : `(${obj})`;
597
+ if (e.method === "isNull")
598
+ return `${recv}.Null?`;
599
+ if (e.method === "isUndefined")
600
+ return `${recv}.Undefined?`;
601
+ if (e.method === "isValue")
602
+ return `${recv}.Value?`;
603
+ }
586
604
  // Map methods
587
605
  if (ty === "map") {
588
606
  if (e.method === "getDirect")
@@ -841,7 +859,7 @@ function emitExpr(e) {
841
859
  const fieldNames = new Set(e.fields.map(f => f.name));
842
860
  const matches = [];
843
861
  for (const [name, fields] of _structureDecls) {
844
- if (fields.length >= e.fields.length && fields.every(f => fieldNames.has(f.name) || f.type.kind === "optional")) {
862
+ if (fields.length >= e.fields.length && fields.every(f => fieldNames.has(f.name) || f.type.kind === "optional" || f.type.kind === "nullish")) {
845
863
  matches.push(name);
846
864
  }
847
865
  }
@@ -869,6 +887,10 @@ function emitExpr(e) {
869
887
  needPreamble("OptionType");
870
888
  return "None";
871
889
  }
890
+ if (sf.type.kind === "nullish") {
891
+ needPreamble("NullishType");
892
+ return "Nullish.Undefined";
893
+ }
872
894
  return `/* missing: ${sf.name} */`;
873
895
  });
874
896
  return `${ctorName}(${vals.join(", ")})`;
@@ -1740,6 +1762,7 @@ const SET_TO_SEQ = `method SetToSeq<T>(s: set<T>) returns (res: seq<T>)
1740
1762
  /** Preamble code keyed by name. Emitted in this order when needed. */
1741
1763
  const PREAMBLE_CODE = [
1742
1764
  ["OptionType", "datatype Option<T> = None | Some(value: T)"],
1765
+ ["NullishType", "datatype Nullish<T> = Undefined | Null | Value(value: T)"],
1743
1766
  // Opaque carrier for `unknown`-typed values. `(==)` for compare/map-key/match;
1744
1767
  // `(0)` (auto-init ⇒ nonempty) so `havoc` (`:= *`) is well-formed.
1745
1768
  ["UnknownType", "type Unknown(==, 0)"],
@@ -1882,7 +1905,9 @@ function resolveTy(ty) {
1882
1905
  if (ty.kind === "user" && !_declaredTypes.has(ty.name))
1883
1906
  return { kind: "string" };
1884
1907
  if (ty.kind === "optional")
1885
- return { kind: "optional", inner: resolveTy(ty.inner) };
1908
+ return { ...ty, inner: resolveTy(ty.inner) };
1909
+ if (ty.kind === "nullish")
1910
+ return { kind: "nullish", inner: resolveTy(ty.inner) };
1886
1911
  if (ty.kind === "array")
1887
1912
  return { kind: "array", elem: resolveTy(ty.elem) };
1888
1913
  if (ty.kind === "tuple")
@@ -1916,7 +1941,13 @@ function qualifyCtor(name, type) {
1916
1941
  * literal value → quoted Dafny string
1917
1942
  * "_" → "_"
1918
1943
  */
1919
- const CTOR_MAP = { "some": "Some", "none": "None" };
1944
+ const CTOR_MAP = {
1945
+ "some": "Some",
1946
+ "none": "None",
1947
+ "nullishUndefined": "Undefined",
1948
+ "nullishNull": "Null",
1949
+ "nullishValue": "Value",
1950
+ };
1920
1951
  function translatePattern(p) {
1921
1952
  if (p.kind === "wild")
1922
1953
  return "_";
@@ -1925,7 +1956,7 @@ function translatePattern(p) {
1925
1956
  const ctorName = (Object.hasOwn(CTOR_MAP, p.ctor) ? CTOR_MAP[p.ctor] : undefined) ?? dafnyCtorName(p.ctor);
1926
1957
  if (p.binders.length === 0)
1927
1958
  return ctorName;
1928
- return `${ctorName}(${p.binders.map(escapeName).join(", ")})`;
1959
+ return `${ctorName}(${p.binders.map(b => b === "_" ? "_" : escapeName(b)).join(", ")})`;
1929
1960
  }
1930
1961
  export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
1931
1962
  // Programmatic callers share the CLI's compatibility checks.
@@ -419,7 +419,7 @@ const OTHER_LINE_BREAK = /[\r\u2028\u2029]/;
419
419
  */
420
420
  export function proofAdditionViolations(generated, proof, proofName) {
421
421
  const proofLines = proof.split("\n");
422
- const genLines = generated.split("\n");
422
+ const genLines = generated === "" ? [] : generated.split("\n");
423
423
  const matched = matchGeneratedLines(genLines, proofLines);
424
424
  if (!matched)
425
425
  return [`${proofName}: generated lines are not contained in order in the proof`];
@@ -781,9 +781,10 @@ function extractExpr(node) {
781
781
  };
782
782
  }
783
783
  }
784
- // null → undefined (both map to None in backends)
784
+ // Preserve `null` distinctly from `undefined` so `T | null | undefined`
785
+ // (`Nullish<T>`) and single-sentinel `T | null` / `T | undefined` stay sound (#304).
785
786
  if (Node.isNullLiteral(node)) {
786
- return { kind: "var", name: "undefined" };
787
+ return { kind: "var", name: "null" };
787
788
  }
788
789
  // `typeof X` — only meaningful in a `typeof X === "string"` discriminator over
789
790
  // a synth `U | T[]` union (see narrow's parseTypeofStringCheck); any other use
@@ -1264,6 +1265,8 @@ function typeToString(type) {
1264
1265
  return "number";
1265
1266
  if (type.isUndefined())
1266
1267
  return "undefined";
1268
+ if (type.isNull())
1269
+ return "null";
1267
1270
  if (type.isNumber() || type.isNumberLiteral())
1268
1271
  return "number";
1269
1272
  if (type.isBigInt() || type.isBigIntLiteral())
@@ -1331,9 +1334,17 @@ function typeToString(type) {
1331
1334
  if (real.length <= 1)
1332
1335
  return parts.join(" | ");
1333
1336
  // A genuine multi-member union with no tagged-union shape LS can model →
1334
- // a single opaque type. (See _synthOpaque.) Preserve an outer optional.
1337
+ // a single opaque type. (See _synthOpaque.) Preserve outer null/undefined.
1335
1338
  const opaque = _synthOpaque(real);
1336
- return real.length === parts.length ? opaque : `${opaque} | undefined`;
1339
+ const hasNull = parts.includes("null");
1340
+ const hasUndef = parts.includes("undefined");
1341
+ if (hasNull && hasUndef)
1342
+ return `${opaque} | null | undefined`;
1343
+ if (hasNull)
1344
+ return `${opaque} | null`;
1345
+ if (hasUndef)
1346
+ return `${opaque} | undefined`;
1347
+ return opaque;
1337
1348
  }
1338
1349
  if (type.isTuple()) {
1339
1350
  return `[${type.getTupleElements().map(t => typeToString(t)).join(", ")}]`;
@@ -3059,16 +3070,16 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
3059
3070
  // already-extracted `fn.returnType` string for nullish suffixes to detect
3060
3071
  // the wrap-in-Optional case.
3061
3072
  let innerType = null;
3062
- let wrapOptional = false;
3063
3073
  const sourceReturnText = fn.returnType ?? "";
3064
- const sourceHadNullish = / \| (null|undefined)$/.test(sourceReturnText)
3065
- || sourceReturnText.includes(" | null ") || sourceReturnText.includes(" | undefined ")
3066
- || sourceReturnText.includes(" | null|") || sourceReturnText.includes(" | undefined|");
3074
+ const sourceHasNull = /(^|\|\s*)null(\s*\||$)/.test(sourceReturnText);
3075
+ const sourceHasUndef = /(^|\|\s*)undefined(\s*\||$)/.test(sourceReturnText);
3076
+ let wrapNull = false;
3077
+ let wrapUndef = false;
3067
3078
  const sym = retType.getSymbol();
3068
3079
  if ((sym?.getName() === "__type" || sym?.getName() === "__object") && retType.isObject() && !retType.isArray()) {
3069
3080
  innerType = retType;
3070
- if (sourceHadNullish)
3071
- wrapOptional = true;
3081
+ wrapNull = sourceHasNull;
3082
+ wrapUndef = sourceHasUndef;
3072
3083
  }
3073
3084
  else if (retType.isUnion()) {
3074
3085
  const arms = retType.getUnionTypes();
@@ -3079,15 +3090,25 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
3079
3090
  const otherSym = onlyOther.getSymbol();
3080
3091
  if ((otherSym?.getName() === "__type" || otherSym?.getName() === "__object") && onlyOther.isObject() && !onlyOther.isArray()) {
3081
3092
  innerType = onlyOther;
3082
- wrapOptional = true;
3093
+ wrapNull = nullish.some(t => t.isNull());
3094
+ wrapUndef = nullish.some(t => t.isUndefined());
3083
3095
  }
3084
3096
  }
3085
3097
  }
3098
+ const formatReturnNullability = (base) => {
3099
+ if (wrapNull && wrapUndef)
3100
+ return `${base} | null | undefined`;
3101
+ if (wrapNull)
3102
+ return `${base} | null`;
3103
+ if (wrapUndef)
3104
+ return `${base} | undefined`;
3105
+ return base;
3106
+ };
3086
3107
  if (innerType) {
3087
3108
  // Try typeToString first — it resolves collapsed single-variant unions
3088
3109
  const resolved = typeToString(innerType);
3089
3110
  if (resolved !== "__type" && !resolved.includes("__type") && knownTypes.has(resolved)) {
3090
- fn.returnType = wrapOptional ? `${resolved} | undefined` : resolved;
3111
+ fn.returnType = formatReturnNullability(resolved);
3091
3112
  continue;
3092
3113
  }
3093
3114
  const synName = f.owner + fn.name.charAt(0).toUpperCase() + fn.name.slice(1) + "Result";
@@ -3100,7 +3121,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
3100
3121
  knownTypes.add(synName);
3101
3122
  }
3102
3123
  }
3103
- fn.returnType = wrapOptional ? `${synName} | undefined` : synName;
3124
+ fn.returnType = formatReturnNullability(synName);
3104
3125
  // Also resolve imported types referenced in the return type's fields
3105
3126
  for (const prop of innerType.getProperties()) {
3106
3127
  resolveType(prop.getTypeAtLocation(f.node), f.node);