# Checker Specification

`temporal-typing` declares; a *checker* verifies. This document says what a
checker must do to verify Python source annotated with `temporal-typing`, so
that any checker (one built on Manyan, TLC, Apalache, or something else) gives
the same verdict on the same source.

[semantics.md](semantics.md) defines what the declarations *mean*. This
document defines what a checker must *do* with them: how it finds them, which
Python it must accept, what it must reject, and what it must report.

The words MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119.

The one rule behind every section: **a checker never reports PASS for a
check it did not make.** Whatever it skips, guesses or cannot translate, it
says so.

---

## 1. Pipeline

A checker runs these stages:

1. **Read.** Parse the files, never importing or executing them, resolve
   their names and imports (§2), and extract every specification, contract
   and model (§3). Reject what §3, §4 and §6 say to reject.
2. **Translate.** Give each model a meaning in the checker's backend, usually
   a TLA⁺ module and `.cfg` (§5).
3. **Check.** Run the backend over the finite model the `Model` describes (§7).
4. **Report.** Give one verdict per model (§8).

Stage 1 is the same for every checker, and this package implements it: the
**front-end**, `temporal_typing.frontend` (§10). A checker written in Python
SHOULD use it rather than repeat it. A checker that does not MUST give the
same diagnostics.

A model whose reading has errors gets an ERROR verdict; the other models go
on. A model is refused for the errors of what it reads (its specification or
contract, their bases, refinement targets and the functions they call, and
the model itself) and for errors outside any unit in its files, such as a
syntax error or an unbound name.

## 2. Resolving names

- A checker MUST work from source alone (`ast` or equivalent). It MUST NOT
  import, execute or evaluate user modules, predicates or bodies. It MAY
  compile them, which runs nothing, to find what only the compiler rejects.
- It MUST recognise every way of naming the library: `from temporal_typing
  import Init`, `from temporal_typing import Init as I`, `import
  temporal_typing as t` then `t.Init`, and `typing.Annotated` under any alias,
  from `typing` or `typing_extensions`.
- A name read that nothing binds, or a top-level name read before the
  statement that binds it, is an ERROR (`unknown-name`): the file would not
  import.
- A specification referenced from another file (`Refines[Abs]` where `Abs` is
  imported, a base class, a `Model` whose specification is imported) MUST be
  resolved by following the import to its source, relative to the file and to
  the search roots the user gives. If it cannot be, the unit is an ERROR
  (`unresolved-import`). It MUST NOT be skipped. An import nothing uses, or
  one a plain class uses, is not an error: it may be installed where the code
  runs.
- A module is known by its dotted name, as Python knows it, so a
  specification's qualified name is unique. A file whose module name is
  already read from another file (`a/spec.py` and `b/spec.py`, outside any
  package) is an ERROR (`duplicate-module`), and nothing in it is read.
- Inheritance follows Python's MRO: a specification has its bases'
  declarations, and a method that overrides a base's action keeps the base's
  clauses ([semantics.md §1](semantics.md)).
- Only annotations that name `temporal_typing`, directly or through a
  module-level alias, are read. A class with none is not a specification and
  is left alone.

## 3. Extracting

The units are those of [semantics.md §1](semantics.md): a specification class
and a contract function. For each specification a checker builds:

| Table | From |
| --- | --- |
| Constants | `Constant[T]` fields, with their defaults |
| Variables | `State[T]` and `Ghost[T]` fields, with their defaults |
| Operators | `Pure[T]` methods and properties |
| Clauses | `@spec(name=Clause(...))`, merged along the MRO |
| Actions | Every method whose return annotation carries `Action`, with its parameters, `Requires`, predicate, body, `Ensures`, `Modifies` and frame |
| Refinements | Every method returning `Refines[A]`, with its mapping |

A method body that is `...` (with or without a docstring) is no body: the
action's transition is its predicate. `pass` is a body that changes nothing.

### Binding predicate parameters

- In a class clause, the one parameter is the state.
- In a method's clause, the first parameter is the state. The others bind
  **by name** to the method's parameters, plus `result` in `Ensures`.
- In a contract's clause, every parameter binds by name to a function
  parameter, plus `result` in `Ensures`.
- A parameter that names nothing is an ERROR (`bad-binding`), at the lambda.

### Frames

An action's frame is the variables it may change: its `Modifies` if it has
one; else the variables its body writes, directly or through the methods it
calls, and the `Ghost` variables its predicate primes; else, with no body,
the variables its predicate primes. Every other variable is unchanged.

## 4. The Python a checker accepts

A checker MUST give every construct it accepts **its Python meaning**. Where
the backend's operator differs from Python's, the checker encodes Python's.
Everything else it MUST reject as `unsupported`, at the construct's line, in
Python terms (`try is not supported in a body`), never as a dump of the
syntax tree.

### 4.1 Values

| Python | Meaning a checker must keep |
| --- | --- |
| `int` | Unbounded integers. `//` floors, and `%` takes the divisor's sign (`-7 % 3 == 2`, `7 % -3 == -2`). `/` gives a float: reject. |
| `bool` | `True` and `False`. Python's `bool` is an `int` (`True == 1`, `True + 1 == 2`): a checker either encodes that or rejects mixing `bool` with `int`. |
| `None` | One value, distinct from every other. `Optional[T]` and `T \| None` are `T` or `None`. |
| `str` | Atoms compared by equality. String methods: reject. |
| `tuple[T, ...]`, `list[T]` | Sequences indexed from 0, compared by value. A negative index counts from the end. A slice clamps its bounds as Python does. An index out of range is a failure in the checked behaviour (§8), not an undefined value. |
| `frozenset[T]`, `set[T]` | Finite sets, with `\|`, `&`, `-`, `^`, `<=`, `<`, `in` and the methods of the same meaning. |
| `dict[K, V]` | Finite functions. A missing key is a failure in the checked behaviour. `in` tests keys. |
| `ModelValue` subclasses | Atoms equal only to themselves: same sort and same name. |
| `Literal[...]`, an `Enum` | Those values. |

A bare container (`list`, `dict`) says nothing of what it holds: reject.
Any other type, a class's included, is `unsupported`. Equality between values
of different types is `False` in Python. A checker whose backend rejects such
comparisons MUST rule them out statically or encode them.

### 4.2 Expressions

Arithmetic, comparisons (chained ones too), `not`, `and`, `or`, conditional
expressions, subscripts and slices, displays and comprehensions over finite
collections, `*` inside a display, the builtins `len`, `min`, `max`, `abs`,
`sum`, `all`, `any`, `range`, `enumerate`, `sorted`, `reversed`, `zip`,
`tuple`, `list`, `set`, `frozenset` and `dict`, and the value methods
`union`, `intersection`, `difference`, `symmetric_difference`, `issubset`,
`issuperset`, `isdisjoint`, `keys`, `values`, `items`, `get`, `index`,
`count` and `copy`, with the meanings in [semantics.md §3](semantics.md). In
addition:

- **Truthiness.** `if xs:`, `while n:` and `not d` test emptiness or zero as
  Python does. A checker encodes it or rejects it. It MUST NOT pass a
  collection where the backend wants a boolean.
- **`and` / `or`** give one of their operands. Where the operands are not
  booleans (`a or 7`), a checker encodes that or rejects it.
- **A set's order.** Python iterates a set in the order of its hashes,
  for a `str` another in each run. Where that order is seen, a checker MUST
  reject: a set into a `tuple` or `list`, a list comprehension or generator
  over a set, `*` of a set in a sequence's display, a `for` loop over a set,
  a dict comprehension over a set that may give a key twice. Where it is
  not (`sorted`, `len`, `sum`, `min`, `max`, `all`, `any`, `set`,
  `frozenset`, `in`, a set comprehension), it is Python's.
- `is` and `is not` compare with `None`, `True` or `False` only.
- `/`, `@`, `<<`, `>>`, `~`, `:=`, f-strings, lambdas outside `choose`,
  floats, and calls to anything not named here are `unsupported`.

In a predicate, a call to an action is `misplaced-clause` except inside
`enabled`, `weak_fairness` and `strong_fairness`; the last two belong in a
`Fairness` clause only. A predicate calls `Pure` operators, not other
methods.

### 4.3 Statements in a body

| Statement | Meaning |
| --- | --- |
| `self.x = e`, `self.x += e`, local assignment, tuple unpacking | Sequential: a later statement reads what an earlier one wrote. Assigning a constant is `bad-write`; assigning a name the specification does not declare is `unknown-name`. |
| `self.items.append(v)`, `self.d[k] = v`, `del self.d[k]`, `self.items.pop()` and the other in-place changes of lists, sets and dicts | The state variable changes. |
| An in-place change of a local that may share its value (a parameter, or `xs = self.items`) | `unsupported`: change a copy (`xs = list(xs)`). |
| `if` / `elif` / `else`, `return` | Branches of the transition. |
| `for v in <finite collection>`, `while c` | The loop, run to completion; `break` and `continue` keep their meaning. A checker MUST bound or detect non-termination and report it. |
| `assert c` | A proof obligation: in every reachable pre-state where the action is enabled, `c` holds on that path. A failure is a FAIL of kind `assertion`. A checker MUST NOT drop an `assert`. |
| `raise E(...)` | That path gives no successor: the call fails. A `raise` after a write to state on the same path is `unsupported`. |
| A call to an action or a method on `self` | Its body runs in place, and an action's `Requires` becomes an obligation at the call site. Recursion is `unsupported`. |
| A call to a `Pure` operator or a module-level function | Its value. The function's body is checked as a `Pure` body. |
| `try`, `with`, `match`, `global`, `nonlocal`, `import`, nested `def` or `class`, `async`, `yield`, `await`, a value computed and thrown away | `unsupported`. |

A `Pure` body follows the same rules and MUST NOT write state, directly or
through what it calls (`bad-write`).

A public method that writes state but carries no `Action` is not checked:
the front-end warns (`unannotated-mutator`).

## 5. Translation

This section uses TLA⁺. A checker with another backend MUST check the same
obligations.

### 5.1 Specification

- **Init** is the conjunction of the `Init` clauses, with each variable's
  class-level default where no `Init` clause mentions it. `__init__` takes no
  part. A variable with neither is an ERROR (`no-init`).
- **Next** is the disjunction of the actions, each quantified over its
  parameters' domains, as in [semantics.md §5](semantics.md). An action's
  transition comes from its **body** when it has one and from its predicate
  otherwise, with its frame (§3). In a *spec-only* run, a checker uses the
  predicates and ignores the bodies.
- **Spec** is `Init /\ [][Next]_vars /\ Fairness`, with the `Fairness`
  clauses conjoined.

### 5.2 Obligations

| Obligation | Checked as |
| --- | --- |
| Each `Assume`, and `Where` on a `Constant` | `ASSUME` |
| Each `Invariant`, and `Where` on a variable | `INVARIANT` |
| Each `ActionInvariant` | `PROPERTY [][A]_vars` |
| Each `Property` | `PROPERTY` |
| **Conformance** of an action with both a predicate and a body | For every parameter value in the domain: `Requires => Pred` with each `prime(v)` the body's new value of `v`, together with the action's `Ensures`, the `Where` of its result, and its frame. |
| A contract | For every argument tuple in the domains: `Requires /\ Where(args) => Ensures /\ Where(result)` with `result` the body's value |
| Each `assert` | §4.3 |

### 5.3 Refinement

For a specification `C` and each `Refines[A]` mapping `m`, a checker MUST
check **all** of `C!Spec => A!Spec` under `m`:

1. `A`'s `Init` under `m`,
2. `[][A!Next]_(A!vars)` under `m`,
3. **every `Fairness` clause of `A`** under `m`,
4. `A`'s invariants and properties under `m`.

A mapping MUST say what each of `A`'s variables is (`missing-mapping`). An
`A` constant it does not map is `C`'s constant of the same name, or else a
`missing-mapping` error. If a checker cannot check one of the four, the
verdict is ERROR, not PASS.

### 5.4 Symmetry

A checker MUST NOT apply a symmetry when the model checks a `Property` or a
refinement, as TLC's reduction is unsound there. It MUST then warn that the
symmetry was dropped (`symmetry-dropped`).

## 6. Models

- Every name in a `Model` MUST exist: `actions`, `invariants` and
  `properties` entries and `constants` keys. A name that does not is an ERROR
  (`unknown-name`). This catches typos, which otherwise check nothing.
- Every constant without a default MUST be bound in `constants`
  (`unbound-constant`), with a value of its type (`bad-domain`).
- **Domains.** Every parameter a model quantifies over MUST get a finite
  domain: an entry in `Model.domains`, keyed by the parameter's type (its
  alias as written, then the type under its `Where`), or from the type itself
  when it is `bool`, `None`, a `Literal` or an `Enum`. An `Optional[T]` or
  union gets the domains of its parts. A `Where` narrows a domain; it does not
  supply one. A checker MUST NOT make up a domain. A missing one is an ERROR
  (`missing-domain`), an empty one is `vacuous`, and a value not of the key's
  type is `bad-domain`. A domain no parameter uses is a warning
  (`unused-domain`).
- A contract is checked through a `Model` whose specification is the
  function. It takes `domains` only.
- `state_constraint`, `action_constraint` and `check_deadlock` are passed to
  the backend with their `.cfg` meaning. The constraints are predicates of
  one state and of one step.
- A model built with `dataclasses.replace(model, ...)` is a model too.

## 7. Checking

A checker runs the backend once per `Model`, each in isolation: no shared
working directory, no change to the process's current directory, safe to run
in parallel.

## 8. Verdicts

Each model gets one verdict.

**PASS** MUST say what was checked: the number of initial and distinct
states, the domains, whether a constraint bounded the search, and which
symmetries were applied or dropped. For example:

```
PASS bank_account.py::small_account_model  884 states; deposit.amount, withdraw.amount ∈ 1..3; bounded by state_constraint
```

**Vacuity.** Zero initial states is an ERROR (`vacuous`), not a PASS. An
action that is never enabled SHOULD be a warning.

**FAIL** MUST name its kind and what failed:

| Kind | Names |
| --- | --- |
| `assumption` | The `Assume` or `Where` |
| `invariant` | The `Invariant` or the variable's `Where` |
| `action-invariant` | The `ActionInvariant` |
| `conformance` | The action, its parameter values, and the conjunct that failed (predicate, `Ensures`, frame on variable `v`) |
| `contract` | The function, its arguments and its result |
| `assertion` | The action and the `assert` line |
| `refinement` | The abstract specification and the part: init, step, fairness, invariant, property |
| `property` | The `Property` |
| `deadlock` | The state |
| `runtime` | An index out of range, a missing key, or a division by zero in the checked behaviour |

and give the trace in Python terms: variable names as declared, values as
Python would print them (tuples, frozensets, dicts, `None`, model values by
name), and for each step the action and its parameter values.

**ERROR** is either a user error with a diagnostic of §9 at a `file:line`,
or an **internal** error: the backend rejected what the checker generated.
An internal error is the checker's bug and MUST be reported as such, never as
the user's FAIL.

Warnings go with the verdict and do not change it.

A command-line checker SHOULD exit 0 when every verdict is PASS, 1 when any is
FAIL, and 2 when any is ERROR. It SHOULD also give its verdicts in a
machine-readable form.

## 9. Diagnostics

Every diagnostic has a code, a `file:line:column`, and a message in Python
terms. These are all of them:

| Code | When |
| --- | --- |
| `syntax-error` | The file does not parse or does not compile, or cannot be read |
| `unresolved-import` | A specification, base or refined class is imported from a module no search root holds; a relative import goes above its package |
| `duplicate-module` | A file has the module name of a file already read, as two `spec.py` outside any package do: Python has one module of a name |
| `unknown-name` | A name nothing binds or that is read before its binding; a member a specification does not have; a name in a `Model` its specification does not have; a name `temporal_typing`, `typing`, `typing_extensions`, `dataclasses` or `enum` does not have |
| `bad-binding` | A clause's parameter binds nothing, or a clause takes the wrong parameters; an override changes an action's parameters |
| `bad-clause` | A clause takes no predicate it can use: not a lambda or a module-level function, a description not a string literal; `@spec` without its clauses |
| `role-conflict` | One field has two roles, a `ClassVar` has a role, `Pure` marks a field, a method is both an action and `Pure`, or a base's role changes in a subclass |
| `level-error` | An expression above its clause's level ([semantics.md §2](semantics.md)): `prime` in an `Invariant`, a variable in an `Assume`, `eventually` in an `Ensures` |
| `misplaced-clause` | A clause where it does not belong: a class clause on a method or as an attribute, `Requires` on a method without `Action`, an action called in a predicate, `weak_fairness` outside `Fairness`, `Refines` outside a refinement method, `Action(...)` outside `Annotated`, `@dataclass(slots=True)` above `@spec`, which makes a class `@spec` did not see; a library name other than `@spec` of a class used as a decorator |
| `duplicate-clause` | Two clauses, two `Action`s or two `Modifies` with one name; a clause named as a member; `@spec` applied twice; a name given twice in a `Model` or `Modifies` |
| `no-init` | A variable has no initial value; of a `Protocol`, its implementations give one |
| `no-actions` | A model has no action |
| `no-transition` | An action has neither a body nor a predicate |
| `missing-type` | A parameter has no annotation |
| `missing-domain` | A parameter the model quantifies over has no domain |
| `unbound-constant` | A constant with no default is not bound in `constants` |
| `vacuous` | A domain is empty |
| `bad-domain` | A domain or constant holds a value not of its type, or is not a finite collection; a `Symmetry` holds something other than model values |
| `bad-model` | A `Model` field that does not exist or has the wrong form; a model of something that is no specification or contract |
| `unsupported` | A construct outside §4 |
| `bad-write` | A body assigns a constant, `Modifies` names a constant, or a `Pure` body writes state |
| `missing-mapping` | A refinement does not say what an abstract variable or constant is |
| `bad-arity` | An operator, action or builtin called with the wrong number of arguments |
| `unannotated-mutator` | *warning*: a public method writes state but is no action |
| `symmetry-dropped` | *warning*: a `Symmetry` the model cannot use (§5.4) |
| `unused-domain` | *warning*: a domain no parameter of the model uses |

`tests/conformance` holds a fixture for every code; each fixture marks, on
the line it belongs to, each diagnostic the front-end must give.

## 10. The front-end

```
python -m temporal_typing [--root DIR] [--json] [-q] PATH ...
```

reads the files and directories given, and prints every diagnostic, then a
line per model saying what a checker would check of it: its actions,
invariants, properties, constraints, symmetry and domains. It exits 1 when
there is an error. `--root` adds a directory to search for imports before the
files' own; `--json` gives the same as JSON.

From Python:

```python
from temporal_typing.frontend import load

program = load(["examples/"])
for model in program.models:
    if program.errors_of(model):
        ...  # the verdict is ERROR, with these diagnostics
    else:
        ...  # translate model.spec, model.domains, model.constants, ...
```

`load` gives a `Program`: its `specs`, `contracts`, `models` and
`diagnostics`. Each model carries its specification or contract, already
merged along the MRO, with frames inferred, constants bound and domains
resolved to tuples of values keyed by `"action.param"`. A `TypeRef` is
whole: a `seq` or `set` has one type argument, a `dict` two, a union two or
more, and a type with a part that cannot be read is no type, with an error.
`Program.diagnostics_of(model)` and `errors_of(model)` give the diagnostics
of what the model reads (§1). Every `Model(...)` the files hold is in
`models`, so each gets a verdict: one whose specification cannot be read has
`spec` None, and errors. The front-end has no dependency, runs nothing it
reads, and reads any input in bounded time: what is nested too deeply, or
holds more than a million values, is refused as `unsupported`.

## 11. Conformance

A checker conforms to a `temporal-typing` release when it gives the expected
verdict for every case in that release's conformance suite, `tests/checker`.
Each case is a Python file whose module docstring states the verdict expected
for each model, by kind and name (`PASS`, `FAIL conformance inc`, `ERROR
unknown-name`), and the warnings it gets (`PASS (warns symmetry-dropped)`).
This repository checks every case's ERROR verdicts and warnings with the
front-end, and that every other case runs as plain Python.

## 12. Prior work

A prototype checker lived in Manyan at
[soasme/manyan@41a7aac](https://github.com/soasme/manyan/blob/41a7aac/python/manyan/temporal.py).
It translates to TLA⁺ and checks conformance as §5.2 does. Where it fell
short of this document is listed in [ROADMAP.md](../ROADMAP.md).
