Pythonic contract syntax
Reference for the Pythonic .lema contract surface and the restricted .lean implementation and proof language over canonical store objects, including scope boundaries, grammar, structural rederive, and display-bound review digests.
Lema separates what a module promises from how it is implemented and proved across two file formats that compile into the same content-addressed store (lema.core/v4, Objects and identity):
- The Pythonic
.lemasurface (crates/lema-core/src/view.rs): A dedicated contract, law, and simple-expression language for reading, reviewing, and authoring definitions over existing types (def), proposition claims (def ... -> Prop), theorem statements (law), multi-law specification records (contract), and contract selections (select). Every.lemadeclaration can be parsed, rendered, and structurally re-derived (view::rederive) in pure Rust with zero Lean or Python runtime. - Restricted
.leanoverInit(crates/lema-cli/src/): The implementation, data-type, and proof language used to declare new inductive types (inductive), operational records with value fields (structure), recursive or pattern-matching implementations, and kernel-checked proof terms (theorem ... := ...).
What .lema covers vs. what lives in .lean
Because .lema is designed so that every rendered contract view can be round-tripped back to its exact statement and template SHA-256 object IDs without running the Lean elaborator (view::rederive), .lema intentionally covers specifications, laws, and expression-level definitions, not data-type declarations or proof scripts:
| Construct | Authored in .lema? | Authored in .lean? | Why |
|---|---|---|---|
Pure expression definition (def f(x: T) -> U:) | Yes | Yes | Expression bodies built from function calls, operators, let, if/then/else, fn, pairs, lists, and literals lower directly via view::lean_declaration and round-trip through view::rederive. |
Proposition claim (def P(x: T) -> Prop:) | Yes | Yes | A Prop-valued def states a reusable property that can be selected with select P(impl). |
Theorem statement (law name(...): with requires / ensures) | Statement only (via lema view or paired with --proof in lema publish) | Full theorem name ... := proof | .lema displays and parses the theorem’s statement (law), never tactic scripts or proof terms. In lema add, theorems with proof terms are authored in .lean files (while lema publish on a single .lema law accepts the proof expression via --proof / --proof-file). |
Multi-law specification structure (contract Name(ops: T):) | Yes (Prop-valued fields only) | Yes (structure Name (ops : T) : Prop where) | A .lema contract block defines a Prop-valued structure whose fields are law propositions. It is accepted by the kernel with zero proof obligations until selected. |
Contract or claim selection (select Claim(impl)) | Yes | Via CLI / RPC (contract.select) | select is a codebase directive in .lema modules that creates an immutable lema.contract/v1 selection record in the store. |
New data types (inductive) and operational records (structure in Type) | No (authored in .lean; field projections like K.pre(s, c) render in .lema) | Yes | Inductive data types (Prog, Tree, HttpCmd), operational interfaces (Impl, EscrowStorage), and mixed structures that combine data functions with propositions (Contract C R S, whose next field returns S : Type) are declared in .lean. |
Pattern matching (match ... with), structural recursion, and tactic proofs (by simp, omega) | No | Yes | Multi-branch pattern matching, recursive definitions over inductives, and Lean proof terms live in .lean modules; their types and laws still render in .lema via lema view. |
Surface grammar mapping (.lema vs. Lean view)
Every construct in .lema maps one-to-one to a canonical kernel term construct and has the identical logical meaning as in Lean 4:
| Concept | Pythonic .lema contract syntax | Restricted Lean view |
|---|---|---|
Value or predicate definition (def) | def f(x: Nat, y: Nat) -> Nat:\n body | def f (x : Nat) (y : Nat) : Nat :=\n body |
Proposition claim (def ... -> Prop) | def PreservesZero(f: Nat -> Nat) -> Prop:\n f(0) == 0 | def PreservesZero (f : Nat → Nat) : Prop :=\n f 0 = 0 |
Theorem statement (law) | law t(x: Nat, h: x <= y):\n x <= y | theorem t (x : Nat) (h : x ≤ y) :\n x ≤ y |
| Precondition and postcondition spine | law safe(x: Int):\n requires x > 0\n ensures f(x) >= 0 | theorem safe (x : Int) :\n x > 0 → f x ≥ 0 |
Multi-law contract structure (contract) | contract LawfulStorage(ops: Storage):\n law get_put(k: Key, v: Val):\n ... | structure LawfulStorage (ops : Storage) : Prop where\n get_put : ∀ (k : Key) (v : Val), ... |
Contract or claim selection (select) | select LawfulStorage(MemoryStorage) | (Creates an immutable lema.contract/v1 record in the store) |
Universal quantifier (forall) | forall x: Nat :: P(x) | ∀ (x : Nat), P x |
Existential quantifier (exists) | exists x: Nat :: P(x) | ∃ x : Nat, P x |
Anonymous function (fn) | fn(x: Nat) -> x + 1 | fun (x : Nat) => x + 1 |
Local binding (let / have) | let y: Nat = v; body (have y: Nat = v; body in explicit view) | let y : Nat := v; body |
| Boolean and logical operators | and, or, not, <->, -> | ∧, ∨, ¬, ↔, → |
| Comparison and membership | ==, !=, <, <=, >, >=, in | =, ≠, <, ≤, >, ≥, ∈ |
Function application and explicit @ | f(x, g(y)) and @LE.le(Nat, inst, x, y) | f x (g y) and @LE.le Nat inst x y |
| Implicit and instance binders | {alpha: Type}, [inst: Ord(alpha)] | {α : Type}, [inst : Ord α] |
Unicode logical and comparison symbols (∀, ∃, ∧, ∨, ¬, ≠, ≤, ≥, →, ↔) are accepted when parsing .lema input, while canonical rendered views (render_declaration) always emit the ASCII spellings above.
Examples in both views
A definition, a proposition claim, and a selection (def and select)
In a .lema file, you can define an expression-level function (advance), state a Prop claim (Advances), and select that claim for the implementation (select Advances(advance)), creating a kernel-checked lema.contract/v1 selection record (Codebase records):
Pythonic
def advance(n: Nat) -> Nat:
n + 1
def Advances(f: Nat -> Nat) -> Prop:
forall n: Nat :: f(n) > n
select Advances(advance)Lean
These declarations express the same implementation and promise. Selection is a Lema codebase operation; the final comment names its target, without supplying a proof.
def advance (n : Nat) : Nat := n + 1
def Advances (f : Nat → Nat) : Prop :=
∀ n : Nat, f n > n
-- Selected proposition: Advances advanceExplanation
For every nonnegative integer n, the selected function must return a number greater than n. The implementation advance adds one.
Advances describes the promise independently of the implementation. Selecting Advances(advance) records an open obligation about that exact function. It becomes checked only when a matching proof is accepted.
The promise requires an increase, but does not require an increase of exactly one. A function that adds two would satisfy it too.
def advance(n: Nat) -> Nat:
n + 1
def Advances(f: Nat -> Nat) -> Prop:
forall n: Nat :: f(n) > n
select Advances(advance)def advance (n : Nat) : Nat := n + 1
def Advances (f : Nat → Nat) : Prop :=
∀ n : Nat, f n > nA theorem statement with requires and ensures (law)
When a theorem’s statement is an implication chain H1 → H2 → Goal, lema view renders the hypotheses as requires clauses and the conclusion as ensures. These are static logical hypotheses and conclusions in the theorem’s statement object, not runtime assertions inserted into compiled calls:
Pythonic
law nonnegative_step(x: Int):
requires x > 0
ensures x + 1 >= 0Lean
The arrow expresses implication: the postcondition follows when the precondition holds. This view shows the statement, without a proof term.
∀ x : Int, x > 0 → x + 1 ≥ 0Explanation
If the integer x is greater than zero, then x + 1 is nonnegative. The promise is conditional: it says what follows when the input satisfies the precondition.
These are logical conditions for a proof. They do not insert runtime assertions into calls, and this statement alone is not proof evidence.
law nonnegative_step(x: Int):
requires x > 0
ensures x + 1 >= 0∀ x : Int, x > 0 → x + 1 ≥ 0A multi-law contract block
A contract block defines a Prop-valued structure whose fields are individual law propositions parameterized by an operational interface (Storage, declared in .lean). Because a contract structure has type Storage → Prop, it is accepted by the Lean kernel on day one with zero proofs and zero sorry axioms:
Pythonic
contract LawfulStorage(ops: Storage):
law get_put(k: Key, v: Val):
ops.get(ops.put(k, v), k) == vLean
structure LawfulStorage (ops : Storage) : Prop where
get_put : ∀ (k : Key) (v : Val),
ops.get (ops.put k v) k = vExplanation
For every key k and value v, storing v at k and then reading k from the resulting state must return v.
Storage, Key and Val must already be in scope, with operations of the types used here. LawfulStorage is a proposition-valued record: a proof of it must supply evidence for its get_put law.
Declaring the record does not prove that any particular storage implementation obeys it. More laws can be added when the intended behavior needs a stronger contract.
contract LawfulStorage(ops: Storage):
law get_put(k: Key, v: Val):
ops.get(ops.put(k, v), k) == vstructure LawfulStorage (ops : Storage) : Prop where
get_put : ∀ (k : Key) (v : Val),
ops.get (ops.put k v) k = vWhere a proof lives (.lema view vs. .lean module)
In a project workflow (lema add), .lean files supply data types, recursive implementations, and proof terms (theorem ... := ...), while lema view renders any accepted definition or theorem statement in .lema syntax without its proof term:
Pythonic
This readable view shows the definition and the law’s statement. The Lean tab contains the complete module, including the proof.
def keep(n: Nat) -> Nat:
n
law keep_law(n: Nat):
keep(n) == nLean
namespace Lema
def keep (n : Nat) : Nat := n
theorem keep_law (n : Nat) : keep n = n := rfl
end LemaExplanation
keep returns its input unchanged. The law says this holds for every nonnegative integer.
The Lean module includes the proof rfl. Lean reduces keep n to n and checks that both sides are equal by definition. The Pythonic tab displays the same definition and statement, without the proof term.
def keep(n: Nat) -> Nat:
n
law keep_law(n: Nat):
keep(n) == nnamespace Lema
def keep (n : Nat) : Nat := n
theorem keep_law (n : Nat) : keep n = n := rfl
end LemaWhy Contract C R S in Core is declared in .lean
In The program core, Contract C R S combines two proposition fields (pre : S → C → Prop and post : S → (c : C) → R c → Prop) with a state-transition function next : (s : S) → (c : C) → R c → S that returns a state S : Type. Because a .lema contract block only declares Prop-valued law fields, Contract C R S is declared as a structure in audit/view/core/Core.lean, while field projections (K.pre(s, c), K.next(s, c, reply), K.post(s, c, reply)) render directly in .lema:
Pythonic
For an existing contract K, these expressions read its command condition, next state and reply condition. The record also contains a state transition function, so its declaration uses Lean rather than a proposition-only contract block.
K.pre(s, c)
K.next(s, c, reply)
K.post(s, c, reply)Lean
structure Contract (C : Type) (R : C → Type) (S : Type) where
pre : S → C → Prop
next : (s : S) → (c : C) → R c → S
post : S → (c : C) → R c → PropExplanation
A protocol contract describes which commands are permitted, which replies are promised, and how the protocol state changes after a reply.
pre checks whether command c is permitted in state s. next computes the next state from s, c and its reply. post states what that reply must satisfy. The reply’s type R c depends on the command.
The record defines the rules. Separate safety and implementation proofs establish that a program and its implementation follow those rules.
Two library contracts from audit/inputs/
Here are the two sorting laws (sortBy_sorted and sortBy_perm) from Lema.Std.Canonical (audit/inputs/Canonical.json), shown in both views:
Pythonic
Both views below are rendered from the same accepted statement objects in the store. A sorting contract needs both laws: returning an empty list would be in order, so the second law requires every original element and its count to survive.
law sortBy_sorted(le: alpha -> alpha -> Bool, l: List(alpha)):
requires forall a: alpha, b: alpha, c: alpha :: (le(a, b) == true and le(b, c) == true) -> le(a, c) == true
requires forall a: alpha, b: alpha :: le(a, b) == true or le(b, a) == true
ensures Pairwise(fn(a: alpha, b: alpha) -> le(a, b) == true, sortBy(le, l))
law sortBy_perm(le: alpha -> alpha -> Bool, l: List(alpha)):
Perm(sortBy(le, l), l)Lean
theorem sortBy_sorted {α : Type} (le : α → α → Bool)
(trans : ∀ a b c, le a b = true → le b c = true → le a c = true)
(total : ∀ a b, le a b = true ∨ le b a = true) :
∀ l : List α, (sortBy le l).Pairwise (fun a b => le a b = true)
theorem sortBy_perm {α : Type} (le : α → α → Bool) :
∀ l : List α, (sortBy le l).Perm lExplanation
The first law (sortBy_sorted) promises that for any comparison function le that is transitive and total, every item in sortBy(le, l) is ordered before or equal to the items that follow it.
The second law (sortBy_perm) closes the loophole where a buggy implementation simply drops elements or returns an empty list: it promises that the output list is an exact permutation of the input list, preserving every element and its multiplicity.
Because both laws live in the content-addressed store as accepted statement objects, callers such as canonical HTTP header sorting depend only on these statement hashes, never on the internal sorting implementation or proof steps.
law sortBy_sorted(le: alpha -> alpha -> Bool, l: List(alpha)):
requires forall a: alpha, b: alpha, c: alpha :: (le(a, b) == true and le(b, c) == true) -> le(a, c) == true
requires forall a: alpha, b: alpha :: le(a, b) == true or le(b, a) == true
ensures Pairwise(fn(a: alpha, b: alpha) -> le(a, b) == true, sortBy(le, l))
law sortBy_perm(le: alpha -> alpha -> Bool, l: List(alpha)):
Perm(sortBy(le, l), l)theorem sortBy_sorted {α : Type} (le : α → α → Bool)
(trans : ∀ a b c, le a b = true → le b c = true → le a c = true)
(total : ∀ a b, le a b = true ∨ le b a = true) :
∀ l : List α, (sortBy le l).Pairwise (fun a b => le a b = true)
theorem sortBy_perm {α : Type} (le : α → α → Bool) :
∀ l : List α, (sortBy le l).Perm lAnd here are the authenticated-encryption round-trip and tag-mismatch rejection laws from Lema.Std.ChaCha20Poly1305 (audit/inputs/ChaCha20Poly1305.json):
Pythonic
From the cryptography library (audit/inputs/ChaCha20Poly1305.json), used by TLS 1.3 and Noise record protection.
law aead_roundtrip_checked(key: ByteArray, nonce: ByteArray, aad: ByteArray, pt: ByteArray, ct: ByteArray):
requires sealChecked(key, nonce, aad, pt) == some(ct)
ensures openChecked(key, nonce, aad, ct) == some(pt)
law open_rejects_tag_mismatch(key: List(UInt8), nonce: List(UInt8), aad: List(UInt8), body: List(UInt8), tag: List(UInt8)):
requires length(tag) == 16
requires tag != Spec.sealTag(key, nonce, aad, body)
ensures open(ByteArray.mk(Array.mk(key)), ByteArray.mk(Array.mk(nonce)), ByteArray.mk(Array.mk(aad)), ByteArray.mk(Array.mk(body ++ tag))) == noneLean
theorem aead_roundtrip_checked (key nonce aad pt ct : ByteArray)
(h : sealChecked key nonce aad pt = some ct) :
openChecked key nonce aad ct = some pt
theorem open_rejects_tag_mismatch (key nonce aad body tag : List UInt8)
(ht : tag.length = 16)
(hne : tag ≠ Spec.sealTag key nonce aad body) :
open ⟨⟨key⟩⟩ ⟨⟨nonce⟩⟩ ⟨⟨aad⟩⟩ ⟨⟨body ++ tag⟩⟩ = noneExplanation
The first theorem proves that whenever sealChecked accepts a 32-byte key, 12-byte nonce, additional authenticated data, and plaintext within RFC 8439 bounds and produces ciphertext ct, openChecked recovers the exact original plaintext pt.
The second theorem proves that if the 16-byte authentication tag at the end of a message differs in any bit from the RFC 8439 Poly1305 tag, open returns none and releases zero plaintext bytes.
The implementation computes ChaCha20 in 16 unboxed UInt32 registers and Poly1305 in five 26-bit UInt64 limbs, proved equal to the RFC 8439 mathematical specification and checked by the VM’s ConstantTime static analyzer.
law aead_roundtrip_checked(key: ByteArray, nonce: ByteArray, aad: ByteArray, pt: ByteArray, ct: ByteArray):
requires sealChecked(key, nonce, aad, pt) == some(ct)
ensures openChecked(key, nonce, aad, ct) == some(pt)
law open_rejects_tag_mismatch(key: List(UInt8), nonce: List(UInt8), aad: List(UInt8), body: List(UInt8), tag: List(UInt8)):
requires length(tag) == 16
requires tag != Spec.sealTag(key, nonce, aad, body)
ensures open(ByteArray.mk(Array.mk(key)), ByteArray.mk(Array.mk(nonce)), ByteArray.mk(Array.mk(aad)), ByteArray.mk(Array.mk(body ++ tag))) == nonetheorem aead_roundtrip_checked (key nonce aad pt ct : ByteArray)
(h : sealChecked key nonce aad pt = some ct) :
openChecked key nonce aad ct = some pt
theorem open_rejects_tag_mismatch (key nonce aad body tag : List UInt8)
(ht : tag.length = 16)
(hne : tag ≠ Spec.sealTag key nonce aad body) :
open ⟨⟨key⟩⟩ ⟨⟨nonce⟩⟩ ⟨⟨aad⟩⟩ ⟨⟨body ++ tag⟩⟩ = noneExpressions, operators, and precedence
| Construct | Pythonic .lema syntax | Meaning |
|---|---|---|
| Explicit parameter | (x: T) in header | Explicit parameter x of type T |
| Implicit / instance parameter | {alpha: Type}, [x: T], {{x: T}} | Implicit, typeclass-instance, or strict-implicit parameter |
| Function call | f(a, b) | f applied to a, then b |
| Explicit application | @f(a, b) | f applied with all implicit and instance arguments visible |
| Anonymous function | fn(x: T) -> e | Function mapping x : T to e |
| Universal / existential | forall x: T :: P, exists x: T :: P | Universal (∀) and existential (∃) quantification |
| Local binding | let x: T = v; e (have when nondep: true in explicit view) | e evaluated with x bound to v |
| Conditional | if c then a else b | Decidable conditional (ite) |
| Pair and projections | (a, b), x.1, x.2 | Prod.mk, Prod.fst, Prod.snd |
| Lists and options | ([] : List(T)), a :: l, a ++ b, (none : Option(T)), some(a) | List and Option constructors and concatenation |
| Arithmetic | a + b, a - b, a * b, a / b, a % b, a ^ b | Standard arithmetic operators on the operands’ type |
| Comparisons | a == b, a != b, a <= b, a < b, a >= b, a > b, a in s | Equality, inequality, order, and membership |
| Logic and products | P and Q, P or Q, P <-> Q, not P, A * B | Conjunction, disjunction, equivalence, negation, and product type |
| Literals | 3 (at Nat), (3 : Int) (OfNat.ofNat), nat_lit(3), "text" | Numeric and string literals |
| Universes | Prop, Type, Type 1, Sort(u + 1), Sort(max(u, v)) | Universe sorts and levels |
Operators follow standard precedence levels from loosest to tightest:
| Precedence | Operators | Associativity |
|---|---|---|
20 | <-> (↔) | non-associative (must be parenthesized if chained) |
25 | -> (→) | right-associative (A -> B <-> C is (A -> B) <-> C) |
30 | or (∨) | right-associative |
35 | and (∧), * (× on types) | right-associative |
40 | not (¬) | prefix (not a == b is not (a == b)) |
50 | ==, !=, <=, <, >=, >, in | non-associative |
65 | +, -, ++ | left-associative |
67 | :: | right-associative |
70 | *, /, % | left-associative |
75 | ^ | right-associative |
Function application f(...) binds tightest, while forall, exists, fn, let, and if extend as far to the right as possible. The renderer parenthesizes compound operands and arrow domains so rendered views can be read without memorizing precedence rules.
Public API in crates/lema-core/src/view.rs
crates/lema-core/src/view.rs exposes seven deterministic entry points:
| Function signature | Purpose |
|---|---|
render_declaration(table: &Table, objects: &BTreeMap<String, Value>, name: &str, id: &str) -> Result<Rendered> | Renders a stored declaration, record, or family into canonical Pythonic .lema text together with its authoritative names map. |
parse(text: &str, table: &Table) -> Result<Declaration> | Parses a single declaration in .lema syntax into an AST Declaration. |
parse_module(text: &str, table: &Table) -> Result<ParsedModule> | Parses a multi-declaration .lema source file (def, law, contract, and select items), recording 1-based {start_line, start_col, end_line, end_col} spans and symbolic RefKey citations per item. |
lean_term(t: &Term, table: &Table, lean: &dyn Fn(&RefKey) -> String) -> Result<String> | Lowers a parsed .lema term into restricted Lean term syntax. |
lean_declaration(d: &Declaration, head: &str, proof: Option<&str>, table: &Table, lean: &dyn Fn(&RefKey) -> String) -> Result<String> | Lowers a parsed .lema declaration into restricted Lean source for kernel elaboration. |
rederive(text: &str, names: &BTreeMap<String, Value>, objects: &BTreeMap<String, Value>, externals: &ExternalBinders, declaration: &str) -> Result<Rederived> | Rebuilds the canonical statement and template object IDs directly from text and names in pure Rust without invoking Lean. |
renderer_sha256() -> String | Computes the domain-separated SHA-256 digest (LEMA-CONTRACT-VIEW-v1\0) of all production renderer/parser/rederive Rust source (before #[cfg(test)]\nmod tests {) plus view/external-binders.json. |
Names, Unicode anti-spoofing, and binder generation
- Display names (
displayableandshows): Published names are shown without theLema.prefix unless stripping it would collide with a LeanInitname. A name is displayed only when it consists of dot-separated identifiers that are not reserved keywords or literals (some,none,true,false,obj_...). Any object without a valid display name renders asobj_<12-hex-id>(plus.mk,.rec,.ctor_1, or.field_0for record/family roles). - Unicode confusable and invisible character rejection (
invisible): Identifier names reject Hangul fillers, zero-width characters, bidirectional controls, and formatting characters so two displayed names can never look identical while referring to different objects. Inside string literals, only printable ASCII, standard letters, and digits appear raw; all formatting, bidirectional, combining, and separator code points are escaped as\u{xxxx}. - Deterministic binder names: Because canonical objects use de Bruijn indices (
bvar) and erase source variable names, the renderer generates deterministic binder names (alpha,beta, … for types,h,h_1, … for proof hypotheses, andx,y,z, … for values) that never collide with the first segment of any constant name in the declaration.
Zero-Lean structural rederive, hidden arguments, and review digests
When lema site build or Store::review_display (crates/lema-store/src/display.rs) prepares an approval view (lema.review-display/v1), it never trusts the printer blindly:
- Zero-Lean structural round trip (
rederive):view::rederiveparses the rendered.lematext under itsnamesmap, combines the parsed syntax tree with the universe levels and implicit/instance arguments stored in the object, and reconstructs the canonicalstatementandtemplateobjects in pure Rust. If the reconstructed SHA-256 IDs do not match the declaration’s own IDs, the view is markedOutcome::Mismatch(Display::approvable() == false) and cannot be approved. - Hidden-argument occurrence tracking (
Rederived::hiddenandRederived::explicit): Every implicit and instance argument omitted by the readable.lemaview (such as theAddinstance behind+, theLEinstance behind<=,ite’sDecidableinstance, orOfNat) is extracted in left-to-right textual occurrence order as(occurrence, kind, text)inRederived::hidden, alongside the complete unabbreviated declarationRederived::explicitwhere every application is prefixed with@, all universe levels are shown, and non-dependentletbindings are shown ashave. Swapping two instances between two occurrences of<=in the same formula changes bothRederived::hiddenandRederived::explicit. - Display-bound reviews (
renderer_sha256()andlema.review-display/v1): An approval view digest (sha256("LEMA-REVIEW-DISPLAY-v1\0" || canonical({renderer, subject, views}))) bindsview::renderer_sha256(), the target reference transition, the rendered.lematext, thenamesmap,Rederived::hidden, andRederived::explicit. Undercrates/lema-store/src/protect.rs, a display-bound review counts atref.publishorref.adoptonly while the subject still produces that exact digest under the currentrenderer_sha256().
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility