{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c8e3ab1c",
   "metadata": {},
   "source": [
    "# A minimal kernel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95d8eccd",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# kernel code: files next to the notebook or the course repository's kernel/\n",
    "for directory in [Path.cwd(), *Path.cwd().parents]:\n",
    "    if (directory / \"kernel.py\").is_file():\n",
    "        sys.path.insert(0, str(directory))\n",
    "        break\n",
    "    if (directory / \"kernel\" / \"kernel.py\").is_file():\n",
    "        sys.path.insert(0, str(directory / \"kernel\"))\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "138d3995",
   "metadata": {},
   "source": [
    "In the previous section we used the kernel as a black box: we gave it a proof tree, and it answered which\n",
    "equation the tree justifies. Now we open the box. The whole kernel is one file, `kernel.py`, and one class,\n",
    "`Kernel`. We will see almost all of its code, because this is exactly the point: the kernel should\n",
    "be small enough to be read and understood."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5fbaa18",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "import textwrap\n",
    "\n",
    "import kernel\n",
    "from kernel import Kernel, ProofError, Refl, Symm, Trans, CongrArg, Inst, subst\n",
    "from syntax import term, equation, show, show_equation\n",
    "\n",
    "\n",
    "def show_code(obj):\n",
    "    \"\"\"Prints the code of a function or method (without the class indent).\"\"\"\n",
    "    print(textwrap.dedent(inspect.getsource(obj)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40169e31",
   "metadata": {},
   "source": [
    "## Terms\n",
    "\n",
    "A term is a tree. In Python we write terms as tuples: the first element of a tuple is the symbol of an\n",
    "operation, and the remaining ones are the arguments. Variables and constants are strings. The parser from the\n",
    "file `syntax.py` turns the usual notation into tuples, and the function `show` turns\n",
    "them back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d53f01b",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = term(\"x + y * n(x)\")\n",
    "print(t)\n",
    "print(show(t))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2467f526",
   "metadata": {},
   "source": [
    "Which symbols are allowed and how many arguments they take is given by the **signature** — a dictionary that\n",
    "the kernel receives when it is created. For Boolean algebra:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39a7a722",
   "metadata": {},
   "outputs": [],
   "source": [
    "from boolean import SIGNATURE\n",
    "\n",
    "print(SIGNATURE)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3348033b",
   "metadata": {},
   "source": [
    "Constants are symbols with zero arguments, and any other identifier can be a variable — the method `is_var`\n",
    "recognizes variables. The method `term` checks whether a string or a tuple is a well-formed term of this\n",
    "signature; the kernel calls it for every term that it receives from outside. Both methods accept only plain\n",
    "strings and tuples (`type(t) is str`), not objects of their subclasses — we will see why when we prove the kernel sound in {doc}`§3.4 <w03_4_zaufanie>`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a7446b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_code(Kernel.is_var)\n",
    "show_code(Kernel.term)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb8e5eeb",
   "metadata": {},
   "source": [
    "The parser is not part of the kernel, but it is not irrelevant to trust. The kernel checks a proof of the\n",
    "statement that it was given. If the parser misread a string, the kernel would check a different statement\n",
    "from the one we have in mind. We will return to this problem in {doc}`§3.4 <w03_4_zaufanie>`.\n",
    "\n",
    "## Substitution\n",
    "\n",
    "The rule `Inst` requires substituting terms for variables. This takes four lines:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3b00a3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_code(subst)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59698aa4",
   "metadata": {},
   "source": [
    "Substitution is **simultaneous**: the substitution $x := y$, $y := x$ swaps the two variables instead of giving\n",
    "$x + x$, as substituting one after the other would (first $x := y$, then $y := x$). The second example is the instance of axiom H3 from the third step of the proof of $x + x = x$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ed4d506",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(show(subst(term(\"x + y\"), {\"x\": \"y\", \"y\": \"x\"})))\n",
    "s = {\"x\": \"x\", \"y\": \"x\", \"z\": term(\"n(x)\")}\n",
    "print(show(subst(term(\"x + y * z\"), s)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e79eaf0",
   "metadata": {},
   "source": [
    "Why is it so simple? Our terms have no **bound variables**: they contain no quantifiers $\\forall$, $\\exists$,\n",
    "and no $\\lambda$-functions. If they did, substitution would require care. Let us substitute $y := x$ in the\n",
    "formula $\\forall x\\ (x + y = y + x)$ by simply replacing letters. We get $\\forall x\\ (x + x = x + x)$, which\n",
    "is a completely different statement, because the new $x$ has been “captured” by the quantifier. The kernels of\n",
    "Lean and other proof assistants have to guard against this; one of the solutions is de Bruijn indices\n",
    "(more in {ref}`§3.5 <w03-de-bruijn>`). We avoid this problem by choosing a logic without bound variables.\n",
    "\n",
    "## The heart of the kernel: the method `conclusion`\n",
    "\n",
    "The most important method of the kernel takes a proof tree and returns a pair of terms: the left-hand and the\n",
    "right-hand side of the equation that the tree justifies. If the tree is not a valid proof, it raises the\n",
    "exception `ProofError`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19a95e26",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_code(Kernel.conclusion)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bb0d172",
   "metadata": {},
   "source": [
    "The `match` statement recognizes the kind of node and immediately unpacks its fields. The five cases are the\n",
    "five rules:\n",
    "\n",
    "* `Refl(t)` — only checks that $t$ is a term and returns $(t, t)$.\n",
    "* `Symm(p)` — computes the conclusion of the subtree $p$ and swaps its sides.\n",
    "* `Trans(p, q)` — computes the conclusions of both subtrees and **compares the middle terms**. This is the only\n",
    "  place in the method `conclusion` where the kernel compares terms (the method `theorem` later compares the\n",
    "  conclusion with the stated theorem); the comparison `b != b2` checks that the trees are identical, not that\n",
    "  they are equal “after simplification”.\n",
    "* `CongrArg(z, C, p)` — checks that $z$ is a variable and $C$ is a term, and inserts both sides of the\n",
    "  conclusion of $p$ into the hole $z$ of the context $C$.\n",
    "* `Inst(name, args)` — looks up the fact with this name, checks the number of arguments, and\n",
    "  substitutes them for the variables of the fact.\n",
    "\n",
    "The method is recursive: it computes the conclusion of a tree from the conclusions of its subtrees and visits\n",
    "each node exactly once. There is no searching or guessing here at all. The kernel does not know *why* the\n",
    "proof looks the way it does; it only checks whether each node is a correct application of a rule.\n",
    "\n",
    "## The environment: axioms and theorems\n",
    "\n",
    "The kernel stores an **environment**: the dictionary `facts`, which assigns to the name of a fact\n",
    "its variables and both sides of its equation. Facts are added by two methods. An axiom enters the environment\n",
    "without a proof. A theorem enters it only if the conclusion of its proof is **exactly** the stated equation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02d39385",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_code(Kernel.axiom)\n",
    "show_code(Kernel.theorem)\n",
    "show_code(Kernel._add)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63163cc1",
   "metadata": {},
   "source": [
    "A few details matter:\n",
    "\n",
    "* a proof can refer only to facts that are already in the environment, so no proof can appeal to itself or to\n",
    "  a theorem proved “later”;\n",
    "* the name of a fact must be new, so a theorem, once accepted, cannot be replaced;\n",
    "* the declared variables of a fact must be variables, not constants: otherwise the rule `Inst` would\n",
    "  substitute terms for constants (the first version of the kernel did not guard against this — details in {doc}`§3.4 <w03_4_zaufanie>`);\n",
    "* all variables of the equation must be declared: a theorem says “for all $x$”, and we know which $x$ is\n",
    "  meant.\n",
    "\n",
    "Let us build the environment of Boolean algebra with six theorems from the file `boolean.py`. Their proofs are\n",
    "built by tactics, the subject of the next section; the kernel checks them in the same way as a proof\n",
    "assembled by hand."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf153f25",
   "metadata": {},
   "outputs": [],
   "source": [
    "from boolean import theory_with_theorems\n",
    "\n",
    "j, proofs = theory_with_theorems()\n",
    "for name, (variables, l, r) in j.facts.items():\n",
    "    print(f\"{name:13} ∀ {', '.join(variables):8} {show(l)} = {show(r)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad6001d3",
   "metadata": {},
   "source": [
    "## What a theorem rests on\n",
    "\n",
    "With every fact, the kernel records the set of axioms on which this fact rests: an axiom rests on itself, and\n",
    "a theorem on the union of the assumptions of the facts used in its proof. The command `#print axioms` in Lean\n",
    "works in a similar way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab7634df",
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in proofs:\n",
    "    print(f\"{name:13} {' '.join(sorted(j.assumptions[name]))}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c019673a",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert sorted(j.assumptions[\"add_idem\"]) == [\"H3\", \"H5\", \"H6\", \"H7\", \"H8\"]\n",
    "assert not {\"H1\", \"H2\"} & j.assumptions[\"add_idem\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7ed72ac",
   "metadata": {},
   "source": [
    "The proof of the equation $x + x = x$ uses neither commutativity (H1, H2) nor axiom H4. Such information can\n",
    "be valuable: the theorem then holds in every structure in which just the axioms used by the proof hold. For\n",
    "the proof of the Riemann hypothesis, `#print axioms` lists Lean’s three standard axioms and nothing else — this\n",
    "means that nowhere in the 175,187 files was an assumption about prime numbers or about the zeros of the\n",
    "function $\\zeta$ added.\n",
    "\n",
    "## What the kernel rejects\n",
    "\n",
    "Let us watch the kernel in action on a few bad proofs. The function `check` prints the conclusion\n",
    "or the reason for rejection:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79c22bbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "def check(d):\n",
    "    try:\n",
    "        print(\"accepted:\", show_equation(j.conclusion(d)))\n",
    "    except ProofError as error:\n",
    "        print(\"rejected:\", error)\n",
    "\n",
    "\n",
    "check(Trans(Inst(\"H5\", (\"x\",)), Inst(\"H6\", (\"x\",))))    # the middles differ\n",
    "check(Inst(\"H3\", (\"x\",)))                                # too few arguments\n",
    "check(Inst(\"H9\", (\"x\",)))                                # no such fact\n",
    "check(Refl((\"+\", \"x\")))                                  # + takes two arguments\n",
    "check(Trans(Symm(Inst(\"H5\", (\"x\",))), Inst(\"H5\", (\"x\",))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e82b1b1",
   "metadata": {},
   "source": [
    "The first proof tries to join $x + 0 = x$ with $x \\cdot 1 = x$, and the middle terms $x$ and $x \\cdot 1$\n",
    "differ. The last one is correct: $x = x + 0$ and $x + 0 = x$ imply $x = x$. There is also an error of\n",
    "a different kind: a correct proof, but of a different statement from the one stated. The kernel will accept\n",
    "the tree `Inst(\"H5\", (\"x\",))`, because it proves the equation $x + 0 = x$, but not as a proof of the equation\n",
    "$x + x = x$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7ab618e",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    j.theorem(\"wrong\", [\"x\"], *equation(\"x + x = x\"), Inst(\"H5\", (\"x\",)))\n",
    "except ProofError as error:\n",
    "    print(\"rejected:\", error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06da4303",
   "metadata": {},
   "source": [
    "## The kernel does not check axioms\n",
    "\n",
    "What if someone added an axiom that is not true? The kernel will accept it without discussion: an axiom is an\n",
    "assumption, not a theorem. Let us add the “miracle” $x + y = x$ (the axiom `miracle`) and\n",
    "use it to prove the false equation $x + 1 = x$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0099ddb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from boolean import theory\n",
    "\n",
    "j2 = theory()\n",
    "j2.axiom(\"miracle\", [\"x\", \"y\"], *equation(\"x + y = x\"))\n",
    "j2.theorem(\"falsehood\", [\"x\"], *equation(\"x + 1 = x\"), Inst(\"miracle\", (\"x\", \"1\")))\n",
    "print(\"accepted; assumptions:\", sorted(j2.assumptions[\"falsehood\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f41964ba",
   "metadata": {},
   "source": [
    "The kernel was right: $x + 1 = x$ **follows** from the axiom `miracle`. The kernel checks logical consequence,\n",
    "not the truth of the axioms, and the list of assumptions immediately reveals where the falsehood came from.\n",
    "This is exactly how `sorry` works in Lean: this command closes a proof by adding the axiom `sorryAx`, and\n",
    "`#print axioms` shows it. That is why, for the proof of the Riemann hypothesis, it was so important that the\n",
    "list of axioms contains only the three standard entries.\n",
    "\n",
    "## How big is the kernel?\n",
    "\n",
    "Let us count the lines of code of the kernel, skipping blank lines, comments, and documentation strings\n",
    "(*docstrings*):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09c251e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ast\n",
    "\n",
    "source = inspect.getsource(kernel)\n",
    "docs = set()\n",
    "for node in ast.walk(ast.parse(source)):\n",
    "    if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef)):\n",
    "        first_one = node.body[0]\n",
    "        if isinstance(first_one, ast.Expr) and isinstance(\n",
    "                first_one.value, ast.Constant):\n",
    "            docs.update(range(first_one.lineno, first_one.end_lineno + 1))\n",
    "loc = [w for i, w in enumerate(source.splitlines(), start=1)\n",
    "       if w.strip() and not w.strip().startswith(\"#\") and i not in docs]\n",
    "print(\"lines of kernel code:\", len(loc))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d05191d2",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert len(loc) < 120"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adf140f1",
   "metadata": {},
   "source": [
    "That is fewer than a hundred and twenty lines, which can be read in a quarter of an hour. The principle that\n",
    "a program we trust should be small enough to be checked by hand is called the **de Bruijn criterion**, after\n",
    "N. G. de Bruijn, the creator of the Automath system. Lean’s kernel is much larger than ours, because its logic\n",
    "is much richer, but the idea is the same: everything outside the kernel — the parser, tactics, automated\n",
    "proving — may make mistakes and still will not introduce a false theorem.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* Terms are tuples; the signature says which symbols are allowed. Without bound variables, substitution is an\n",
    "  ordinary, simultaneous replacement of variables.\n",
    "* The method `conclusion` is five cases of a `match` statement, one for each rule. The kernel searches for\n",
    "  nothing: it visits each node once and, in the method `conclusion`, compares terms only in the rule `Trans`.\n",
    "* A theorem enters the environment only if the conclusion of its proof is exactly the stated equation; facts\n",
    "  are added one by one, so there is no circular reasoning.\n",
    "* The kernel checks that statements follow from the axioms, not that the axioms are true. The list of\n",
    "  assumptions (`#print axioms`) shows what a theorem really rests on.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Predict on paper the conclusion of the proof\n",
    "   `Trans(Inst(\"H1\", (\"x\", \"y\")), Inst(\"H1\", (\"y\", \"x\")))`, and then check it with the method `j.conclusion`.\n",
    "   Build a similar proof of the equation $x \\cdot y = x \\cdot y$ that does not use the rule `Refl`.\n",
    "2. ★ In a copy of the method `conclusion`, add printing of every visited node and trace how the kernel checks the\n",
    "   proof of $x + x = x$ from the previous section. How many times does the kernel compare terms in the rule\n",
    "   `Trans`?\n",
    "3. ★★ Build a “broken kernel”: a subclass of the class `Kernel` in which the rule `Trans` does not check whether\n",
    "   the middle terms are equal. Build a “proof” of the equation $x + y = x$ in it and point out the node that\n",
    "   smuggles in the falsehood.\n",
    "4. ★★★ Add to the kernel the rule `Congr(f, p₁, …, pₖ)`: the equations $a_i = b_i$ imply\n",
    "   $f(a_1, \\dots, a_k) = f(b_1, \\dots, b_k)$ (in Lean, `congr`). Show that the new rule is redundant: every\n",
    "   use of it can be replaced by the rules `CongrArg` and `Trans` (for a constant, which has no arguments, by the\n",
    "   rule `Refl`). Write a function that does this."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
