# Semantics

This document defines what `temporal-typing` declarations mean, in TLA⁺
(*Specifying Systems*, Lamport 2002). [checker.md](checker.md) defines what a
checker must do with them.

Declarations are passive. Importing a module, decorating a class,
constructing a clause or a `Model`, instantiating a class and calling its
methods never run a predicate. The expression primitives (`prime`,
`always`, ...) raise `NotImplementedError` if Python calls them.

## 1. Units

A **specification** is a class: plain, `@dataclass`, `typing.Protocol` or
`Generic`. Its declarations are:

| Declaration | Where | TLA⁺ |
| --- | --- | --- |
| `c: Constant[T]` | class field | `CONSTANT c` |
| `v: State[T]`, `g: Ghost[T]` | class field | `VARIABLE v`, `VARIABLE g` |
| `@spec(name=Clause(...), ...)` | class decorator | named clauses (§4) |
| `def op(self, ...) -> Pure[T]` | method or property | operator `op` |
| `def act(self, ...) -> Annotated[R, Action(...), ...]` | method | action `act` (§5) |
| `def m(self) -> Refines[A]` | method | refinement mapping (§8) |

A **contract** is a module-level function whose return annotation carries
`Requires` or `Ensures` (§7).

A `Model` (§9) names one specification or contract and makes it finite.

`Ghost` variables are variables the specification keeps and the
implementation need not: a history, a prophecy. They are in `vars` like any
other.

### Inheritance

A class has the declarations of its bases, in Python's method resolution
order. A method that overrides an action of a base keeps the base's clauses:
the override's body must conform to the base's `Action` predicate and
satisfy its `Requires`, `Ensures` and `Modifies`. A base's clauses become the
subclass's own, assumptions included. Inheritance is composition, not
refinement; refinement is `Refines` (§8).

## 2. Levels

Every expression has a TLA⁺ level, and every clause allows up to one:

| Level | Allows | Clauses |
| --- | --- | --- |
| 0, constant | constants, constant operators | `Assume`, `Where` on a `Constant` |
| 1, state | level 0 and variables | `Init`, `Invariant`, `Requires`, `Where` elsewhere, `Pure` operators, `Model.state_constraint` |
| 2, action | level 1 and `prime`, `unchanged`, `enabled`, `result` | `Action`, `ActionInvariant`, `Ensures`, `Model.action_constraint` |
| 3, temporal | level 2 and `always`, `eventually`, `leads_to`, `weak_fairness`, `strong_fairness` | `Property`, `Fairness` |

`enabled(A)` is a state-level expression, so an `Invariant` may use it.
`weak_fairness` and `strong_fairness` belong in `Fairness` only.

## 3. Values and types

A declared type gives the set of values a name takes:

| Python type | Values |
| --- | --- |
| `int`, `bool`, `str`, `None` | integers, booleans, strings, the one value `None` |
| `tuple[T, ...]`, `list[T]` | finite sequences |
| `frozenset[T]`, `set[T]` | finite sets |
| `dict[K, V]` | finite functions from keys to values |
| `Optional[T]`, `T \| None` | `T` and `None` |
| `Literal["a", "b"]`, an `Enum` | those values |
| a `ModelValue` subclass | the model values of that sort the model gives |
| a type variable | the values the model gives |

No other type, a class's included, has values a checker can give it.

`Annotated[T, Where(p)]` is `{x \in T : p(x)}`. Several `Where` clauses are
conjoined. Where it sits decides what it obliges:

| Position | Meaning |
| --- | --- |
| `c: Constant[Positive]` | an assumption: `ASSUME p(c)` |
| `v: State[Positive]`, `Ghost[...]` | an invariant: `[]p(v)` |
| an action or function parameter | part of the guard: only such arguments are taken |
| a return type | an obligation on `result` |

Values have their Python meaning, not TLA⁺'s where the two differ: `//`
floors, `%` takes the sign of the divisor, sequences are indexed from 0 and
from the end with negative indexes, `and` and `or` give an operand, an empty
collection is false. A Python error in the checked behaviour (an index out of
range, a missing key, division by zero, a failed `assert`) is a failure of
the specification, not an undefined value.

## 4. Class clauses

`@spec` names each clause by its keyword. The predicate's one parameter, `s`,
is the specification's state.

| Clause | Means |
| --- | --- |
| `Assume(p)` | `ASSUME p`, of the constants |
| `Init(p)` | `p` holds in the initial state |
| `Invariant(p)` | `[]p` |
| `ActionInvariant(p)` | `[][p]_vars`: every step satisfies `p`, over `s.x` and `prime(s.x)` |
| `Property(p)` | the temporal formula `p` holds of every behaviour |
| `Fairness(p)` | `p`, of `weak_fairness` and `strong_fairness`, is assumed |

**Init** is the conjunction of the `Init` clauses and, for each variable with
a class-level default (`x: State[int] = 0`, a dataclass field's default),
`x = default`. `__init__` is ordinary Python and does not take part. A
variable that has no default and that no `Init` clause mentions is an
error.

**Spec** is

$$\text{Init} \land \square[\text{Next}]_{\text{vars}} \land \text{Fairness}$$

where `vars` is every `State` and `Ghost` variable, `Next` is §5's, and
`Fairness` is the conjunction of the `Fairness` clauses. Each `Assume`,
`Invariant`, `ActionInvariant` and `Property` is then a claim about `Spec`.

## 5. Actions

A method is an action when its return annotation carries `Action`:

```python
def withdraw(self, amount: Positive) -> Annotated[
    Positive,                                      # what the method returns
    Requires(lambda s, amount: amount <= s.balance),
    Action(lambda s, amount: prime(s.balance) == s.balance - amount),
    Ensures(lambda s, amount, result: result == amount),
    Modifies("balance"),
]:
    self.balance -= amount
    return amount
```

Predicates bind their first parameter to the state and the others to the
method's parameters **by name**, with `result` for the return value in
`Ensures`; a predicate may leave out parameters it does not use. In every
predicate, `s.x` is the value before the step and `prime(s.x)` the value
after it.

| Clause | At most | Means |
| --- | --- | --- |
| `Requires(p)` | any number, conjoined | the guard: the action is enabled only where `p` holds |
| `Action(p)` / `Action()` | one | the action's transition, below |
| `Ensures(p)` | any number, conjoined | every step of the action satisfies `p` |
| `Modifies(v, ...)` | one | the action changes no variable but these |

### Transition

The **body** is the method's code, unless it is `...` (with or without a
docstring), which means the method has none. A body of `pass` is a body: it
changes nothing.

- With a body, the body is the transition: running it from the state `s`
  with arguments `args` gives the next state. A path that ends in `raise`
  gives no next state: the call fails.
- With no body, `Action(p)`'s predicate is the transition. `Action()` with no
  body is an error.

For each action $A$ with parameters $p_1, \dots, p_k$ of types $T_1,\dots,T_k$:

$$A^{\exists} \triangleq \exists p_1 \in D_1, \dots, p_k \in D_k : \text{Guard}_A \land \text{Transition}_A \land \text{Frame}_A$$

where $D_i$ is the domain of $T_i$ (§9), and $\text{Next} \triangleq \bigvee_A A^{\exists}$.

### Frame

An action changes only the variables in its frame, and leaves every other
variable unchanged:

1. with `Modifies(...)`, the variables it lists;
2. otherwise, with a body, the variables the body assigns or mutates;
3. otherwise, the variables its predicate puts under `prime(...)`.

A `Ghost` variable the body does not assign takes the value the predicate
gives it, so an implementation need not keep a ghost.

### Conformance

An action with both a predicate and a body claims the body implements the
predicate. In every reachable state, for every argument in the domains where
the guard holds, the step the body takes satisfies `Action`'s predicate,
every `Ensures`, the `Where` on the return type, the frame, and every
`assert` the body reaches. This is how a specification and the code it
describes are kept from drifting apart.

## 6. Operators

A method, property or function returning `Pure[T]` is an operator:
predicates may use it (`s.available`), and its body must not change state.

## 7. Contracts

A module-level function with `Requires` or `Ensures` on its return type is
checked on its own: for every argument tuple in the domains where every
`Requires` and parameter `Where` holds, the body returns, and the result
satisfies every `Ensures` and the return type's `Where`. Its predicates bind
the function's parameters by name, and `result`.

## 8. Refinement

A method annotated `-> Refines[A]` that returns `Refines(v=e, ...)` maps the
state of its class `C` onto the specification `A`: each of `A`'s constants
and variables is given by an expression over `C`'s. It claims

$$C!\text{Spec} \implies \overline{A}!\text{Spec}$$

under the mapping, which is all of:

1. `A`'s `Init`,
2. `[][A!Next]_(A!vars)`, so `C` may take a step `A` stutters on,
3. every `Fairness` of `A`,
4. every `Invariant`, `ActionInvariant` and `Property` of `A`.

## 9. Models

`Model` is the Python form of a TLC `.cfg`:

| Field | Means |
| --- | --- |
| `spec` | the specification class or contract function |
| `constants` | a value for each `Constant`, by name; a constant's class-level default is used where none is given |
| `domains` | a finite collection for each type the check quantifies over |
| `actions` | the actions in `Next`, by name; all when `None` |
| `invariants` | the `Invariant`s and `ActionInvariant`s checked, by name; all when `None` |
| `properties` | the `Property`s checked, by name; all when `None` |
| `state_constraint` | `CONSTRAINT`: the search does not go past a state where it is false |
| `action_constraint` | `ACTION_CONSTRAINT`, of a step |
| `check_deadlock` | whether a reachable state with no next state is a failure |

### Domains

`domains` is keyed by type: a class (`int`, `Proc`), a type alias
(`Positive`), or a type variable (`T`). The domain of a declared type is the
first that applies:

1. the entry for the type as written, alias included (`Positive`);
2. for `Optional[T]`, the domain of `T` and `None`;
3. for `bool`, `Literal[...]` and an `Enum`, all their values;
4. the entry for the type under its `Where` clauses (`int` for `Positive`).

A `Where` then narrows the domain. A type with no domain, where the check
needs one, is an error: a checker does not make one up.

### Symmetry

A constant whose value is a `Symmetry` set declares that permuting its model
values maps behaviours to behaviours (TLC's `SYMMETRY Permutations(S)`). The
reduction is unsound for temporal properties, so a model that checks a
`Property` or a refinement does not use it.

## 10. Expression primitives

| Primitive | TLA⁺ | Level |
| --- | --- | --- |
| `implies(p, q)` | `p => q` | any |
| `choose(S, pred)`, `choose(S)` | `CHOOSE x \in S : pred(x)`, `: TRUE` | 1 |
| `prime(e)` | `e'` | 2 |
| `unchanged(e, ...)` | `UNCHANGED <<e, ...>>` | 2 |
| `enabled(s.a(args))` | `ENABLED a(args)` | 1 |
| `always(p)` | `[]p` | 3 |
| `eventually(p)` | `<>p` | 3 |
| `leads_to(p, q)` | `p ~> q` | 3 |
| `weak_fairness(s.a(args), on=e)` | `WF_e(a(args))`, `e` being `vars` when omitted | 3 |
| `strong_fairness(s.a(args), on=e)` | `SF_e(a(args))` | 3 |

Inside predicates, `all(...)` and `any(...)` over finite collections are
`\A` and `\E`, comprehensions are set, sequence and function constructors,
and the rest of Python means what Python means, within the subset of
[checker.md §4](checker.md).
