agent-formal-verify 0.4.13 → 0.4.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.
@@ -13,10 +13,12 @@ change, and so is an added item whose kind narrows what is checked.
13
13
  and the normalized definitions of Spec,
14
14
  of each operator a check or reach line names, and of the operators those
15
15
  reference through local EXTENDS. Local INSTANCE substitutions retain their whole module tree.
16
- .rs Kani. Each qualified harness name with the #[cfg(...)] attributes other
16
+ .rs Kani. Each qualified harness name with its #[kani::should_panic] and
17
+ #[kani::unwind(...)] attributes and the #[cfg(...)] attributes other
17
18
  than cfg(kani), and the #[cfg_attr(..., cfg(...))] ones, on it, its enclosing
18
19
  items, the file and each out-of-line mod declaration that leads to the file from a crate root, through
19
- #[path], and each kani::assume, kani::any_where, kani::cover! and
20
+ #[path], with each route in the file's crates that the record cannot read, such as a mod
21
+ declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
20
22
  #[kani::stub] with its owning free function, under inline modules. Unsupported owners fail. Added covers and harnesses are allowed.
21
23
  Added assumes and stubs are changes.
22
24
  In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
@@ -30,55 +32,28 @@ Usage:
30
32
  compare old's entry with new from now on
31
33
 
32
34
  Compare prints UNCHANGED or CHANGED per file, indented lines for each item that
33
- changed, and a SUMMARY line. Move prints MOVED; it reads only the record, never
35
+ changed, and a SUMMARY line. It prints NOT CHECKED for an unchanged Kani file in a
36
+ Cargo package that record could not check against Kani. Move prints MOVED; it reads only the record, never
34
37
  the new file, and with --module renames the recorded Kani owners under module
35
38
  OLD to sit under NEW. Exit codes: 0 unchanged, 1 changed or a record or model
36
39
  file that fails to parse, 2 usage error.
37
40
  """
38
41
  import argparse
39
- import functools
40
42
  import hashlib
41
43
  import json
42
- import os
43
44
  import re
44
45
  import sys
45
- import tempfile
46
46
  from pathlib import Path
47
- from typing import NamedTuple
48
47
 
49
48
  sys.dont_write_bytecode = True
50
49
 
51
- import kani
52
50
  import runner
53
- import storage
54
51
  import tlc
52
+ from kani_reader import KANI_KEY, RouteReader, compiled_problems, kani_surface
55
53
  from lean_records import read_record as read_lean_record
54
+ from surface import STRING, Surface, collapse
56
55
 
57
56
  FORMAT = 2
58
- NARROWING = {"lean": (), "tla": (), "kani": ("assume", "stub")}
59
- KINDS = {".statements": "lean", ".matrix": "tla", ".rs": "kani"}
60
- STRING = re.compile(r'"(?:\\.|[^"\\])*"', re.DOTALL)
61
-
62
-
63
- def collapse(text, literals=None):
64
- if literals is None:
65
- literals = (match.span() for match in STRING.finditer(text))
66
- parts, end = [], 0
67
- for start, stop in literals:
68
- parts.extend((re.sub(r"\s+", " ", text[end:start]), text[start:stop]))
69
- end = stop
70
- parts.append(re.sub(r"\s+", " ", text[end:]))
71
- return "".join(parts).strip()
72
-
73
-
74
- class Surface(dict):
75
- def add(self, name, value=""):
76
- candidate, count = name, 1
77
- while candidate in self:
78
- count += 1
79
- candidate = f"{name} #{count}"
80
- self[candidate] = value
81
- return candidate
82
57
 
83
58
 
84
59
  def lean_surface(path):
@@ -298,565 +273,147 @@ def tla_surface(path):
298
273
  return surface
299
274
 
300
275
 
301
- class RustSource(NamedTuple):
302
- uncommented: str
303
- without_comments_or_strings: str
304
- literals: list
305
-
306
-
307
- def rust_masks(source):
308
- text, mask = list(source), list(source)
309
- literals = []
310
-
311
- def blank(start, end, *, both):
312
- for i in range(start, end):
313
- if source[i] != "\n":
314
- mask[i] = " "
315
- if both:
316
- text[i] = " "
317
-
318
- i = 0
319
- while i < len(source):
320
- if source.startswith("//", i):
321
- end = source.find("\n", i)
322
- end = len(source) if end < 0 else end
323
- blank(i, end, both=True)
324
- i = end
325
- elif source.startswith("/*", i):
326
- depth, start = 0, i
327
- while i < len(source):
328
- if source.startswith("/*", i):
329
- depth, i = depth + 1, i + 2
330
- elif source.startswith("*/", i):
331
- depth, i = depth - 1, i + 2
332
- if not depth:
333
- break
334
- else:
335
- i += 1
336
- blank(start, i, both=True)
337
- elif raw := re.compile(r'(?<!\w)[bc]?r(#*)"').match(source, i):
338
- close = source.find('"' + raw[1], raw.end())
339
- content_end = len(source) if close < 0 else close
340
- blank(raw.end(), content_end, both=False)
341
- i = content_end + 1 + len(raw[1])
342
- literals.append((raw.start(), min(i, len(source))))
343
- elif source[i] == '"':
344
- opening = i
345
- start = i = i + 1
346
- while i < len(source) and source[i] != '"':
347
- i += 2 if source[i] == "\\" else 1
348
- blank(start, min(i, len(source)), both=False)
349
- i += 1
350
- literals.append((opening, min(i, len(source))))
351
- elif char := re.compile(r"'(?:\\.[^']*|[^'\\])'").match(source, i):
352
- blank(char.start() + 1, char.end() - 1, both=False)
353
- i = char.end()
354
- literals.append(char.span())
355
- else:
356
- i += 1
357
- return RustSource("".join(text), "".join(mask), literals)
358
-
359
-
360
- def after_closing(mask, opener):
361
- closer = {"(": ")", "[": "]", "{": "}"}[mask[opener]]
362
- depth = 0
363
- for i in range(opener, len(mask)):
364
- depth += (mask[i] == mask[opener]) - (mask[i] == closer)
365
- if not depth:
366
- return i + 1
367
- raise ValueError(f"unbalanced {mask[opener]} at offset {opener}")
368
-
369
-
370
- class RustFunction(NamedTuple):
371
- name: str
372
- start: int
373
- keyword: int
374
- body: int
375
- end: int
376
-
377
-
378
- RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
379
- INCLUDE = re.compile(r"\binclude\s*!$")
380
-
381
-
382
- def rust_functions(mask):
383
- """Locate free functions, inline modules, out-of-line `mod name;` declarations and `include!(...)` items outside
384
- function bodies; leave macro and other item bodies opaque.
385
-
386
- A declaration's or an include's body is its `;`.
387
- """
388
- functions, modules, opaque, declarations, includes, counts = [], [], [], [], [], {}
389
-
390
- def add_include(boundary, header, stop, in_body):
391
- if not in_body and (include := INCLUDE.search(header)):
392
- semicolon = re.compile(r"\s*;").match(mask, stop)
393
- includes.append(RustFunction("include", boundary, boundary + include.start(), semicolon.end() - 1 if semicolon else stop - 1, stop))
394
-
395
- def walk(start, end, namespace=(), in_function=False, in_body=False):
396
- i, boundary, item = start, start, None
397
- while i < end:
398
- if match := RUST_ITEM.match(mask, i):
399
- item = (match[1], match[2], match.start())
400
- i = match.end()
401
- elif mask[i] in "([":
402
- stop = after_closing(mask, i)
403
- header = mask[boundary:i].rstrip()
404
- if header.endswith("!"):
405
- opaque.append((i, stop))
406
- add_include(boundary, header, stop, in_body)
407
- i = stop
408
- elif mask[i] == "{":
409
- stop = after_closing(mask, i)
410
- header = mask[boundary:i].rstrip()
411
- macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
412
- if item and not macro:
413
- kind, name, keyword = item
414
- qualified = (*namespace, name)
415
- if kind == "fn":
416
- owner = "::".join(qualified)
417
- counts[owner] = counts.get(owner, 0) + 1
418
- suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
419
- functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop))
420
- else:
421
- modules.append(RustFunction("::".join(qualified), boundary, keyword, i, stop))
422
- walk(i + 1, stop - 1, qualified, kind == "fn", in_body or kind == "fn")
423
- elif in_function and not macro and not re.search(r"\b(?:impl|trait|struct|enum|union|extern|macro)\b", header):
424
- walk(i + 1, stop - 1, namespace, True, True)
425
- else:
426
- opaque.append((i, stop))
427
- add_include(boundary, header, stop, in_body)
428
- i = boundary = stop
429
- item = None
430
- else:
431
- if mask[i] == ";":
432
- if item and item[0] == "mod" and not in_body:
433
- declarations.append(RustFunction("::".join((*namespace, item[1])), boundary, item[2], i, i + 1))
434
- boundary, item = i + 1, None
435
- i += 1
436
-
437
- walk(0, len(mask))
438
- return functions, modules, opaque, declarations, includes
439
-
440
-
441
- KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
442
- MACROS = (
443
- ("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
444
- ("assume", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
445
- ("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
446
- ("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
447
- )
448
- PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\s*\]")
449
- KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof)\w*\b")
450
- ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
451
- INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
452
- RENAMING_IMPORT = re.compile(r"\buse\s+[^;]*?(?<![\w:])(?:::\s*)?kani\b[^;]*?(?:\bas\b|\*|\b(?:assume|any_where|cover|stub|proof)\w*\b)|\bextern\s+crate\s+kani\s+as\b")
453
-
454
-
455
- def applies_cfg(attribute):
456
- """Return whether a compact `cfg_attr(predicate, attribute, ...)` applies a cfg or a module path in its own
457
- attribute list."""
458
- arguments, depth, start = [], 0, len("cfg_attr(")
459
- for i in range(start, len(attribute) - 1):
460
- depth += (attribute[i] in "([{") - (attribute[i] in ")]}")
461
- if attribute[i] == "," and not depth:
462
- arguments.append(attribute[start:i])
463
- start = i + 1
464
- arguments.append(attribute[start:-1])
465
- return any(argument.startswith(("cfg(", "path=")) or argument.startswith("cfg_attr(") and applies_cfg(argument) for argument in arguments[1:])
466
-
467
-
468
- def outer_attributes(source, start, keyword):
469
- """Yield the contents of each top-level outer attribute between start and keyword; skip inner attributes."""
470
- mask = source.without_comments_or_strings
471
- while attribute := ATTRIBUTE.search(mask, start, keyword):
472
- opener = attribute.end() - 1
473
- start = after_closing(mask, opener)
474
- if not attribute[1]:
475
- yield rust_masks(source.uncommented[opener + 1:start - 1])
476
-
477
-
478
- def cfg_guards(source, items):
479
- """Return the cfg attributes other than cfg(kani), and the cfg_attr ones whose attribute list applies a cfg or a
480
- module path, on each (start, keyword, body) item, between its start and its fn or mod keyword, and at the start
481
- of its body.
482
-
483
- A body of -1 stands for the file, which has only inner attributes, and a body at a `;` for an out-of-line `mod`
484
- declaration, which has none. An attribute nested inside another attribute's tokens is not read.
485
- """
486
- text, mask = source.uncommented, source.without_comments_or_strings
487
- guards = []
488
-
489
- def read(attribute):
490
- compact = re.sub(r"\s+", "", attribute.without_comments_or_strings)
491
- if compact.startswith("cfg(") and compact != "cfg(kani)" or compact.startswith("cfg_attr(") and applies_cfg(compact):
492
- guards.append(collapse(attribute.uncommented, attribute.literals))
493
-
494
- for start, keyword, body in items:
495
- if body >= 0:
496
- for attribute in outer_attributes(source, start, keyword):
497
- read(attribute)
498
- if body >= 0 and mask[body] == ";":
499
- continue
500
- inner = body + 1
501
- while attribute := INNER_ATTRIBUTE.match(mask, inner):
502
- opener = attribute.end() - 1
503
- inner = after_closing(mask, opener)
504
- read(rust_masks(text[opener + 1:inner - 1]))
505
- return " ".join(guards)
506
-
507
-
508
- PATH_ATTRIBUTE = re.compile(r"\bpath\s*=\s*")
509
-
510
-
511
- def module_paths(source, item, file):
512
- """Return the paths that `#[path = "..."]` sets on a module item, and those that a cfg_attr may set."""
513
- paths, conditional = [], []
514
- for attribute in outer_attributes(source, item.start, item.keyword):
515
- compact = re.sub(r"\s+", "", attribute.without_comments_or_strings)
516
- if not compact.startswith(("path=", "cfg_attr(")):
517
- continue
518
- for setting in PATH_ATTRIBUTE.finditer(attribute.without_comments_or_strings):
519
- value = string_value(next((attribute.uncommented[begin:end] for begin, end in attribute.literals if begin == setting.end()), ""))
520
- if value is None:
521
- line = source.without_comments_or_strings.count("\n", 0, item.start) + 1
522
- raise ValueError(f"{file}:{line}: cannot read the path in '{collapse(attribute.uncommented, attribute.literals)}'; write it as a string without escapes")
523
- (paths if compact.startswith("path=") else conditional).append(value)
524
- return paths, conditional
525
-
526
-
527
- def string_value(literal):
528
- """Return the value of a Rust string literal without escapes, or None."""
529
- plain = re.fullmatch(r'r(#*)"(.*)"\1', literal, re.DOTALL) or re.fullmatch(r'"([^"\\]*)"', literal)
530
- return plain[plain.lastindex] if plain else None
531
-
532
-
533
- class RustFile(NamedTuple):
534
- source: RustSource
535
- modules: list
536
- declarations: list
537
- includes: list
538
-
539
-
540
- PARSED = {}
541
-
542
-
543
- def parse_rust(path):
544
- if path not in PARSED:
545
- source = rust_masks(path.read_text(encoding="utf-8"))
546
- _, modules, _, declarations, includes = rust_functions(source.without_comments_or_strings)
547
- PARSED[path] = RustFile(source, modules, declarations, includes)
548
- return PARSED[path]
276
+ class LeanKind:
277
+ """Record, compare and move the toolchain and declarations of a Lean statements file."""
549
278
 
279
+ name, suffix, renames = "lean", ".statements", False
550
280
 
551
- def enclosing_modules(parsed, item):
552
- return sorted((module for module in parsed.modules if module.start <= item.start < module.end), key=lambda module: module.start)
281
+ def entry(self, path):
282
+ return model_entry(self.name, lean_surface(path)), None
553
283
 
284
+ def changes(self, entry, path):
285
+ return differences(entry["surface"], lean_surface(path), ()), []
554
286
 
555
- def module_files(file, owner, parsed, declaration):
556
- """Yield each file that an out-of-line `mod` declaration in file may load, by rustc's rules, and whether that
557
- file owns its directory, as a crate root, a mod.rs or a `#[path]` file does."""
558
- states = [(file.parent, file.parent if owner else file.parent / file.stem)]
559
- for module in enclosing_modules(parsed, declaration):
560
- paths, conditional = module_paths(parsed.source, module, file)
561
- name = module.name.rsplit("::", 1)[-1].removeprefix("r#")
562
- states = [(child, child) for directory, prefix in states for child in ([] if paths else [prefix / name]) + [directory / path for path in paths + conditional]]
563
- paths, conditional = module_paths(parsed.source, declaration, file)
564
- name = declaration.name.rsplit("::", 1)[-1].removeprefix("r#")
565
- for directory, prefix in states:
566
- if not paths:
567
- yield prefix / f"{name}.rs", False
568
- yield prefix / name / "mod.rs", True
569
- for path in paths + conditional:
570
- yield directory / path, True
287
+ def valid(self, entry):
288
+ return True
571
289
 
290
+ def moved(self, entry, module, new, existing):
291
+ return model_entry(self.name, joined(entry["surface"], new, existing))
572
292
 
573
- def crate_roots(path):
574
- """Return the crate roots whose module trees may hold path, and those of them that Cargo names, or None for a
575
- file in no crate.
576
-
577
- They are the lib.rs and main.rs in the nearest directory above path that holds either and, in the Cargo package
578
- of the nearest directory above path with a Cargo.toml, Cargo's target files and each `.rs` path that Cargo.toml
579
- names.
580
- """
581
- marker = next((folder for folder in path.parents if (folder / "lib.rs").is_file() or (folder / "main.rs").is_file()), None)
582
- package = next((folder for folder in path.parents if (folder / "Cargo.toml").is_file()), None)
583
- if marker is None and package is None:
584
- return None
585
- markers = [marker / "lib.rs", marker / "main.rs"] if marker else []
586
- named = []
587
- if package:
588
- named += [package / "src/lib.rs", package / "src/main.rs"]
589
- for folder in ("src/bin", "tests", "examples", "benches"):
590
- named += sorted((package / folder).glob("*.rs")) + sorted((package / folder).glob("*/main.rs"))
591
- manifest = (package / "Cargo.toml").read_text(encoding="utf-8")
592
- named += [package / file for file in re.findall(r"""\bpath\s*=\s*["']([^"']+\.rs)["']""", manifest)]
593
- return tuple(dict.fromkeys(root.resolve() for root in markers + named if root.is_file())), {root.resolve() for root in named}
594
-
595
-
596
- CONCAT = re.compile(r"(?:\w+\s*::\s*)*concat\s*!\s*[(\[{]")
597
- MANIFEST_DIR = re.compile(r'(?:\w+\s*::\s*)*env\s*!\s*[(\[{]\s*"CARGO_MANIFEST_DIR"\s*,?\s*[)\]}]')
598
-
599
-
600
- def include_path(argument, file, package):
601
- """Return the file that the argument of an `include!` in file names, or None when the argument is neither a
602
- string without escapes nor a `concat!` of such strings and `env!("CARGO_MANIFEST_DIR")`, which is package,
603
- the directory of the Cargo.toml of the crate being compiled.
604
-
605
- Raises:
606
- ValueError: The argument uses `env!("CARGO_MANIFEST_DIR")` and package is None.
607
- """
608
- argument = argument.strip()
609
- if (value := string_value(argument)) is not None:
610
- return file.parent / value
611
- mask = rust_masks(argument).without_comments_or_strings
612
- if not (concat := CONCAT.match(mask)) or after_closing(mask, concat.end() - 1) != len(mask):
613
- return None
614
- parts, start, depth = [], concat.end(), 0
615
- for i in range(start, len(mask) - 1):
616
- depth += (mask[i] in "([{") - (mask[i] in ")]}")
617
- if mask[i] == "," and not depth:
618
- parts.append(argument[start:i].strip())
619
- start = i + 1
620
- parts.append(argument[start:-1].strip())
621
- pieces = []
622
- for part in filter(None, parts):
623
- if (value := string_value(part)) is not None:
624
- pieces.append(value)
625
- elif MANIFEST_DIR.fullmatch(part):
626
- if package is None:
627
- raise ValueError('no Cargo.toml above the crate root sets env!("CARGO_MANIFEST_DIR"), so the record cannot tell which file it reads')
628
- pieces.append(str(package))
629
- else:
630
- return None
631
- return file.parent / "".join(pieces)
632
-
633
-
634
- TREES = {}
635
-
636
-
637
- def module_tree(roots):
638
- """Return the module declarations that lead to each file the crate roots reach, as {file: {(declarer,
639
- declaration)}}, and the message for each reached file or declaration that could not be read.
640
-
641
- An `include!("...")` item outside function bodies leads to the file it names, relative to the including file,
642
- which declares modules as a file that owns its directory does, whatever inline modules hold the include.
643
- """
644
- if roots not in TREES:
645
- edges, broken, seen = {}, [], set()
646
- work = [(root, True, next((folder for folder in root.parents if (folder / "Cargo.toml").is_file()), None)) for root in roots]
647
- while work:
648
- file, owner, package = work.pop()
649
- if (file, owner, package) in seen:
650
- continue
651
- seen.add((file, owner, package))
652
- try:
653
- parsed = parse_rust(file)
654
- except ValueError as error:
655
- broken.append(f"{file}: {error}")
656
- continue
657
- for declaration in parsed.declarations:
658
- try:
659
- targets = list(module_files(file, owner, parsed, declaration))
660
- except ValueError as error:
661
- broken.append(str(error))
662
- continue
663
- for target, owns in targets:
664
- if target.is_file():
665
- target = target.resolve()
666
- edges.setdefault(target, set()).add((file, declaration))
667
- work.append((target, owns, package))
668
- for include in parsed.includes:
669
- invocation = rust_masks(parsed.source.uncommented[include.keyword:include.end])
670
- line = parsed.source.without_comments_or_strings.count("\n", 0, include.keyword) + 1
671
- shown = collapse(invocation.uncommented, invocation.literals)
672
- try:
673
- target = include_path(invocation.uncommented[invocation.without_comments_or_strings.index("!") + 1:].strip()[1:-1], file, package)
674
- except ValueError as error:
675
- broken.append(f"{file}:{line}: cannot read the path in '{shown}': {error}")
676
- continue
677
- if target is None:
678
- broken.append(f"{file}:{line}: cannot read the path in '{shown}'; write it as a string without escapes, or as concat! of such strings and env!(\"CARGO_MANIFEST_DIR\")")
679
- elif target.is_file():
680
- target = target.resolve()
681
- edges.setdefault(target, set()).add((file, include))
682
- work.append((target, True, package))
683
- TREES[roots] = edges, broken
684
- return TREES[roots]
685
-
686
-
687
- def declaration_guards(path):
688
- """Return the guards on the out-of-line `mod` declarations that lead to path from its crate roots, outermost
689
- first, and the module path that each route gives path's items, with "" for a crate root. A crate root is one
690
- route without guards, since its own crate always compiles it, unless it is a lib.rs or main.rs that Cargo does
691
- not name and another file declares, which makes it a module. For more than one route, the guards are
692
- `routes(...)` with each route as its crate root's path relative to path's directory, a colon and its guards,
693
- or `unguarded` for a route without any, sorted and separated by `; `.
694
-
695
- It follows each declaration from the crate roots by rustc's rules, including `#[path = "..."]` and each path
696
- that a cfg_attr may set, and each `include!("...")` item outside function bodies. It does not expand macros, so
697
- a declaration that a macro holds or builds is not a route it reads; `compiled_problems` checks those against the
698
- harnesses that Kani compiles. It fails for a file that no route it reads reaches, and names each reached file,
699
- declaration and `include!` that it could not read.
700
- """
701
- if (crates := crate_roots(path)) is None:
702
- return "", {""}
703
- roots, named = crates
704
- edges, broken = module_tree(roots)
705
- if path in roots and path not in edges:
706
- return "", {""}
707
- if path not in edges:
708
- unread = "".join(f"; {message}" for message in broken)
709
- raise ValueError(f"{path}: no module declaration that the record can read leads to this file from a crate root; declare it with `mod <name>;` or `#[path = \"...\"]` outside macros and function bodies, in a file that a crate root reaches{unread}")
710
-
711
- def routes(file, visiting):
712
- root = file in named or file in roots and all(declarer == file for declarer, _ in edges.get(file, ()))
713
- found = [(file, "", "")] if root else []
714
- for declarer, declaration in edges.get(file, ()):
715
- if declarer in visiting:
716
- continue
717
- parsed = parse_rust(declarer)
718
- enclosing = enclosing_modules(parsed, declaration)
719
- items = [(0, 0, -1)] + [(module.start, module.keyword, module.body) for module in enclosing] + [(declaration.start, declaration.keyword, declaration.body)]
720
- guards = cfg_guards(parsed.source, items)
721
- # An included file's items sit in the modules around the include!; a declared file's in its module.
722
- local = (enclosing[-1].name if enclosing else "") if declaration in parsed.includes else declaration.name
723
- found += [(start, " ".join(filter(None, (route, guards))), "::".join(filter(None, (module, local))))
724
- for start, route, module in routes(declarer, visiting | {declarer})]
725
- return found
726
-
727
- traced = routes(path, {path})
728
- modules = {module for _, _, module in traced}
729
- found = sorted((os.path.relpath(root, path.parent), guards) for root, guards, _ in traced)
730
- if len(found) == 1:
731
- return found[0][1], modules
732
- labelled = "; ".join(f"{root}: {guards or 'unguarded'}" for root, guards in found)
733
- return f"routes({labelled})", modules
734
-
735
-
736
- def kani_surface(path):
737
- source = rust_masks(path.read_text(encoding="utf-8"))
738
- text, mask = source.uncommented, source.without_comments_or_strings
739
- if renaming := RENAMING_IMPORT.search(mask):
740
- raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub or harness attribute in under another name; write each as kani::<name> so the record can read it")
741
- functions, modules, opaque, _, _ = rust_functions(mask)
742
- declared, _ = declaration_guards(path)
743
-
744
- def owner_at(position, *, attribute=False):
745
- if not any(start <= position < end for start, end in opaque):
746
- for function in reversed(functions):
747
- if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
748
- return function
749
- line = mask.count("\n", 0, position) + 1
750
- raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and impl or trait bodies")
751
-
752
- surface = Surface()
753
- spans, read = [], []
754
- for kind, pattern in MACROS:
755
- for match in pattern.finditer(mask):
756
- end = after_closing(mask, match.end() - 1)
757
- read.append((match.start(), end))
758
- argument = rust_masks(text[match.end():end - 1])
759
- owner = owner_at(match.start(), attribute=kind == "stub").name
760
- spans.append((match.start(), f"{kind} {collapse(argument.uncommented, argument.literals)} in {owner}", ""))
761
- for match in PROOF.finditer(mask):
762
- read.append(match.span())
763
- harness = owner_at(match.start(), attribute=True)
764
- enclosing = sorted((item for item in functions + modules if item.start <= harness.start and harness.end <= item.end), key=lambda item: item.start)
765
- guards = " ".join(filter(None, (declared, cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing]))))
766
- spans.append((match.start(), f"harness {harness.name}", guards))
767
- for token in KANI_TOKEN.finditer(mask):
768
- if not any(start <= token.start() < end for start, end in read):
769
- line = mask.count("\n", 0, token.start()) + 1
770
- raise ValueError(f"{path}:{line}: '{collapse(token[0])}' is in a form the record cannot read; write kani::assume(...), kani::any_where(...), kani::cover!(...), #[kani::stub(...)] or #[kani::proof], alone or under #[cfg_attr(kani, ...)]")
771
- for _, item, guards in sorted(spans):
772
- surface.add(item, guards)
773
- return surface
774
-
775
-
776
- @functools.cache
777
- def checker():
778
- return kani.Kani()
779
293
 
294
+ class TlaKind:
295
+ """Record, compare and move the checks of a TLA+ matrix and the specs it runs."""
780
296
 
781
- @functools.cache
782
- def compiled_in(package):
783
- """Return each harness that Kani compiles in the Cargo package at package.
297
+ name, suffix, renames = "tla", ".matrix", False
784
298
 
785
- Raises:
786
- ValueError: Kani is not installed, or cannot compile the package.
787
- """
788
- try:
789
- with tempfile.TemporaryDirectory(prefix="baseline-kani-", dir=storage.ensure_temp_root()) as work:
790
- return tuple(kani.compiled(package, Path(work), checker()))
791
- except (kani.CheckError, runner.Unavailable) as error:
792
- raise ValueError(f"cannot ask Kani which harnesses it compiles in {package}: {error}") from error
299
+ def entry(self, path):
300
+ return model_entry(self.name, tla_surface(path)), None
793
301
 
302
+ def changes(self, entry, path):
303
+ old, new = entry["surface"], tla_surface(path)
304
+ lines = []
305
+ if not any(name.startswith("imports ") for name in old):
306
+ lines.append(" previous baseline did not track imported modules; review and record this matrix again")
307
+ if "TLA+ layout version" not in old:
308
+ lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
309
+ return lines + differences(old, new, ()), []
794
310
 
795
- # A closure or a `const _` block puts an anonymous segment in Kani's name for a harness inside it.
796
- ANONYMOUS = re.compile(r"\{\w+#\d+\}|_")
311
+ def valid(self, entry):
312
+ return True
797
313
 
314
+ def moved(self, entry, module, new, existing):
315
+ return model_entry(self.name, joined(entry["surface"], new, existing))
798
316
 
799
- def item_path(name):
800
- return "::".join(part.removeprefix("r#") for part in name.split("::") if not ANONYMOUS.fullmatch(part))
801
317
 
318
+ class KaniKind:
319
+ """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
802
320
 
803
- def route_owner(name, modules, owners):
804
- """Return the owner in owners, keyed by item_path, that Kani's harness name gives under one of modules, or None.
321
+ name, suffix, renames = "kani", ".rs", True
805
322
 
806
- The name must start with the module path itself. Anonymous segments are dropped only after it, since no route
807
- that the record reads runs through a closure or a `const _` block.
808
- """
809
- parts = [part.removeprefix("r#") for part in name.split("::")]
810
- for module in modules:
811
- prefix = [part.removeprefix("r#") for part in module.split("::")] if module else []
812
- if parts[:len(prefix)] == prefix and (owner := owners.get(item_path("::".join(parts[len(prefix):])))):
813
- return owner
814
- return None
323
+ def __init__(self):
324
+ self.reader = RouteReader()
815
325
 
326
+ def entry(self, path):
327
+ surface = kani_surface(path, self.reader)
328
+ entry = model_entry(self.name, surface)
329
+ notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
330
+ # A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
331
+ try:
332
+ problems, names = compiled_problems(path, surface, self.reader)
333
+ except ValueError as error:
334
+ return entry, "\n".join([*notes, f" not checked against Kani: {error}"])
335
+ if problems:
336
+ raise ValueError(f"{path}: " + "; ".join(problem.strip().removeprefix("FAIL ") for problem in problems))
337
+ if names is not None:
338
+ entry["compiled"] = names
339
+ return entry, "\n".join(notes) or None
340
+
341
+ def changes(self, entry, path):
342
+ surface = kani_surface(path, self.reader)
343
+ lines = differences(entry["surface"], surface, ("assume", "stub"))
344
+ unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
345
+ "stopped compiling from one that never compiled")
346
+ try:
347
+ problems, names = compiled_problems(path, surface, self.reader, entry.get("compiled"))
348
+ except ValueError as error:
349
+ if "compiled" in entry:
350
+ return [*lines, f" FAIL {error}"], []
351
+ return lines, [unchecked, f" {error}"]
352
+ if names is None or "compiled" in entry and not entry.get("partial"):
353
+ return lines + problems, []
354
+ # Name each recorded harness that Kani does not compile now; a harness behind a feature that is not a
355
+ # default never compiles, so this cannot count as a change.
356
+ recorded = {"harness " + re.sub(r"\[\d+\]$", "", KANI_KEY.fullmatch(item)[2])
357
+ for item in entry["surface"] if item.startswith("harness ") and item in surface}
358
+ missing = sorted(recorded - set(names) - set(entry.get("compiled", ())))
359
+ return lines + problems, [unchecked, *(f" not compiled now {item}" for item in missing)]
360
+
361
+ def valid(self, entry):
362
+ compiled = entry.get("compiled", [])
363
+ return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
364
+ and isinstance(entry.get("partial", False), bool))
365
+
366
+ def moved(self, entry, module, new, existing):
367
+ surface, compiled = entry["surface"], entry.get("compiled")
368
+ if module:
369
+ surface = renamed(surface, *module)
370
+ compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
371
+ surface = joined(surface, new, existing)
372
+ partial = compiled is None or entry.get("partial", False)
373
+ if existing is not None:
374
+ # The merged list keeps the harnesses of each entry checked against Kani at record, and is partial when
375
+ # either entry was not checked.
376
+ other = existing.get("compiled") if existing["kind"] == self.name else None
377
+ partial = partial or other is None or existing.get("partial", False)
378
+ compiled = None if compiled is None and other is None else [*(other or []), *(compiled or [])]
379
+ result = model_entry(self.name, surface)
380
+ if compiled is not None:
381
+ result["compiled"] = sorted(compiled)
382
+ if partial:
383
+ result["partial"] = True
384
+ return result
385
+
386
+
387
+ def model_kinds():
388
+ """Return a fresh adapter for each model kind, by the name a record entry gives as its kind."""
389
+ return {kind.name: kind for kind in (LeanKind(), TlaKind(), KaniKind())}
816
390
 
817
- def compiled_problems(path, surface, recorded=None):
818
- """Return the lines on which the harnesses that Kani compiles from path disagree with surface and recorded, and
819
- surface's harnesses that it compiles, as `harness <owner>` items, or None for them when no Cargo package holds
820
- path.
821
-
822
- Each harness that Kani compiles from path must be one of surface's harnesses under the module path of a route
823
- that the record reads. A harness in recorded that Kani compiles on no route is a harness that was switched off.
824
391
 
825
- Raises:
826
- ValueError: Kani is not installed, or cannot compile the package.
827
- """
828
- package = next((folder for folder in path.parents if (folder / "Cargo.toml").is_file()), None)
829
- if package is None:
830
- return [f" not compiled {item}" for item in recorded or ()], None
831
- names = {harness.name for harness in compiled_in(package) if harness.source == path}
832
- _, modules = declaration_guards(path)
833
- owners = {re.sub(r"\[\d+\]$", "", KANI_KEY.fullmatch(item)[2]) for item in surface if item.startswith("harness ")}
834
- found = {name: route_owner(name, modules, {item_path(owner): owner for owner in owners}) for name in names}
835
- lines = [f" FAIL Kani compiles {name} from this file, but no route that the record reads gives that name; declare "
836
- "the module with `mod <name>;` or `#[path = \"...\"]` outside macros and function bodies"
837
- for name, owner in sorted(found.items()) if owner is None]
838
- compiled = sorted({f"harness {owner}" for owner in found.values() if owner is not None})
839
- lines += [f" not compiled {item}" for item in sorted(set(recorded or ()) - set(compiled))]
840
- return lines, compiled
392
+ def digest(surface):
393
+ return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
841
394
 
842
395
 
843
- SURFACES = {"lean": lean_surface, "tla": tla_surface, "kani": kani_surface}
396
+ def model_entry(kind, surface):
397
+ return {"kind": kind, "digest": digest(surface), "surface": surface}
844
398
 
845
399
 
846
- def digest(surface):
847
- return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
400
+ def joined(surface, new, existing):
401
+ """Add the items that the entry existing records for the file new, which must not repeat an item of surface."""
402
+ if existing is None:
403
+ return surface
404
+ if overlap := surface.keys() & existing["surface"].keys():
405
+ raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
406
+ return {**existing["surface"], **surface}
848
407
 
849
408
 
850
- def read_record(path):
409
+ def read_record(path, kinds):
851
410
  record = json.loads(path.read_text(encoding="utf-8"))
852
411
  models = record.get("models") if isinstance(record, dict) else None
853
412
  if not isinstance(models, dict) or record.get("format") != FORMAT:
854
413
  raise ValueError(f"{path}: unsupported record format; run record with a new record file")
855
414
  for model, entry in models.items():
856
- if not isinstance(entry, dict) or entry.get("kind") not in SURFACES or not isinstance(entry.get("surface"), dict):
857
- raise ValueError(f"{path}: malformed entry for {model}")
858
- compiled = entry.get("compiled", [])
859
- if not isinstance(compiled, list) or not all(isinstance(name, str) for name in compiled):
415
+ if (not isinstance(entry, dict) or entry.get("kind") not in kinds or not isinstance(entry.get("surface"), dict)
416
+ or not kinds[entry["kind"]].valid(entry)):
860
417
  raise ValueError(f"{path}: malformed entry for {model}")
861
418
  return models
862
419
 
@@ -867,28 +424,19 @@ def write_record(path, models):
867
424
 
868
425
 
869
426
  def record(record_path, files):
427
+ kinds = model_kinds()
428
+ by_suffix = {kind.suffix: kind for kind in kinds.values()}
870
429
  for file in files:
871
- if file.suffix not in KINDS:
872
- print(f"usage: {file} has no model surface; expected one of {', '.join(KINDS)}")
430
+ if file.suffix not in by_suffix:
431
+ print(f"usage: {file} has no model surface; expected one of {', '.join(by_suffix)}")
873
432
  return 2
874
- models = read_record(record_path) if record_path.exists() else {}
433
+ models = read_record(record_path, kinds) if record_path.exists() else {}
875
434
  updates, notes = {}, {}
876
435
  for file in files:
877
- kind = KINDS[file.suffix]
878
- surface = SURFACES[kind](file.resolve())
879
- entry = {"kind": kind, "digest": digest(surface), "surface": surface}
880
- if kind == "kani":
881
- # A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
882
- try:
883
- problems, names = compiled_problems(file.resolve(), surface)
884
- except ValueError as error:
885
- notes[str(file.resolve())] = f" not checked against Kani: {error}"
886
- else:
887
- if problems:
888
- raise ValueError(f"{file.resolve()}: " + "; ".join(problem.strip().removeprefix("FAIL ") for problem in problems))
889
- if names is not None:
890
- entry["compiled"] = names
891
- updates[str(file.resolve())] = entry
436
+ model = str(file.resolve())
437
+ updates[model], note = by_suffix[file.suffix].entry(file.resolve())
438
+ if note:
439
+ notes[model] = note
892
440
  for model, entry in updates.items():
893
441
  print(f"RECORDED {model} {entry['digest']}")
894
442
  previous = models.get(model, {}).get("digest")
@@ -900,15 +448,14 @@ def record(record_path, files):
900
448
  return 0
901
449
 
902
450
 
903
- KANI_KEY = re.compile(r"(harness |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
904
-
905
-
906
451
  def renamed(surface, old_module, new_module):
907
452
  """Rewrite each Kani owner under old_module to sit under new_module, where `crate` is the file's root."""
908
453
  old, new = ([] if path == "crate" else path.split("::") for path in (old_module, new_module))
909
454
  result = {}
910
455
  for name, value in surface.items():
911
- head, owner, duplicate = KANI_KEY.fullmatch(name).groups()
456
+ if (item := KANI_KEY.fullmatch(name)) is None:
457
+ raise ValueError(f"cannot rename the recorded item '{name}', which is not a Kani harness, assume, cover or stub")
458
+ head, owner, duplicate = item.groups()
912
459
  parts = owner.split("::")
913
460
  if parts[:len(old)] == old:
914
461
  owner = "::".join(new + parts[len(old):])
@@ -919,49 +466,34 @@ def renamed(surface, old_module, new_module):
919
466
 
920
467
 
921
468
  def move(record_path, old_file, new_file, module):
922
- models = read_record(record_path) if record_path.is_file() else {}
469
+ kinds = model_kinds()
470
+ models = read_record(record_path, kinds) if record_path.is_file() else {}
923
471
  old, new = str(old_file.resolve()), str(new_file.resolve())
924
472
  if old not in models:
925
473
  print(f"usage: {old} has no record entry; record it before the move")
926
474
  return 2
927
- kind = models[old]["kind"]
928
- if KINDS.get(new_file.suffix) != kind:
929
- print(f"usage: {new} is not a {kind} model file")
475
+ kind = kinds[models[old]["kind"]]
476
+ if new_file.suffix != kind.suffix:
477
+ print(f"usage: {new} is not a {kind.name} model file")
930
478
  return 2
931
- if module and kind != "kani":
479
+ if module and not kind.renames:
932
480
  print("usage: --module applies only to a Kani harness file")
933
481
  return 2
934
482
  entry = models.pop(old)
935
- surface, compiled = entry["surface"], entry.get("compiled")
936
- if module:
937
- surface = renamed(surface, *module)
938
- compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
939
- if new in models:
940
- if overlap := surface.keys() & models[new]["surface"].keys():
941
- raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
942
- surface = {**models[new]["surface"], **surface}
943
- # The merged entry holds Kani's list only when both entries were checked against Kani at record.
944
- compiled = [*models[new]["compiled"], *compiled] if "compiled" in models[new] and compiled is not None else None
945
- models[new] = {"kind": kind, "digest": digest(surface), "surface": surface}
946
- if compiled is not None:
947
- models[new]["compiled"] = sorted(compiled)
483
+ models[new] = kind.moved(entry, module, new, models.get(new))
948
484
  write_record(record_path, models)
949
485
  print(f"MOVED {old} -> {new}")
950
486
  return 0
951
487
 
952
488
 
953
- def differences(kind, old, new):
489
+ def differences(old, new, narrowing):
954
490
  lines = []
955
- if kind == "tla" and not any(name.startswith("imports ") for name in old):
956
- lines.append(" previous baseline did not track imported modules; review and record this matrix again")
957
- if kind == "tla" and "TLA+ layout version" not in old:
958
- lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
959
491
  for name in old:
960
492
  if name not in new:
961
493
  lines.append(f" removed {name}")
962
494
  elif old[name] != new[name]:
963
495
  lines += [f" changed {name}", f" old: {old[name]}", f" new: {new[name]}"]
964
- lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in NARROWING[kind]]
496
+ lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in narrowing]
965
497
  return lines
966
498
 
967
499
 
@@ -969,31 +501,30 @@ def compare(record_path):
969
501
  if not record_path.is_file():
970
502
  print(f"usage: record file {record_path} does not exist; run record first")
971
503
  return 2
972
- models = read_record(record_path)
973
- changed = 0
504
+ kinds = model_kinds()
505
+ models = read_record(record_path, kinds)
506
+ changed = unchecked = 0
974
507
  for model, entry in models.items():
975
508
  try:
976
509
  if not Path(model).is_file():
977
- lines = [" file is missing"]
510
+ lines, notes = [" file is missing"], []
978
511
  else:
979
- surface = SURFACES[entry["kind"]](Path(model))
980
- lines = differences(entry["kind"], entry["surface"], surface)
981
- if entry["kind"] == "kani":
982
- try:
983
- problems, names = compiled_problems(Path(model), surface, entry.get("compiled"))
984
- lines += problems
985
- if names is not None and "compiled" not in entry:
986
- lines.append(" not checked against Kani at record, so compare cannot see a harness that "
987
- "stopped compiling on a route that the record does not read")
988
- except ValueError as error:
989
- lines.append(f" FAIL {error}")
512
+ lines, notes = kinds[entry["kind"]].changes(entry, Path(model))
990
513
  except (OSError, ValueError, KeyError, TypeError) as error:
991
- lines = [f" FAIL {error}"]
514
+ lines, notes = [f" FAIL {error}"], []
992
515
  changed += bool(lines)
993
- print(f"{'CHANGED' if lines else 'UNCHANGED'} {model}")
516
+ unchecked += bool(notes) and not lines
994
517
  if lines:
995
- print("\n".join(lines))
996
- print(f"SUMMARY {len(models) - changed} unchanged, {changed} changed")
518
+ status = "CHANGED"
519
+ elif notes:
520
+ status = "NOT CHECKED"
521
+ else:
522
+ status = "UNCHANGED"
523
+ print(f"{status} {model}")
524
+ if lines or notes:
525
+ print("\n".join(lines + notes))
526
+ not_checked = f", {unchecked} not checked" if unchecked else ""
527
+ print(f"SUMMARY {len(models) - changed - unchecked} unchanged, {changed} changed{not_checked}")
997
528
  return int(changed > 0)
998
529
 
999
530