# Guide

How to write specifications with `temporal-typing`. [semantics.md](semantics.md)
is the reference; this is the tour.

## 1. A specification is a class

State is a field, a clause is a keyword of `@spec`, and an action is a
method:

```python
from typing import Annotated, Protocol
from temporal_typing import Action, Init, Invariant, Model, Requires, State, prime, spec


@spec(
    init=Init(lambda s: s.x == 0),
    bounded=Invariant(lambda s: 0 <= s.x <= 10),
)
class Counter(Protocol):
    x: State[int]

    def increment(self) -> Annotated[
        None,
        Requires(lambda s: s.x < 10),
        Action(lambda s: prime(s.x) == s.x + 1),
    ]: ...

    def reset(self) -> Annotated[None, Action(lambda s: prime(s.x) == 0)]: ...


model = Model(Counter)
```

In every predicate `s.x` is the value now and `prime(s.x)` the value after
the step. An action changes only what it says it changes: `increment` leaves
every variable but `x` alone.

`@spec` adds nothing to the class's type, so `Counter` is still a protocol
any class with an `x` and the two methods satisfies.

## 2. Code that is its own specification

Give the method a body and `Action()` without a predicate, and the body is
the transition:

```python
from dataclasses import dataclass


@spec(bounded=Invariant(lambda s: 0 <= s.x <= 10))
@dataclass
class Counter:
    x: State[int] = 0  # the default is part of the initial state

    def increment(self) -> Annotated[None, Requires(lambda s: s.x < 10), Action()]:
        self.x += 1
```

The class is ordinary Python: `Counter().increment()` runs, with no checking
at run time.

## 3. Code checked against its specification

Give the method both a body and a predicate, and the checker checks the body
does what the predicate says, in every reachable state, for every argument:

```python
def withdraw(self, amount: Positive) -> Annotated[
    Positive,
    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
```

If someone later changes the body to `self.balance -= amount + 1`, the
specification and the code disagree, and the check fails with the state and
the argument where they do. An `assert` in a body is checked the same way.

## 4. Refined types

A `Where` on a type is a set comprehension. Define the type once:

```python
from temporal_typing import Constant, Where

Positive = Annotated[int, Where(lambda x: x > 0, "positive")]
NonNegative = Annotated[int, Where(lambda x: x >= 0, "non-negative")]
```

On a constant it is an assumption, on a variable an invariant, on a
parameter a guard, and on a return type an obligation.

## 5. Function contracts

A function with `Requires` or `Ensures` is checked on its own, over the
arguments its model gives:

```python
from temporal_typing import Ensures, Pure, Requires


def clamp(value: int, low: int, high: int) -> Annotated[
    Pure[int],
    Requires(lambda low, high: low <= high),
    Ensures(lambda value, low, high, result: low <= result <= high),
]:
    return max(low, min(value, high))


clamp_model = Model(clamp, domains={int: range(-3, 4)})
```

## 6. Fairness and liveness

A `Property` is a temporal formula; a `Fairness` clause is what the system
may assume about the scheduler:

```python
from temporal_typing import Fairness, ModelValue, Property, leads_to, strong_fairness, weak_fairness


class Proc(ModelValue):
    pass


@spec(
    init=Init(lambda s: s.holder is None and s.waiting == frozenset()),
    fair=Fairness(lambda s: all(strong_fairness(s.acquire(p)) and weak_fairness(s.release(p)) for p in s.procs)),
    starvation_free=Property(lambda s: all(leads_to(p in s.waiting, s.holder == p) for p in s.procs)),
)
class Mutex(Protocol):
    procs: Constant[frozenset[Proc]]
    holder: State[Proc | None]
    waiting: State[frozenset[Proc]]

    def request(self, p: Proc) -> Annotated[
        None,
        Requires(lambda s, p: p not in s.waiting and s.holder != p),
        Action(lambda s, p: prime(s.waiting) == s.waiting | {p}),
    ]: ...

    def acquire(self, p: Proc) -> Annotated[
        None,
        Requires(lambda s, p: p in s.waiting and s.holder is None),
        Action(lambda s, p: prime(s.holder) == p and prime(s.waiting) == s.waiting - {p}),
    ]: ...

    def release(self, p: Proc) -> Annotated[
        None,
        Requires(lambda s, p: s.holder == p),
        Action(lambda s, p: prime(s.holder) is None),
    ]: ...
```

`weak_fairness(s.release(p))` is `WF_vars(release(p))`: the action is called
like a method, and `on=` gives another subscript. Strong fairness on
`acquire` is what makes `starvation_free` hold: under weak fairness a waiting
process can lose the lock forever.

## 7. Refinement

A ring buffer is a queue. Say how its state maps onto the queue's, and the
checker checks every ring-buffer behaviour is a queue behaviour, fairness
included:

```python
from temporal_typing import Refines


def refines_queue(self) -> Refines[BoundedQueue[T]]:
    return Refines(
        capacity=self.capacity,
        items=tuple(self.buf[(self.head + i) % self.capacity] for i in range(self.size)),
    )
```

The method is real Python too: calling it gives the queue a ring buffer
stands for, which a test can compare with a real queue. See
[examples/bounded_queue.py](../examples/bounded_queue.py).

## 8. Models

A model makes a specification finite: values for its constants and finite
domains for the types it quantifies over, keyed by type:

```python
from temporal_typing import Symmetry

PROCS = frozenset({Proc("p1"), Proc("p2"), Proc("p3")})

model = Model(Mutex, constants={"procs": PROCS}, domains={Proc: PROCS})
safety = Model(Mutex, constants={"procs": Symmetry(PROCS)}, domains={Proc: PROCS}, properties=())
bounded = Model(Counter, state_constraint=lambda s: s.x < 5)
```

- A domain is any finite collection: `range`, `frozenset`, a list.
- A domain is never made up: a type the check needs and the model does not
  give is an error. `bool`, `Literal[...]` and an `Enum` need none.
- A `Symmetry` set lets the checker treat permutations of its model values as
  one state. It is dropped, with a warning, when the model checks a temporal
  property or a refinement, where it would hide behaviours.
- `actions`, `invariants` and `properties` pick clauses by name. A name that
  does not exist is an error, not a check of nothing.
- `state_constraint` bounds the search: a result holds of the states the
  search reached.

## 9. Checking

`temporal-typing` does not check; checkers do, as `mypy` does for `typing`.
`python -m temporal_typing PATH ...` reads your declarations the way every
checker does and reports what it finds wrong with them: an unknown name, a
predicate parameter that binds nothing, a `prime` in an `Invariant`, Python a
checker cannot give its meaning to, a type with no domain. A file it reports
nothing for is one a checker can check.

```
$ python -m temporal_typing examples/bank_account.py
examples/bank_account.py:75: small_account_model: BankAccount; 2 actions; invariants within_limit, ledger_matches_balance, ledger_append_only; bounded by a constraint; deposit.amount in 1..3; withdraw.amount in 1..3
1 file: 1 specification, 0 contracts, 1 model; 0 errors, 0 warnings
```

Predicates and bodies are a subset of Python, given its Python meaning:
integers, booleans, strings, `None`, tuples, frozensets, dicts and model
values; arithmetic (with `//`, not `/`), comparisons, comprehensions and the
common builtins; in bodies, assignment, in-place changes of the state's
lists, sets and dicts, `if`, `for`, `while`, `assert` and `raise`. `try`,
`with`, I/O and calls into other libraries are not in it.
[checker.md §4](checker.md) has the whole of it.

What a checker's result means:

- **PASS** holds for the finite model only: those constants, those domains,
  the states the constraint let it reach. A checker says which.
- **FAIL** comes with a behaviour: the states, the actions and their
  arguments. A *conformance* failure is a step where a method's body and its
  `Action` disagree: it names the action, its arguments, the state before,
  and the variable or clause where the two part. Fix whichever is wrong; the
  point is that they can no longer differ silently.
- **ERROR** means nothing was checked, and says why.

## 10. Type checkers

The package is typed (PEP 561) and its declarations are ordinary `typing`
constructs, so `mypy --strict` and Pyright check a specification like any
other code. In Pyright's strict mode, prefer named predicate functions to
lambdas, whose parameters it cannot infer.
