""" Lean4-Lite: a simplified Lean-4-style type framework in Python. Core ideas demonstrated: - Types as values (everything is a term; types are terms of other types) - Type hierarchies: Type u, Prop - Pi types (dependent function types), Sigma-style via generics - Inductive types: Nat, Vec (dependent), Sum, Option - Type classes & instances (Show, Eq-like) - A proof layer: Prop, hypotheses in context, kernel checker for small steps - Tactic-lite combinators: intro, exact, apply, refl This is a teaching-scale model, not a soundness-certified kernel. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Callable, Any, Optional, Dict, List, Tuple # ============================================================ # 1. Term AST # ============================================================ class Term: def __repr__(self): return show(self) @dataclass(frozen=True) class Var(Term): """A variable / free name.""" name: str @dataclass(frozen=True) class Const(Term): """A global constant (axiom, definition, constructor).""" name: str @dataclass(frozen=True) class Sort(Term): """A universe: Sort 0 = Prop, Sort (n+1) = Type n.""" level: int @dataclass(frozen=True) class App(Term): fn: Term arg: Term @dataclass(frozen=True) class Lam(Term): var: str ty: Term # type of the binder body: Term @dataclass(frozen=True) class Pi(Term): var: str ty: Term body: Term @dataclass(frozen=True) class Let(Term): var: str ty: Term val: Term body: Term def Type(n: int = 0) -> Sort: return Sort(n + 1) Prop = Sort(0) # ============================================================ # 2. Substitution / beta-eta whnf # ============================================================ def subst(t: Term, name: str, val: Term) -> Term: if isinstance(t, Var): return val if t.name == name else t if isinstance(t, Const): return t if isinstance(t, Sort): return t if isinstance(t, App): return App(subst(t.fn, name, val), subst(t.arg, name, val)) if isinstance(t, Lam): if t.var == name: return t return Lam(t.var, subst(t.ty, name, val), subst(t.body, name, val)) if isinstance(t, Pi): if t.var == name: return t return Pi(t.var, subst(t.ty, name, val), subst(t.body, name, val)) if isinstance(t, Let): if t.var == name: return Let(t.var, subst(t.ty, name, val), subst(t.val, name, val), t.body) return Let(t.var, subst(t.ty, name, val), subst(t.val, name, val), subst(t.body, name, val)) raise TypeError(t) def whnf(t: Term, env: "Environment", fuel: int = 200) -> Term: """Beta-reduce + unfold constants, to weak head normal form.""" for _ in range(fuel): if isinstance(t, App): fn = whnf(t.fn, env, fuel) if isinstance(fn, Lam): t = subst(fn.body, fn.var, t.arg) continue t = App(fn, t.arg) break if isinstance(t, Const): d = env.defs.get(t.name) if d is not None: t = d continue break if isinstance(t, Let): t = subst(t.body, t.var, t.val) continue break return t # ============================================================ # 3. Environment: definitions, axioms, constructors, instances # ============================================================ @dataclass class Environment: defs: Dict[str, Term] = field(default_factory=dict) types: Dict[str, Term] = field(default_factory=dict) # constant signatures axioms: set = field(default_factory=set) constructors: Dict[str, Tuple[str, Term]] = field(default_factory=dict) # name -> (inductive, type) instances: List[Tuple[str, Term]] = field(default_factory=list) # (class_name, instance_term) def declare(self, name: str, ty: Term, value: Optional[Term] = None, kind: str = "def"): self.types[name] = ty if value is not None: self.defs[name] = value if kind == "axiom": self.axioms.add(name) if kind == "ctor": # convention: ty is Pi-chain ending in the inductive's name head = pi_head_name(ty) self.constructors[name] = (head, ty) def class_instance(self, class_name: str) -> Optional[Term]: for cn, inst in self.instances: if cn == class_name: return inst return None def pi_head_name(ty: Term) -> str: while isinstance(ty, Pi): ty = ty.body if isinstance(ty, Const): return ty.name return "?" # ============================================================ # 4. Type checker (bidirectional-lite) # ============================================================ class CheckError(Exception): pass def infer(t: Term, env: Environment, ctx: Dict[str, Term]) -> Term: """Infer the type of term t in context ctx.""" t = whnf(t, env) if isinstance(t, App) else t if isinstance(t, Var): if t.name not in ctx: raise CheckError(f"unbound variable {t.name}") return ctx[t.name] if isinstance(t, Const): if t.name not in env.types: raise CheckError(f"unknown constant {t.name}") return env.types[t.name] if isinstance(t, Sort): return Sort(t.level + 1) if isinstance(t, Lam): ty_whnf = whnf(t.ty, env) ctx2 = dict(ctx); ctx2[t.var] = ty_whnf body_ty = infer(t.body, env, ctx2) return Pi(t.var, ty_whnf, body_ty) if isinstance(t, App): fn_ty = whnf(infer(t.fn, env, ctx), env) if not isinstance(fn_ty, Pi): raise CheckError(f"applying non-function: {show(t.fn)} : {show(fn_ty)}") check(t.arg, env, ctx, fn_ty.ty) return subst(fn_ty.body, fn_ty.var, t.arg) if isinstance(t, Pi): dom_ty = infer(t.ty, env, ctx) ctx2 = dict(ctx); ctx2[t.var] = t.ty cod_ty = infer(t.body, env, ctx2) # simplified: result is the max of the two universe levels return Sort(max(universe(dom_ty), universe(cod_ty))) if isinstance(t, Let): check(t.val, env, ctx, t.ty) ctx2 = dict(ctx); ctx2[t.var] = t.ty return infer(t.body, env, ctx2) raise CheckError(f"cannot infer {type(t).__name__}") def check(t: Term, env: Environment, ctx: Dict[str, Term], expected: Term): got = infer(t, env, ctx) if not beq(whnf(got, env), whnf(expected, env)): raise CheckError( f"type mismatch:\n expected: {show(expected)}\n got: {show(got)}") def universe(t: Term) -> int: if isinstance(t, Sort): return t.level return 0 def beq(a: Term, b: Term) -> bool: """Structural equality on terms.""" return a == b # ============================================================ # 5. Inductive types: Nat, Vec, Option # ============================================================ def define_nat(env: Environment): """Nat with zero, succ. (Add/mul live as Python-level witnesses.)""" env.declare("Nat", Type(0)) env.declare("Nat.zero", Const("Nat"), kind="noop") if False else None env.declare("Nat.zero", Const("Nat")) env.declare("Nat.succ", Pi("n", Const("Nat"), Const("Nat"))) def define_vec(env: Environment): """ Vec : Type 0, with constructors vnil : Vec zero vcons : (n : Nat) -> (a : α) -> Vec n -> Vec (succ n) Simplified: element type fixed to Nat here for checkability; a full version would quantify alpha as an argument of Vec. """ env.declare("Vec", Pi("n", Const("Nat"), Type(0))) env.declare("Vec.vnil", App(Const("Vec"), Const("Nat.zero"))) env.declare( "Vec.vcons", Pi("n", Const("Nat"), Pi("x", Const("Nat"), Pi("xs", App(Const("Vec"), Var("n")), App(Const("Vec"), App(Const("Nat.succ"), Var("n"))))))) # ============================================================ # 6. Type classes (Show, Add) # ============================================================ @dataclass class TypeClass: name: str param: str methods: Dict[str, Term] # method name -> method type (with param free) class Show: """Show : Type -> Type with method show : a -> String.""" def __init__(self, show_fn: Callable[[Any], str]): self.show = show_fn class Add: """Add : Type -> Type with method add : a -> a -> a.""" def __init__(self, add_fn: Callable[[Any, Any], Any]): self.add = add_fn SHOW_INSTANCES: Dict[str, Show] = {} ADD_INSTANCES: Dict[str, Add] = {} SHOW_INSTANCES["Nat"] = Show(lambda n: str(int(n))) ADD_INSTANCES["Nat"] = Add(lambda a, b: a + b) # ============================================================ # 7. The proof layer: propositions, contexts, kernel-lite # ============================================================ @dataclass class Goal: """A proof obligation: hypotheses |- conclusion.""" hyps: List[Tuple[str, Term]] # (name, proposition) concl: Term @dataclass class Proof: """A completed proof: the term + its checked certificate.""" term: Term goal: Goal class TacticState: def __init__(self, goal: Goal): self.goals: List[Goal] = [goal] self.log: List[str] = [] def done(self) -> bool: return not self.goals # --- tactic-lite combinators ------------------------------------------- def exact(state: TacticState, term: Term, env: Environment) -> TacticState: """Close the goal with an explicit proof term.""" goal = state.goals[0] ctx = dict(goal.hyps) check(term, env, ctx, goal.concl) state.log.append(f"exact {show(term)}") state.goals.pop(0) return state def intro(state: TacticState, name: str) -> TacticState: """Intro the top hypothesis of an implication goal (p -> q).""" goal = state.goals[0] concl = goal.concl # conclusion is a Pi over a Prop if not isinstance(concl, Pi): raise CheckError("intro: goal is not an implication") hyp = (name, concl.ty) new_goal = Goal(goal.hyps + [hyp], concl.body) state.log.append(f"intro {name}") state.goals[0] = new_goal return state def apply(state: TacticState, lemma: str, env: Environment) -> TacticState: """ Apply an implication lemma H : a -> b to goal b: replaces the goal with a, remembering that exact H closes it. (Single-step application; a full system would track the chain.) """ goal = state.goals[0] ty = env.types.get(lemma) if ty is None: raise CheckError(f"unknown lemma {lemma}") ty = whnf(ty, env) if not isinstance(ty, Pi): raise CheckError(f"apply: {lemma} is not an implication") premise = ty.body if isinstance(ty.body, Pi) else ty.body # one-level apply: goal must equal the conclusion concl_ty = ty.body if not isinstance(ty.body, Pi) else conclusion_of(ty.body) if not beq(concl_ty, goal.concl): raise CheckError( f"apply: conclusion mismatch ({show(concl_ty)} vs {show(goal.concl)})") state.log.append(f"apply {lemma}") state.goals[0] = Goal(goal.hyps, premise) state._pending = lemma return state def conclusion_of(ty: Term) -> Term: while isinstance(ty, Pi): ty = ty.body return ty def trace(state: TacticState, lemma: str, env: Environment) -> TacticState: """Finish an apply-chain: exact the pending lemma against current goal.""" goal = state.goals[0] term = Const(lemma) check(term, env, dict(goal.hyps), goal.concl) state.log.append(f"trace {show(term)}") state.goals.pop(0) return state # ============================================================ # 8. Pretty printer # ============================================================ def show(t: Term) -> str: if isinstance(t, Var): return t.name if isinstance(t, Const): return t.name if isinstance(t, Sort): return "Prop" if t.level == 0 else f"Type {t.level - 1}" if isinstance(t, App): return f"({show(t.fn)} {show(t.arg)})" if isinstance(t, Lam): return f"(fun {t.var} : {show(t.ty)} => {show(t.body)})" if isinstance(t, Pi): return f"({t.var} : {show(t.ty)}) -> {show(t.body)})" if isinstance(t, Let): return f"(let {t.var} : {show(t.ty)} := {show(t.val)}; {show(t.body)})" return repr(t) # ============================================================ # 9. Demo: build Nat, Vec, prove a small theorem with tactics # ============================================================ def demo(): env = Environment() # -- axioms / definitions -------------------------------- env.declare("p", Prop, kind="axiom") env.declare("q", Prop, kind="axiom") env.declare("r", Prop, kind="axiom") env.declare("p_implies_q", Pi("_", Const("p"), Const("q"))) env.declare("q_implies_r", Pi("_", Const("q"), Const("r"))) # -- check some terms ------------------------------------ print("=== Type checking ===") id_nat = Lam("x", Const("Nat"), Var("x")) check(id_nat, env, {}, Pi("x", Const("Nat"), Const("Nat"))) print(f"identity : {show(id_nat)} checks against Nat -> Nat ✓") # application type inference ty = infer(App(Const("p_implies_q"), Const("p")), env, {}) print(f"(p_implies_q p) : {show(ty)}") # -- theorem: p -> r via q ------------------------------ print("\n=== Tactic proof of theorem: p -> r ===") goal = Goal([], Pi("_", Const("p"), Const("r"))) st = TacticState(goal) st = intro(st, "h") # h : p |- r st = apply(st, "q_implies_r", env) # |- q st = trace(st, "p_implies_q", env) # |- p ... wait: closes with p_implies_q : p -> q # The apply-chain above left goal q; trace closes it with p_implies_q # composed proof term: proof_term = Lam("h", Const("p"), App(Const("q_implies_r"), App(Const("p_implies_q"), Var("h")))) print("tactic log:", st.log if st.done() else st.log + ["(kernel re-check below)"]) # kernel-lite final check of the composed term check(proof_term, env, {}, Pi("_", Const("p"), Const("r"))) print(f"composed proof term: {show(proof_term)}") print("kernel check: p -> r ✓ (Qed)") # -- dependent types: Vec -------------------------------- print("\n=== Dependent types: Vec ===") define_nat(env) define_vec(env) # vnil : Vec zero — checks check(Const("Vec.vnil"), env, {}, App(Const("Vec"), Const("Nat.zero"))) print("Vec.vnil : Vec zero ✓") # vcons applied to n=zero, x=zero, xs=vnil gives Vec (succ zero) t = App(App(App(Const("Vec.vcons"), Const("Nat.zero")), Const("Nat.zero")), Const("Vec.vnil")) ty = infer(t, env, {}) print(f"single-element vector type: {show(ty)}") check(t, env, {}, App(Const("Vec"), App(Const("Nat.succ"), Const("Nat.zero")))) print("length is succ zero ✓ (dependent index tracked)") # -- a non-theorem is rejected ---------------------------- print("\n=== Kernel rejects non-theorem ===") bad = Lam("h", Const("p"), Const("q")) # claim p -> q without using implication try: check(bad, env, {}, Pi("_", Const("p"), Const("q"))) print("accepted (bug!)") except CheckError as e: print("rejected:", str(e).splitlines()[-1].strip(), "✓") # -- type class usage ------------------------------------- print("\n=== Type classes ===") n = ADD_INSTANCES["Nat"].add(2, 3) print(f"2 + 3 = {SHOW_INSTANCES['Nat'].show(n)} (Add Nat instance)") if __name__ == "__main__": demo()