lemmascript 0.6.10 → 0.6.12

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,468 @@
1
+ /**
2
+ * Check the lines a `.dfy` proof adds to its `.dfy.gen` companion for
3
+ * constructs that bypass verification or weaken generated contracts.
4
+ *
5
+ * Added lines may not contain `assume`, `expect`, `decreases *`, `{:axiom}`,
6
+ * `@Axiom`, `{:verify false}`, `{:only}`, `@VerifyOnly`, or `{:extern}`.
7
+ * Text inside comments (including nested block comments), strings (including
8
+ * verbatim strings), and character literals is ignored.
9
+ *
10
+ * Inside a generated declaration header (before its body `{` or the next
11
+ * declaration for bodyless declarations), added lines may introduce complete
12
+ * `ensures`, `modifies`, `reads`, or `decreases` clauses (other than
13
+ * `decreases *`), but may not add `requires` clauses or extend/split a
14
+ * generated signature or header clause. Auxiliary declarations added in the
15
+ * proof may declare their own `requires` and other clauses freely.
16
+ *
17
+ * Separately, added lines may not introduce an `// lsc options:` header,
18
+ * because verifier flags are read from that header in the proof, and may not
19
+ * contain line breaks other than `\n` (Dafny ends a `//` comment at `\r`).
20
+ * A generated line kept in the proof must lex to the same tokens it has in
21
+ * the generated file, so added comments or strings cannot disable it, and an
22
+ * added line may not repeat a generated verification-bypass line.
23
+ */
24
+ const OPERATORS = ["<==>", "==>", "<==", "==", "!=", "<=", ">=", ":=", "::", "->", "=>", "&&", "||", ".."];
25
+ /** Dafny identifiers may start with `'` or `?` (`?x` and `'x` are names). */
26
+ function isWordStart(ch) {
27
+ return /[A-Za-z0-9_'?]/.test(ch);
28
+ }
29
+ function isWordChar(ch) {
30
+ return /[A-Za-z0-9_'?]/.test(ch);
31
+ }
32
+ /** Tokenize Dafny source, dropping comments and collapsing literals to single tokens. */
33
+ export function lexDafny(text) {
34
+ const tokens = [];
35
+ let line = 0;
36
+ let i = 0;
37
+ const advance = (to) => {
38
+ for (; i < to && i < text.length; i++)
39
+ if (text[i] === "\n")
40
+ line++;
41
+ };
42
+ while (i < text.length) {
43
+ const ch = text[i];
44
+ const next = text[i + 1];
45
+ if (/\s/.test(ch)) {
46
+ advance(i + 1);
47
+ continue;
48
+ }
49
+ if (ch === "/" && next === "/") {
50
+ const end = text.indexOf("\n", i);
51
+ advance(end < 0 ? text.length : end);
52
+ continue;
53
+ }
54
+ if (ch === "/" && next === "*") {
55
+ let depth = 0;
56
+ let j = i;
57
+ while (j < text.length) {
58
+ if (text[j] === "/" && text[j + 1] === "*") {
59
+ depth++;
60
+ j += 2;
61
+ }
62
+ else if (text[j] === "*" && text[j + 1] === "/") {
63
+ depth--;
64
+ j += 2;
65
+ if (depth === 0)
66
+ break;
67
+ }
68
+ else
69
+ j++;
70
+ }
71
+ advance(j);
72
+ continue;
73
+ }
74
+ const start = line;
75
+ if (ch === "@" && next === "\"") {
76
+ let j = i + 2;
77
+ while (j < text.length) {
78
+ if (text[j] === "\"" && text[j + 1] === "\"")
79
+ j += 2;
80
+ else if (text[j] === "\"") {
81
+ j++;
82
+ break;
83
+ }
84
+ else
85
+ j++;
86
+ }
87
+ tokens.push({ text: "\"\"", line: start });
88
+ advance(j);
89
+ continue;
90
+ }
91
+ if (ch === "\"") {
92
+ let j = i + 1;
93
+ while (j < text.length && text[j] !== "\"" && text[j] !== "\n")
94
+ j += text[j] === "\\" ? 2 : 1;
95
+ tokens.push({ text: "\"\"", line: start });
96
+ advance(j + 1);
97
+ continue;
98
+ }
99
+ if (ch === "'") {
100
+ const literal = /^'(?:\\u\{[0-9A-Fa-f_]+\}|\\U\{[0-9A-Fa-f_]+\}|\\u[0-9A-Fa-f]{4}|\\.|[^'\\\n])'/u.exec(text.slice(i));
101
+ if (literal) {
102
+ tokens.push({ text: "''", line: start });
103
+ advance(i + literal[0].length);
104
+ continue;
105
+ }
106
+ }
107
+ if (isWordStart(ch)) {
108
+ let j = i + 1;
109
+ while (j < text.length && isWordChar(text[j]))
110
+ j++;
111
+ tokens.push({ text: text.slice(i, j), line: start });
112
+ advance(j);
113
+ continue;
114
+ }
115
+ if (ch === "{" && next === ":") {
116
+ tokens.push({ text: "{:", line: start });
117
+ advance(i + 2);
118
+ continue;
119
+ }
120
+ const op = OPERATORS.find(o => text.startsWith(o, i));
121
+ tokens.push({ text: op ?? ch, line: start });
122
+ advance(i + (op?.length ?? 1));
123
+ }
124
+ return tokens;
125
+ }
126
+ /**
127
+ * Map each proof line to the generated line it keeps, or -1 for an added
128
+ * line, matching each generated line to the earliest equal proof line.
129
+ * Returns undefined when the generated lines do not all appear in order.
130
+ */
131
+ function matchGeneratedLines(genLines, proofLines) {
132
+ const matched = [];
133
+ let g = 0;
134
+ for (const line of proofLines) {
135
+ const generated = g < genLines.length && line === genLines[g];
136
+ matched.push(generated ? g++ : -1);
137
+ }
138
+ return g === genLines.length ? matched : undefined;
139
+ }
140
+ /** Token texts starting on each line, joined with a separator. */
141
+ function tokensByLine(tokens, lineCount) {
142
+ const lines = Array.from({ length: lineCount }, () => []);
143
+ for (const t of tokens)
144
+ lines[t.line]?.push(t.text);
145
+ return lines.map(l => l.join("\u0000"));
146
+ }
147
+ /** Whether a token sequence bypasses verification or assumes an unproved fact. */
148
+ function trustsFact(tokens, k) {
149
+ const t = tokens[k].text, following = tokens[k + 1]?.text;
150
+ if (t === "assume")
151
+ return { reason: "assume statements are not allowed in proof additions; prove the fact instead", end: k };
152
+ if (t === "expect")
153
+ return { reason: "expect statements are not allowed in proof additions; prove the fact instead", end: k };
154
+ if (t === "decreases" && following === "*")
155
+ return { reason: "`decreases *` is not allowed in proof additions; provide a termination metric instead", end: k + 1 };
156
+ if (t === "{:" && following === "axiom")
157
+ return { reason: "{:axiom} attributes are not allowed in proof additions; give the declaration a proof or body", end: k + 1 };
158
+ if (t === "@" && following === "Axiom")
159
+ return { reason: "@Axiom attributes are not allowed in proof additions; give the declaration a proof or body", end: k + 1 };
160
+ if (t === "{:" && following === "verify" && !(tokens[k + 2]?.text === "true" && tokens[k + 3]?.text === "}")) {
161
+ const close = findMatchingBrace(tokens, k);
162
+ return {
163
+ reason: "{:verify ...} attributes that disable verification are not allowed in proof additions",
164
+ end: close >= 0 ? close : k + 1,
165
+ };
166
+ }
167
+ if (t === "{:" && following === "only")
168
+ return { reason: "{:only} attributes are not allowed in proof additions; they skip verification of other declarations", end: k + 1 };
169
+ if (t === "@" && following === "VerifyOnly")
170
+ return { reason: "@VerifyOnly attributes are not allowed in proof additions; they skip verification of other declarations", end: k + 1 };
171
+ if (t === "{:" && following === "extern")
172
+ return { reason: "{:extern} attributes are not allowed in proof additions; declare externs in TypeScript with //@ extern", end: k + 1 };
173
+ return undefined;
174
+ }
175
+ const CALLABLE_KEYWORDS = new Set(["method", "lemma", "function", "predicate", "constructor"]);
176
+ const DECL_MODIFIERS = new Set(["ghost", "twostate", "least", "greatest", "static", "opaque", "protected", "abstract"]);
177
+ const CONTAINER_KEYWORDS = new Set(["class", "trait", "module"]);
178
+ const NON_CALLABLE_DECLS = new Set([
179
+ "datatype", "codatatype", "type", "newtype", "class", "trait", "module",
180
+ "const", "import", "include", "export",
181
+ ]);
182
+ const SPEC_CLAUSE_KEYWORDS = new Set(["requires", "ensures", "reads", "modifies", "decreases"]);
183
+ const ALLOWED_ADDED_HEADER_CLAUSES = new Set(["ensures", "reads", "modifies", "decreases"]);
184
+ /** Whether `tokens[k]` is a modifier prefixing a declaration (not an identifier like `least` in an expression). */
185
+ function isDeclModifierAt(tokens, k) {
186
+ let i = k;
187
+ while (i < tokens.length && DECL_MODIFIERS.has(tokens[i].text))
188
+ i++;
189
+ if (i === k || i >= tokens.length)
190
+ return false;
191
+ const next = tokens[i].text;
192
+ return CALLABLE_KEYWORDS.has(next) || NON_CALLABLE_DECLS.has(next) || next === "var";
193
+ }
194
+ /** Tokens after a closing `}` that show `{ ... }` was a set literal inside a header, not a body. */
195
+ const HEADER_CONTINUATION_AFTER_BRACE = new Set([
196
+ "requires", "ensures", "reads", "modifies", "decreases", "{",
197
+ "==", "!=", "<", "<=", ">", ">=", "+", "-", "*", "/", "%",
198
+ "&&", "||", "==>", "<==", "<==>", "in", "!", ".", "[", "(", ")", "]", ",", "?", ":", "::", "|", ";",
199
+ "then", "else", "as", "is",
200
+ ]);
201
+ /** Tokens before `{` inside a spec clause that unambiguously introduce a set/multiset literal. */
202
+ const EXPR_BEFORE_BRACE = new Set([
203
+ "requires", "ensures", "reads", "modifies", "decreases",
204
+ "==", "!=", "<=", ">=", "<", "+", "-", "/", "%",
205
+ "&&", "||", "==>", "<==", "<==>", "!", "in", "::", ":=",
206
+ "then", "else", "iset", "multiset", "set",
207
+ ]);
208
+ /** Return the index of the `}` matching `tokens[openIdx]` (`{` or `{:`), or -1. */
209
+ function findMatchingBrace(tokens, openIdx) {
210
+ let depth = 0;
211
+ for (let i = openIdx; i < tokens.length; i++) {
212
+ const text = tokens[i].text;
213
+ if (text === "{" || text === "{:")
214
+ depth++;
215
+ else if (text === "}") {
216
+ depth--;
217
+ if (depth === 0)
218
+ return i;
219
+ }
220
+ }
221
+ return -1;
222
+ }
223
+ /** Whether `{` at `openIdx` inside a declaration header is a set/multiset literal rather than the body `{`. */
224
+ function isHeaderExprBrace(tokens, openIdx, inSpecClause) {
225
+ const closeIdx = findMatchingBrace(tokens, openIdx);
226
+ const afterClose = closeIdx >= 0 ? tokens[closeIdx + 1]?.text : undefined;
227
+ if (afterClose !== undefined && HEADER_CONTINUATION_AFTER_BRACE.has(afterClose))
228
+ return true;
229
+ const prev = openIdx > 0 ? tokens[openIdx - 1]?.text : undefined;
230
+ if (inSpecClause && prev !== undefined && EXPR_BEFORE_BRACE.has(prev))
231
+ return true;
232
+ return false;
233
+ }
234
+ /**
235
+ * Check generated callable declaration headers for added `requires` clauses,
236
+ * added continuations that alter a generated signature or clause, and added
237
+ * clauses that split a multi-line generated clause.
238
+ */
239
+ function checkGeneratedHeaders(tokens, added, report) {
240
+ let parenDepth = 0;
241
+ let bracketDepth = 0;
242
+ const braceStack = [];
243
+ let pendingContainer = false;
244
+ let inGenHeader = false;
245
+ let inAddedHeader = false;
246
+ let headerSawCallable = false;
247
+ let headerHasName = false;
248
+ let inSpecClause = false;
249
+ let inAddedClause = false;
250
+ let declContainerDepth = 0;
251
+ const reportedExtendLines = new Set();
252
+ const resetHeader = () => {
253
+ inGenHeader = false;
254
+ inAddedHeader = false;
255
+ headerSawCallable = false;
256
+ headerHasName = false;
257
+ inSpecClause = false;
258
+ inAddedClause = false;
259
+ };
260
+ for (let k = 0; k < tokens.length; k++) {
261
+ const t = tokens[k];
262
+ const text = t.text;
263
+ const isAdded = added[t.line];
264
+ const prev = k > 0 ? tokens[k - 1].text : undefined;
265
+ if (text === "{:") {
266
+ braceStack.push("attr");
267
+ continue;
268
+ }
269
+ if (text === "{") {
270
+ const inNonContainer = braceStack.some(b => b !== "container");
271
+ if (parenDepth > 0 || bracketDepth > 0 || inNonContainer) {
272
+ braceStack.push("expr");
273
+ }
274
+ else if (pendingContainer) {
275
+ pendingContainer = false;
276
+ resetHeader();
277
+ braceStack.push("container");
278
+ }
279
+ else if ((inGenHeader || inAddedHeader) && isHeaderExprBrace(tokens, k, inSpecClause)) {
280
+ if (inGenHeader && isAdded && !inAddedClause && !reportedExtendLines.has(t.line)) {
281
+ reportedExtendLines.add(t.line);
282
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
283
+ }
284
+ braceStack.push("expr");
285
+ }
286
+ else {
287
+ resetHeader();
288
+ braceStack.push("body");
289
+ }
290
+ continue;
291
+ }
292
+ if (text === "}") {
293
+ braceStack.pop();
294
+ continue;
295
+ }
296
+ const inNonContainer = braceStack.some(b => b !== "container");
297
+ const atDeclLevel = parenDepth === 0 && bracketDepth === 0 && !inNonContainer;
298
+ if (text === "(") {
299
+ if (inGenHeader && isAdded && !inAddedClause && !reportedExtendLines.has(t.line)) {
300
+ reportedExtendLines.add(t.line);
301
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
302
+ }
303
+ parenDepth++;
304
+ continue;
305
+ }
306
+ if (text === ")") {
307
+ if (parenDepth > 0)
308
+ parenDepth--;
309
+ if (inGenHeader && isAdded && !inAddedClause && !reportedExtendLines.has(t.line)) {
310
+ reportedExtendLines.add(t.line);
311
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
312
+ }
313
+ continue;
314
+ }
315
+ if (text === "[") {
316
+ if (inGenHeader && isAdded && !inAddedClause && !reportedExtendLines.has(t.line)) {
317
+ reportedExtendLines.add(t.line);
318
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
319
+ }
320
+ bracketDepth++;
321
+ continue;
322
+ }
323
+ if (text === "]") {
324
+ if (bracketDepth > 0)
325
+ bracketDepth--;
326
+ if (inGenHeader && isAdded && !inAddedClause && !reportedExtendLines.has(t.line)) {
327
+ reportedExtendLines.add(t.line);
328
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
329
+ }
330
+ continue;
331
+ }
332
+ if (atDeclLevel && prev !== ".") {
333
+ // `by method {` follows a function body and is not a new method declaration.
334
+ if (text === "method" && prev === "by")
335
+ continue;
336
+ if (NON_CALLABLE_DECLS.has(text)) {
337
+ resetHeader();
338
+ pendingContainer = CONTAINER_KEYWORDS.has(text);
339
+ continue;
340
+ }
341
+ if (text === "var" && !headerSawCallable) {
342
+ resetHeader();
343
+ pendingContainer = false;
344
+ continue;
345
+ }
346
+ if (CALLABLE_KEYWORDS.has(text) || isDeclModifierAt(tokens, k)) {
347
+ pendingContainer = false;
348
+ if ((!inGenHeader && !inAddedHeader) || headerHasName) {
349
+ inGenHeader = !isAdded;
350
+ inAddedHeader = isAdded;
351
+ headerSawCallable = CALLABLE_KEYWORDS.has(text);
352
+ headerHasName = false;
353
+ inSpecClause = false;
354
+ inAddedClause = false;
355
+ declContainerDepth = braceStack.length;
356
+ }
357
+ else {
358
+ if (CALLABLE_KEYWORDS.has(text))
359
+ headerSawCallable = true;
360
+ if (!isAdded) {
361
+ inGenHeader = true;
362
+ inAddedHeader = false;
363
+ }
364
+ }
365
+ continue;
366
+ }
367
+ if ((inGenHeader || inAddedHeader) && headerSawCallable && !headerHasName) {
368
+ headerHasName = true;
369
+ if (!inGenHeader)
370
+ continue;
371
+ }
372
+ }
373
+ if (!inGenHeader)
374
+ continue;
375
+ const atHeaderClauseLevel = parenDepth === 0 && bracketDepth === 0 && braceStack.length === declContainerDepth;
376
+ if (!isAdded) {
377
+ if (atHeaderClauseLevel) {
378
+ if (SPEC_CLAUSE_KEYWORDS.has(text)) {
379
+ inSpecClause = true;
380
+ inAddedClause = false;
381
+ }
382
+ else if (inAddedClause) {
383
+ report(t.line, "an added clause splits a generated header clause");
384
+ inAddedClause = false;
385
+ }
386
+ }
387
+ continue;
388
+ }
389
+ // Token is on an added line inside a generated declaration header.
390
+ if (atHeaderClauseLevel) {
391
+ if (text === "requires") {
392
+ report(t.line, "added requires clauses are not allowed in generated declaration headers; strengthen preconditions in TypeScript instead");
393
+ inSpecClause = true;
394
+ // Suppress follow-on continuation diagnostics for the body of this rejected clause.
395
+ inAddedClause = true;
396
+ }
397
+ else if (ALLOWED_ADDED_HEADER_CLAUSES.has(text)) {
398
+ inSpecClause = true;
399
+ inAddedClause = true;
400
+ }
401
+ else if (!inAddedClause && !reportedExtendLines.has(t.line)) {
402
+ reportedExtendLines.add(t.line);
403
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
404
+ }
405
+ }
406
+ else if (!inAddedClause && !reportedExtendLines.has(t.line)) {
407
+ reportedExtendLines.add(t.line);
408
+ report(t.line, "added lines in a generated declaration header must start a new ensures, modifies, reads, or decreases clause and may not extend a generated signature or clause");
409
+ }
410
+ }
411
+ }
412
+ /** Matches the header `dafnyVerifyArgs` reads verifier options from. */
413
+ const LSC_OPTIONS_HEADER = /^\/\/ lsc options:/m;
414
+ /** Line terminators other than `\n` that Dafny or a header regex may honor. */
415
+ const OTHER_LINE_BREAK = /[\r\u2028\u2029]/;
416
+ /**
417
+ * Check the proof additions, returning one diagnostic per rejected construct.
418
+ * Diagnostics name the 1-based proof line, the reason, and the line text.
419
+ */
420
+ export function proofAdditionViolations(generated, proof, proofName) {
421
+ const proofLines = proof.split("\n");
422
+ const genLines = generated.split("\n");
423
+ const matched = matchGeneratedLines(genLines, proofLines);
424
+ if (!matched)
425
+ return [`${proofName}: generated lines are not contained in order in the proof`];
426
+ const added = matched.map(g => g < 0);
427
+ const violations = [];
428
+ const report = (line, reason) => violations.push(`${proofName}:${line + 1}: ${reason}: ${proofLines[line].trim()}`);
429
+ const tokens = lexDafny(proof);
430
+ for (let k = 0; k < tokens.length; k++) {
431
+ const match = trustsFact(tokens, k);
432
+ if (!match)
433
+ continue;
434
+ let addedLine = -1;
435
+ for (let j = k; j <= match.end && j < tokens.length; j++) {
436
+ if (added[tokens[j].line]) {
437
+ addedLine = tokens[j].line;
438
+ break;
439
+ }
440
+ }
441
+ if (addedLine >= 0)
442
+ report(addedLine, match.reason);
443
+ }
444
+ checkGeneratedHeaders(tokens, added, report);
445
+ const genTokens = lexDafny(generated);
446
+ const trustedGenLines = new Set();
447
+ for (let k = 0; k < genTokens.length; k++) {
448
+ if (trustsFact(genTokens, k))
449
+ trustedGenLines.add(genLines[genTokens[k].line]);
450
+ }
451
+ const proofLineTokens = tokensByLine(tokens, proofLines.length);
452
+ const genLineTokens = tokensByLine(genTokens, genLines.length);
453
+ proofLines.forEach((text, line) => {
454
+ const g = matched[line];
455
+ if (g >= 0) {
456
+ if (proofLineTokens[line] !== genLineTokens[g])
457
+ report(line, "added text changes how this generated line is read (for example, by placing it inside a comment or string)");
458
+ return;
459
+ }
460
+ if (OTHER_LINE_BREAK.test(text))
461
+ report(line, "added lines may only use `\\n` line breaks; Dafny ends a `//` comment at `\\r`");
462
+ if (LSC_OPTIONS_HEADER.test(text))
463
+ report(line, "an added `// lsc options:` line would change verifier options; options come from the generated file");
464
+ if (trustedGenLines.has(text))
465
+ report(line, "added lines may not repeat a generated assume, axiom, or verification-bypass line; keep the generated line in place");
466
+ });
467
+ return violations;
468
+ }