# `Lynx.Case`
[🔗](https://github.com/josevalim/lynx/blob/v0.1.0/lib/lynx/case.ex#L1)

Define callable laws alongside ExUnit tests.

Add `use Lynx.Case` after `use ExUnit.Case`, then group laws to verify together:

    use ExUnit.Case, async: true
    use Lynx.Case

    laws "identity" do
      law identity(value), requires: value, expects: value,
        proof: ~LEAN"exact requires"
    end

Each group registers one ExUnit test of type `:laws`. Run groups with
`mix test --only laws`.

Set `LYNX_DEBUG=lean` to print each translated module's reported
verification time in milliseconds, status, and whether it was cached,
as well as the elaboration time of any law. The translated .lean files are
also written by module path to `tmp/<test module>/<group>/` for inspection.
Set `LYNX_DEBUG=olean` to also write the compiled `.olean` files of every
verified module next to its source, so Lean tools such as profilers can load
the translated modules by adding the directory to `LEAN_PATH`.

Set `LYNX_CACHE=0` to disable the verification cache.

Lean's warnings and information messages are printed with their locations
whenever a group verifies, including from cached results.

Set `LYNX_EXPORT=dir` to write each group's elaborated declarations to
`dir/<test module>/<group>.ndjson` for independent kernel checks, as
described in `Lynx`. Exporting bypasses the verification cache.

Lean's own environment variables reach the Lean processes that verify each group.
For example, set `LEAN_NUM_THREADS=n` to elaborate the proofs of a translated
module on at most `n` threads, instead of one per core. Groups verify
concurrently, each in its own process with its own threads.

# `cutoff`
*macro* 

Leaves a function untranslated in this laws group.

    cutoff &Float.invalid_precision_message/1

The function's body becomes `Lynx.Except.cutoff`, which raises
`Lynx.Exception.exhausted`: not a return value or an Erlang exception, and
no handler catches it. A successful-return proof must establish that the
cutoff is never reached. This supports proofs whose unreachable error paths
depend on libraries outside the model; it makes no claim about executing those
paths. The function remains pure (see the purity model in `Lynx`).

Functions built into Lean cannot be cut off.

# `dynamic`
*macro* 

Declares a function that calls by name may reach in this laws group.

    dynamic &:erlang.apply/2

Calls whose module or function is computed, such as `apply(mod, fun, args)`
or `mod.fun(x)`, and computed references, such as `&mod.fun/1`, are resolved
when the program runs. Lean cannot load code at that point, so they reach
only the declared functions and those the program captures by name, such as
`&Module.function/arity`. Calls to other functions raise
`Lynx.Exception.exhausted`, like a `cutoff`, so a successful-return proof must
establish that they are not reached. Declared functions are translated with
the program.

# `law`
*macro* 

Defines a callable law and includes it in the current laws group.

The must be explicitly declared in a `laws/2` block.

## Options

  * `:requires` (optional) — the precondition expression. Defaults to `true`.
  * `:expects` — the expression to prove.
  * `:reaches` — instead of `:expects`, an expression over concurrent code
    that some run makes true (`Lynx.reachable`).
  * `:proof` (optional) — a `Lynx.Lean` value. Defaults to `rfl`.

## Executable definition

Besides defining a law, `law/2` also defines a public function that you can
invoke passing Elixir values. Elixir will then validate said values against the
given `:requires`, the given `:expects`, and return true when both predicates
succeed, otherwise it will raise. This is useful to provide counter examples.

# `laws`
*macro* 

Registers a group of laws as one ExUnit test.

The test translates the laws and their callees, verifies their proofs,
and fails if they do not pass.

Each group has the `:laws` test type and tag. Run only law groups with
`mix test --only laws`.

## Options

  * `:options` (optional) — a keyword list of Lean options, such as
    `[maxHeartbeats: 1_000_000, maxRecDepth: 10_000]`, set at the top of every
    translated module of the group, including its laws. Names are passed to
    Lean as given. Proofs remain kernel-checked.

## Example

    laws "checked" do
      law checked(value),
        requires: value,
        expects: value,
        proof: ~LEAN"exact requires"
    end

If verifying the laws fail, the error report includes the path to folder with
all `.lean` files. Use this to debug and guide your proofs.

# `postlude`
*macro* 

Adds Lean declarations about translated definitions to this laws group.

    postlude ~LEAN"""
    namespace MyTest

    theorem double_integer (n : Int) : «double/1» (.integer n) = .ok (.integer (n + n)) := by
      simp [«double/1»]

    end MyTest
    """

Blocks are joined in order into one Lean module, which imports every module
translated for the group, including the prelude, and which the laws import.
Unlike preludes, postludes may refer to translated definitions, so they can
share lemmas about the translated code between the proofs of several laws.
Lynx writes the module header, so blocks contain only declarations, which are
public and expose their bodies. Namespaces are chosen by the source: the
test module's namespace, such as `MyTest` above, makes declarations available
to law proofs without qualification.

Postludes do not translate anything themselves: the laws must reach every
definition they mention. They do not leak into other groups, and their source
participates in verification cache keys. Proofs retain kernel checking and
axiom audits.

As with `prelude/1`, a file path may be given instead, relative to the
directory of the calling file.

# `prelude`
*macro* 

Adds Lean declarations to the prelude for this laws group.

    prelude ~LEAN"""
    module
    public import Lynx
    public section

    open Lean Elab Tactic
    elab "finish" : tactic => do evalTactic (← `(tactic| rfl))
    """

Blocks are joined in order into one Lean module, so the first block begins
with its header, such as `module` and its imports, which may include runtime
modules like `Lynx.Modules.Erlang.erlang`. Later blocks continue the module.
Every translated module imports the prelude before its proofs and termination
suffixes are parsed, along with the prelude's public imports. Definitions,
lemmas, macros, and elaborators may be declared; namespaces are chosen by the
source. Meta helper definitions must use Lean's `meta` modifier as usual.

The prelude cannot refer to translated definitions, which do not exist yet.
It does not leak into other groups, and its source participates in verification
cache keys. Proofs retain kernel checking and axiom audits.

A file path may be given instead, relative to the directory of the calling
file, to load its contents with `Lynx.Lean.from_file!/1`:

    prelude "tactics.lean"

# `termination_suffix`
*macro* 

Attaches a Lean termination suffix to a translated function for this laws group.

    termination_suffix &:calendar.mod/2, ~LEAN"partial_fixpoint"

The source is a `Lynx.Lean` value. It is parsed as part of the function's
declaration, after its body. The suffix does not change the function's purity
(see the purity model in `Lynx`). With `partial_fixpoint`, inputs on which
the function diverges raise `Lynx.Exception.exhausted`.
Raises if the target function is not translated by the group's laws.

Pass `recur: true` to also attach the suffix to the functions mutually
recursive with the target that have no suffix of their own. Lean requires
every function in a mutually recursive group to be a partial fixpoint once
one of them is:

    termination_suffix &Module.Types.Descr.unfold/1, ~LEAN"partial_fixpoint", recur: true

A function with `partial_fixpoint` also gets a `fixpoint_induct` principle,
which proves properties of every successful return without a termination
measure, as returns on divergent inputs never happen. For a pure function of
`n` arguments, `Lynx.Except.admissible_returnsN` discharges its admissibility
goal:

    apply «mod/2».fixpoint_induct
      (motive := fun f => ∀ a b v, f a b = .ok v → post a b v)
    · exact Lynx.Except.admissible_returns2 _
    · intro f ih a b v returned
      ...

---

*Consult [api-reference.md](api-reference.md) for complete listing*
