Lynx.Laws (Lynx v0.1.0)

Copy Markdown View Source

Define executable laws, their Lean proofs, and verify them.

Elixir example

These examples omit Lean proofs. See the README for complete proofs.

defmodule Sum do
  use Lynx.Laws

  def sum([]), do: 0
  def sum([x | xs]), do: x + sum(xs)

  law sum_empty,
      expects: sum([]) == 0,
      proof: ~LEAN"""
      PROOF GOES HERE
      """
end

Call Sum.sum_empty/0 to check the law at runtime. Add a proof: ~LEAN"..." option to verify it with Lynx.Laws.verify([Sum]).

Erlang example

Each -law attribute names an ordinary predicate function:

-module(sum).
-export([sum/1, sum_empty_ensures/0]).

-law #{name => {sum_empty, []}, ensures => sum_empty_ensures}.
-proof ~"""
GOES HERE
""".

sum([]) -> 0;
sum([X | Xs]) -> X + sum(Xs).

sum_empty_ensures() -> sum([]) == 0.

Add a binary -proof attribute immediately after the -law attribute, then call Lynx.Laws.verify([:sum]) to verify the law.

The -law map accepts these keys:

  • name (required) — {law_name, argument_names}, where the argument names become Lean theorem parameters.
  • ensures (required) — the name of the predicate function to prove.
  • requires (optional) — the name of the precondition function. Omit it for an unconditional law.

Both predicate functions receive the law's arguments in order. Their results must be true for the precondition to hold or the law to succeed. The predicate functions remain callable from Erlang; -law does not generate a wrapper.

Summary

Types

A verification diagnostic, with source location when available.

The verification result for a translated module.

Functions

Defines a callable law with an optional precondition and a Lean proof.

Verifies all laws in the given modules.

Types

diagnostic()

@type diagnostic() :: %{
  optional(:line) => pos_integer(),
  optional(:column) => pos_integer(),
  file: String.t(),
  module: String.t(),
  declaration: String.t() | nil,
  severity: :error | :warning | :information,
  message: String.t()
}

A verification diagnostic, with source location when available.

report()

@type report() :: %{
  status: :ok | :error | :skipped,
  file: String.t(),
  module: String.t(),
  time_ms: non_neg_integer(),
  cached: boolean(),
  theorems: [%{name: String.t(), time_ms: non_neg_integer()}],
  diagnostics: [diagnostic()]
}

The verification result for a translated module.

Functions

law(call, opts)

(macro)

Defines a callable law with an optional precondition and a Lean proof.

The first argument is a local function declaration, such as checked(x) or sum_empty. Arguments must be distinct named variables: patterns, literals, and _ are not accepted. Those names become the Lean theorem parameters.

Options

  • :requires (optional) — an Elixir expression describing the precondition. It must evaluate to exactly true for the expected expression to be evaluated. Defaults to true.

  • :expects — the Elixir expression to prove. It must evaluate to exactly true whenever the precondition holds.

  • :reaches — instead of :expects, an Elixir expression over concurrent code that evaluates to exactly true in some run, whenever the precondition holds in every run. It shows an outcome is possible, such as each branch of a race, and is stated through Lynx.reachable. Each law has one; use one law per outcome.

  • :proof (optional) — a Lynx.Lean value containing the Lean tactic proof, usually built with ~LEAN. Both inline and heredoc sigils are accepted. Defaults to rfl, which only proves goals that hold by definitional equality.

Example

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

Executable definition

Besides defining a law, this macro 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 or :reaches, and return true when both predicates succeed, otherwise it will raise. This is useful to provide counter examples.

verify(modules, opts \\ [])

@spec verify([module() | binary()], keyword()) :: [report()]

Verifies all laws in the given modules.

This is useful for verifying laws in Erlang modules or those using Lynx.Laws directly. For ExUnit integration, see Lynx.Case.

The laws and proofs for all modules given are verified together within a single Lean execution. You must either pass module atoms available on the code path or BEAM binaries for modules compiled in memory. Modules must be compiled with debug info in all cases.

Returns one report per translated module, in dependency order, including dependencies.

A report's :status is :ok when verification succeeds, :error when it fails, or :skipped when a dependency failed. Lean verification failures are returned as reports with :diagnostics; they do not raise. Check that every report has status: :ok to establish successful verification.

Reports also include the source :file, translated :module name, :time_ms, and whether a cached result was used (:cached). See report/0 and diagnostic/0 for the complete structure.

:theorems lists each law's name (including its arity) and elaboration time in milliseconds. Cached and skipped modules have an empty list.

Pass termination_suffixes: %{{module, function, arity} => lean_source} to attach a Lynx.Lean termination suffix to a translated function. The suffix does not change the function's purity (see the purity model in Lynx). Targets must be translated by the laws being verified; annotations do not add translation roots. A value of {lean_source, recur: true} also attaches the suffix to the functions mutually recursive with the target that have no suffix of their own, as with Lynx.Case.termination_suffix/3.

Pass cutoffs: [{module, function, arity}] to leave selected functions untranslated. Calls to these functions raise Lynx.Exception.exhausted, which no handler catches; successful-return proofs must show they are unreachable. No return values or Erlang exceptions are assumed for a cutoff.

Pass dynamic: [{module, function, arity}] to declare the functions that calls by name may reach, as with Lynx.Case.dynamic/1.

Pass preludes: [source, ...] to load Lynx.Lean declaration blocks before translated definitions and proofs, as with Lynx.Case.prelude/1.

Pass postludes: [source, ...] to load Lynx.Lean declaration blocks after translated definitions and before proofs, as with Lynx.Case.postlude/1.

Pass options: [name: value] to set Lean options, such as maxHeartbeats or maxRecDepth, at the top of every translated module. Names are passed to Lean as given. Proofs remain kernel-checked.

Pass debug_dir: dir to write the Lean source of every translated module to dir by module path, such as dir/Erlang/json.lean, when a module does not verify. Also pass debug: :lean to write them even when every module verifies. The sources show the translated code, which is useful when writing proofs. Pass debug: :olean to also write the compiled files of every verified module next to its source, such as dir/Erlang/json.olean. Adding dir to LEAN_PATH then lets Lean tools, such as profilers, load the translated modules by name.

Pass export: path to write the elaborated declarations of the translated modules, with their dependencies, in Lean's export format. Check them with Lean's kernel and the independent checkers bundled with Lean using lake check --from-export, as described in Lynx. Exporting bypasses the verification cache, and the export is written only when every module verifies.

Raises on translation failures, including modules without laws or unsupported code, and on failures to run Lean or read its response.