agent-formal-verify 0.4.13 → 0.4.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.
@@ -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,30 @@ 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
42
+ import fcntl
40
43
  import hashlib
41
44
  import json
42
- import os
43
45
  import re
44
46
  import sys
45
- import tempfile
47
+ from contextlib import contextmanager
46
48
  from pathlib import Path
47
- from typing import NamedTuple
48
49
 
49
50
  sys.dont_write_bytecode = True
50
51
 
51
- import kani
52
52
  import runner
53
- import storage
54
53
  import tlc
54
+ from kani_reader import KANI_KEY, RouteReader, compiled_problems, kani_surface
55
55
  from lean_records import read_record as read_lean_record
56
+ from surface import STRING, Surface, collapse
56
57
 
57
58
  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
59
 
83
60
 
84
61
  def lean_surface(path):
@@ -282,10 +259,10 @@ def tla_surface(path):
282
259
  for task in tasks:
283
260
  if task.reach:
284
261
  surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
285
- {"run": collapse(task.run.label), "constants": collapse(task.run.constants)})
262
+ {"run": collapse(task.run.label), "constants": task.run.constants})
286
263
  specs[task.spec].add(task.reach.operator)
287
264
  else:
288
- run = surface.add(f"run {task.spec} {collapse(task.run.label)}", collapse(task.run.constants))
265
+ run = surface.add(f"run {task.spec} {collapse(task.run.label)}", task.run.constants)
289
266
  for check in task.checks:
290
267
  for name in check.names:
291
268
  surface.add(f"check {task.spec} {check.kind} {name} | [{run}]")
@@ -298,597 +275,189 @@ def tla_surface(path):
298
275
  return surface
299
276
 
300
277
 
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]
549
-
550
-
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)
553
-
554
-
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
278
+ class LeanKind:
279
+ """Record, compare and move the toolchain and declarations of a Lean statements file."""
571
280
 
281
+ name, suffix, renames = "lean", ".statements", False
572
282
 
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.
283
+ def entry(self, path):
284
+ return model_entry(self.name, lean_surface(path)), None
576
285
 
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)
286
+ def changes(self, entry, path):
287
+ return differences(entry["surface"], lean_surface(path), ()), []
632
288
 
289
+ def valid(self, entry):
290
+ return True
633
291
 
634
- TREES = {}
292
+ def moved(self, entry, module, new, existing):
293
+ return model_entry(self.name, joined(entry["surface"], new, existing))
635
294
 
636
295
 
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.
296
+ class TlaKind:
297
+ """Record, compare and move the checks of a TLA+ matrix and the specs it runs."""
640
298
 
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")
299
+ name, suffix, renames = "tla", ".matrix", False
751
300
 
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
301
+ def entry(self, path):
302
+ return model_entry(self.name, tla_surface(path)), None
774
303
 
304
+ def changes(self, entry, path):
305
+ old, new = entry["surface"], tla_surface(path)
306
+ lines = []
307
+ if not any(name.startswith("imports ") for name in old):
308
+ lines.append(" previous baseline did not track imported modules; review and record this matrix again")
309
+ if "TLA+ layout version" not in old:
310
+ lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
311
+ return lines + differences(old, new, ()), []
775
312
 
776
- @functools.cache
777
- def checker():
778
- return kani.Kani()
313
+ def valid(self, entry):
314
+ return True
779
315
 
316
+ def moved(self, entry, module, new, existing):
317
+ return model_entry(self.name, joined(entry["surface"], new, existing))
780
318
 
781
- @functools.cache
782
- def compiled_in(package):
783
- """Return each harness that Kani compiles in the Cargo package at package.
784
319
 
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
793
-
794
-
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+\}|_")
797
-
798
-
799
- def item_path(name):
800
- return "::".join(part.removeprefix("r#") for part in name.split("::") if not ANONYMOUS.fullmatch(part))
320
+ def may_omit_generator_types(entry):
321
+ # Older entries used the same keys for plain assumptions and generator predicates.
322
+ return not entry.get("generator_types") and any(key.startswith("assume ") for key in entry["surface"])
801
323
 
802
324
 
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.
325
+ class KaniKind:
326
+ """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
805
327
 
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
328
+ name, suffix, renames = "kani", ".rs", True
815
329
 
330
+ def __init__(self):
331
+ self.reader = RouteReader()
816
332
 
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.
333
+ def entry(self, path):
334
+ surface = kani_surface(path, self.reader)
335
+ entry = model_entry(self.name, surface)
336
+ entry["generator_types"] = True
337
+ notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
338
+ # A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
339
+ try:
340
+ problems, names = compiled_problems(path, surface, self.reader)
341
+ except ValueError as error:
342
+ return entry, "\n".join([*notes, f" not checked against Kani: {error}"])
343
+ if problems:
344
+ raise ValueError(f"{path}: " + "; ".join(problem.strip().removeprefix("FAIL ") for problem in problems))
345
+ if names is not None:
346
+ entry["compiled"] = names
347
+ return entry, "\n".join(notes) or None
348
+
349
+ def changes(self, entry, path):
350
+ surface = kani_surface(path, self.reader)
351
+ lines = differences(entry["surface"], surface, ("assume", "stub"))
352
+ if may_omit_generator_types(entry):
353
+ lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
354
+ unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
355
+ "stopped compiling from one that never compiled")
356
+ try:
357
+ problems, names = compiled_problems(path, surface, self.reader, entry.get("compiled"))
358
+ except ValueError as error:
359
+ if "compiled" in entry:
360
+ return [*lines, f" FAIL {error}"], []
361
+ return lines, [unchecked, f" {error}"]
362
+ if names is None or "compiled" in entry and not entry.get("partial"):
363
+ return lines + problems, []
364
+ # Name each recorded harness that Kani does not compile now; a harness behind a feature that is not a
365
+ # default never compiles, so this cannot count as a change.
366
+ recorded = {"harness " + re.sub(r"\[\d+\]$", "", KANI_KEY.fullmatch(item)[2])
367
+ for item in entry["surface"] if item.startswith("harness ") and item in surface}
368
+ missing = sorted(recorded - set(names) - set(entry.get("compiled", ())))
369
+ return lines + problems, [unchecked, *(f" not compiled now {item}" for item in missing)]
370
+
371
+ def valid(self, entry):
372
+ compiled = entry.get("compiled", [])
373
+ return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
374
+ and isinstance(entry.get("partial", False), bool) and isinstance(entry.get("generator_types", False), bool))
375
+
376
+ def moved(self, entry, module, new, existing):
377
+ surface, compiled = entry["surface"], entry.get("compiled")
378
+ if module:
379
+ surface = renamed(surface, *module)
380
+ compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
381
+ surface = joined(surface, new, existing)
382
+ partial = compiled is None or entry.get("partial", False)
383
+ if existing is not None:
384
+ # The merged list keeps the harnesses of each entry checked against Kani at record, and is partial when
385
+ # either entry was not checked.
386
+ other = existing.get("compiled") if existing["kind"] == self.name else None
387
+ partial = partial or other is None or existing.get("partial", False)
388
+ compiled = None if compiled is None and other is None else [*(other or []), *(compiled or [])]
389
+ result = model_entry(self.name, surface)
390
+ if not any(may_omit_generator_types(part) for part in (entry, existing) if part is not None):
391
+ result["generator_types"] = True
392
+ if compiled is not None:
393
+ result["compiled"] = sorted(compiled)
394
+ if partial:
395
+ result["partial"] = True
396
+ return result
397
+
398
+
399
+ def model_kinds():
400
+ """Return a fresh adapter for each model kind, by the name a record entry gives as its kind."""
401
+ return {kind.name: kind for kind in (LeanKind(), TlaKind(), KaniKind())}
821
402
 
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
403
 
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
404
+ def digest(surface):
405
+ return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
841
406
 
842
407
 
843
- SURFACES = {"lean": lean_surface, "tla": tla_surface, "kani": kani_surface}
408
+ def model_entry(kind, surface):
409
+ return {"kind": kind, "digest": digest(surface), "surface": surface}
844
410
 
845
411
 
846
- def digest(surface):
847
- return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
412
+ def joined(surface, new, existing):
413
+ """Add the items that the entry existing records for the file new, which must not repeat an item of surface."""
414
+ if existing is None:
415
+ return surface
416
+ if overlap := surface.keys() & existing["surface"].keys():
417
+ raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
418
+ return {**existing["surface"], **surface}
848
419
 
849
420
 
850
- def read_record(path):
421
+ def read_record(path, kinds):
851
422
  record = json.loads(path.read_text(encoding="utf-8"))
852
423
  models = record.get("models") if isinstance(record, dict) else None
853
424
  if not isinstance(models, dict) or record.get("format") != FORMAT:
854
425
  raise ValueError(f"{path}: unsupported record format; run record with a new record file")
855
426
  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):
427
+ if (not isinstance(entry, dict) or entry.get("kind") not in kinds or not isinstance(entry.get("surface"), dict)
428
+ or not kinds[entry["kind"]].valid(entry)):
860
429
  raise ValueError(f"{path}: malformed entry for {model}")
861
430
  return models
862
431
 
863
432
 
864
- def write_record(path, models):
433
+ @contextmanager
434
+ def locked_models(path, kinds):
435
+ """Lock a stable sibling across the read and replacement of a record."""
865
436
  path.parent.mkdir(parents=True, exist_ok=True)
437
+ with path.with_name(f".{path.name}.lock").open("a") as lock:
438
+ fcntl.flock(lock, fcntl.LOCK_EX)
439
+ yield read_record(path, kinds) if path.exists() else {}
440
+
441
+
442
+ def write_record(path, models):
866
443
  runner.atomic_write(path, json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
867
444
 
868
445
 
869
446
  def record(record_path, files):
447
+ kinds = model_kinds()
448
+ by_suffix = {kind.suffix: kind for kind in kinds.values()}
870
449
  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)}")
450
+ if file.suffix not in by_suffix:
451
+ print(f"usage: {file} has no model surface; expected one of {', '.join(by_suffix)}")
873
452
  return 2
874
- models = read_record(record_path) if record_path.exists() else {}
875
453
  updates, notes = {}, {}
876
454
  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
455
+ model = str(file.resolve())
456
+ updates[model], note = by_suffix[file.suffix].entry(file.resolve())
457
+ if note:
458
+ notes[model] = note
459
+ with locked_models(record_path, kinds) as models:
460
+ write_record(record_path, {**models, **updates})
892
461
  for model, entry in updates.items():
893
462
  print(f"RECORDED {model} {entry['digest']}")
894
463
  previous = models.get(model, {}).get("digest")
@@ -896,19 +465,17 @@ def record(record_path, files):
896
465
  print(f" previous {previous}")
897
466
  if model in notes:
898
467
  print(notes[model])
899
- write_record(record_path, {**models, **updates})
900
468
  return 0
901
469
 
902
470
 
903
- KANI_KEY = re.compile(r"(harness |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
904
-
905
-
906
471
  def renamed(surface, old_module, new_module):
907
472
  """Rewrite each Kani owner under old_module to sit under new_module, where `crate` is the file's root."""
908
473
  old, new = ([] if path == "crate" else path.split("::") for path in (old_module, new_module))
909
474
  result = {}
910
475
  for name, value in surface.items():
911
- head, owner, duplicate = KANI_KEY.fullmatch(name).groups()
476
+ if (item := KANI_KEY.fullmatch(name)) is None:
477
+ raise ValueError(f"cannot rename the recorded item '{name}', which is not a Kani harness, assume, cover or stub")
478
+ head, owner, duplicate = item.groups()
912
479
  parts = owner.split("::")
913
480
  if parts[:len(old)] == old:
914
481
  owner = "::".join(new + parts[len(old):])
@@ -919,49 +486,34 @@ def renamed(surface, old_module, new_module):
919
486
 
920
487
 
921
488
  def move(record_path, old_file, new_file, module):
922
- models = read_record(record_path) if record_path.is_file() else {}
489
+ kinds = model_kinds()
923
490
  old, new = str(old_file.resolve()), str(new_file.resolve())
924
- if old not in models:
925
- print(f"usage: {old} has no record entry; record it before the move")
926
- 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")
930
- return 2
931
- if module and kind != "kani":
932
- print("usage: --module applies only to a Kani harness file")
933
- return 2
934
- 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)
948
- write_record(record_path, models)
491
+ with locked_models(record_path, kinds) as models:
492
+ if old not in models:
493
+ print(f"usage: {old} has no record entry; record it before the move")
494
+ return 2
495
+ kind = kinds[models[old]["kind"]]
496
+ if new_file.suffix != kind.suffix:
497
+ print(f"usage: {new} is not a {kind.name} model file")
498
+ return 2
499
+ if module and not kind.renames:
500
+ print("usage: --module applies only to a Kani harness file")
501
+ return 2
502
+ entry = models.pop(old)
503
+ models[new] = kind.moved(entry, module, new, models.get(new))
504
+ write_record(record_path, models)
949
505
  print(f"MOVED {old} -> {new}")
950
506
  return 0
951
507
 
952
508
 
953
- def differences(kind, old, new):
509
+ def differences(old, new, narrowing):
954
510
  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
511
  for name in old:
960
512
  if name not in new:
961
513
  lines.append(f" removed {name}")
962
514
  elif old[name] != new[name]:
963
515
  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]]
516
+ lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in narrowing]
965
517
  return lines
966
518
 
967
519
 
@@ -969,31 +521,30 @@ def compare(record_path):
969
521
  if not record_path.is_file():
970
522
  print(f"usage: record file {record_path} does not exist; run record first")
971
523
  return 2
972
- models = read_record(record_path)
973
- changed = 0
524
+ kinds = model_kinds()
525
+ models = read_record(record_path, kinds)
526
+ changed = unchecked = 0
974
527
  for model, entry in models.items():
975
528
  try:
976
529
  if not Path(model).is_file():
977
- lines = [" file is missing"]
530
+ lines, notes = [" file is missing"], []
978
531
  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}")
532
+ lines, notes = kinds[entry["kind"]].changes(entry, Path(model))
990
533
  except (OSError, ValueError, KeyError, TypeError) as error:
991
- lines = [f" FAIL {error}"]
534
+ lines, notes = [f" FAIL {error}"], []
992
535
  changed += bool(lines)
993
- print(f"{'CHANGED' if lines else 'UNCHANGED'} {model}")
536
+ unchecked += bool(notes) and not lines
994
537
  if lines:
995
- print("\n".join(lines))
996
- print(f"SUMMARY {len(models) - changed} unchanged, {changed} changed")
538
+ status = "CHANGED"
539
+ elif notes:
540
+ status = "NOT CHECKED"
541
+ else:
542
+ status = "UNCHANGED"
543
+ print(f"{status} {model}")
544
+ if lines or notes:
545
+ print("\n".join(lines + notes))
546
+ not_checked = f", {unchecked} not checked" if unchecked else ""
547
+ print(f"SUMMARY {len(models) - changed - unchecked} unchanged, {changed} changed{not_checked}")
997
548
  return int(changed > 0)
998
549
 
999
550