File size: 5,842 Bytes
13e1f35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""Lean 4 + Mathlib inside the Space: background install at startup, and a checker.

check(code) compiles one Lean file and reports errors, sorry use, axioms and banned tactics.
"""
import json, os, re, signal, subprocess, threading, time, uuid

HOME = os.path.expanduser("~")
PROJECT = os.path.join(HOME, "leancheck")
SCRATCH = os.path.join(PROJECT, "scratch")
ELAN_BIN = os.path.join(HOME, ".elan", "bin")
SETUP_LOG = os.path.join(HOME, "lean_setup.log")
HERE = os.path.dirname(os.path.abspath(__file__))

# Tried in order at startup; the first that compiles becomes the header of every file.
# The first is the header the open prover models were trained with.
HEADERS = [
    "import Mathlib\nimport Aesop\n\nset_option maxHeartbeats 400000\n\nopen BigOperators Real Nat Topology Rat",
    "import Mathlib\nimport Aesop\n\nset_option maxHeartbeats 400000\n\nopen Real Nat Topology",
    "import Mathlib",
]

SAFE_AXIOMS = {"propext", "Classical.choice", "Quot.sound"}
THM = re.compile(r"^\s*(?:theorem|lemma)\s+([^\s:({\[]+)", re.M)
BANNED = re.compile(r"\bnative_decide\b|\badmit\b|^\s*axiom\s", re.M)
AXLINE = re.compile(r"'(.+?)' depends on axioms: \[(.*?)\]", re.S)
NOAX = re.compile(r"'(.+?)' does not depend on any axioms")

_state = {"status": "not started", "error": None, "header": None, "since": time.time()}
_sem = threading.BoundedSemaphore(int(os.environ.get("LEAN_PARALLEL", "2")))
_started = threading.Lock()


def _env():
    env = dict(os.environ)
    env["PATH"] = ELAN_BIN + os.pathsep + env.get("PATH", "")
    return env


def status():
    s = dict(_state)
    s["minutes"] = round((time.time() - s["since"]) / 60, 1)
    return s


def header():
    return _state["header"] or HEADERS[-1]


def ready():
    return _state["status"] == "ready"


def _setup():
    try:
        _state.update(status="installing Lean + Mathlib", since=time.time())
        with open(SETUP_LOG, "w") as log:
            r = subprocess.run(["bash", os.path.join(HERE, "setup_lean.sh")],
                               stdout=log, stderr=subprocess.STDOUT, env=_env())
        if r.returncode != 0:
            tail = open(SETUP_LOG).read()[-1500:]
            raise RuntimeError(f"setup_lean.sh exited with {r.returncode}:\n{tail}")
        _state["status"] = "self-test"
        last = None
        for h in HEADERS:
            last = check(h + "\n\ntheorem main_theorem : (2 : ℕ) + 2 = 4 := by norm_num\n", force=True)
            if last["ok"]:
                _state["header"] = h
                break
        if not _state["header"]:
            raise RuntimeError("Lean self-test failed: " + json.dumps(last)[:1500])
        _state.update(status="ready", since=time.time())
    except Exception as e:  # surfaced in the UI
        _state.update(status="failed", error=str(e))


def start():
    """Start the background install once per process."""
    if _started.acquire(blocking=False):
        threading.Thread(target=_setup, daemon=True).start()


def _run(path, timeout):
    p = subprocess.Popen(["lake", "env", "lean", "--json", path], cwd=PROJECT,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
                         env=_env(), start_new_session=True)
    try:
        out, err = p.communicate(timeout=timeout)
        return out, err, False
    except subprocess.TimeoutExpired:
        os.killpg(p.pid, signal.SIGKILL)
        p.communicate()
        return "", "", True


def _parse(out):
    msgs = []
    for line in out.splitlines():
        line = line.strip()
        if line.startswith("{"):
            try:
                msgs.append(json.loads(line))
            except json.JSONDecodeError:
                pass
    return msgs


def check(code, timeout=300, force=False):
    """Compile `code`. ok=True only with no errors, no sorry, standard axioms, nothing banned,
    and every theorem actually elaborated."""
    if not force and not ready():
        raise RuntimeError(f"Lean is not ready (status: {_state['status']})")
    names = THM.findall(code)
    full = code + "\n\n" + "\n".join(f"#print axioms {n}" for n in names) + "\n"
    os.makedirs(SCRATCH, exist_ok=True)
    path = os.path.join(SCRATCH, f"{uuid.uuid4().hex}.lean")
    with open(path, "w") as f:
        f.write(full)
    try:
        with _sem:
            out, err, timed_out = _run(path, timeout)
    finally:
        try:
            os.remove(path)
        except OSError:
            pass
    if timed_out:
        return {"ok": False, "timeout": True, "errors": [], "warnings": [], "axioms": {},
                "bad_axioms": {}, "sorry": False, "banned": [], "stderr": ""}
    msgs = _parse(out)
    fmt = lambda m: {"line": m.get("pos", {}).get("line"), "col": m.get("pos", {}).get("column"),
                     "msg": m.get("data", "")}
    errors = [fmt(m) for m in msgs if m.get("severity") == "error"]
    warnings = [fmt(m) for m in msgs if m.get("severity") == "warning"]
    axioms = {}
    for m in msgs:
        d = m.get("data", "")
        for name, lst in AXLINE.findall(d):
            axioms[name] = [a.strip() for a in lst.split(",") if a.strip()]
        for name in NOAX.findall(d):
            axioms[name] = []
    sorry = any("sorryAx" in a for a in axioms.values()) or \
        any("declaration uses 'sorry'" in w["msg"] for w in warnings)
    banned = sorted(set(BANNED.findall(code)))
    bad = {n: [a for a in ax if a not in SAFE_AXIOMS and a != "sorryAx"] for n, ax in axioms.items()}
    bad = {n: v for n, v in bad.items() if v}
    ok = (not errors and not sorry and not banned and not bad
          and len(axioms) == len(names) and not (err.strip() and not msgs))
    return {"ok": ok, "timeout": False, "errors": errors, "warnings": warnings, "axioms": axioms,
            "bad_axioms": bad, "sorry": sorry, "banned": banned, "stderr": err[-2000:]}