tinyprove 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tinyprove/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ from .core import (
2
+ TypecheckError,
3
+ Term, Sort, Const, Var, Pi, Lam, App,
4
+ Definitions, AxiomDefinition, ConstDefinition,
5
+ infer, check,
6
+ )
7
+ from .ir import (
8
+ IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp,
9
+ )
10
+ from .parser import (
11
+ parse_ir, parse,
12
+ )
13
+ from .inductive import (
14
+ InductiveDef, IrConstructorDefinition, IrInductiveSelfRef,
15
+ )
16
+ from .axiom_defs import (
17
+ get_usual_axioms,
18
+ )
19
+
20
+
21
+ try:
22
+ from importlib.metadata import version
23
+ __version__ = version("tinyprove")
24
+ except Exception:
25
+ __version__ = "0.0.0"
26
+
27
+
@@ -0,0 +1,62 @@
1
+ from .ir import *
2
+ from .parser import parse
3
+ from .core import Definitions, AxiomDefinition
4
+ from .inductive import InductiveDef, IrConstructorDefinition, IrInductiveSelfRef
5
+
6
+
7
+
8
+ def get_usual_axioms():
9
+ ans = Definitions()
10
+
11
+ # Constructive:
12
+
13
+ ans.add(InductiveDef("False", IrSort(0), [], [], [], ans))
14
+
15
+ ans.add(InductiveDef("Unit", IrSort(0), [], [],
16
+ [
17
+ IrConstructorDefinition("in", [], []),
18
+ ], ans))
19
+
20
+ ans.add(InductiveDef("And", IrSort(0), [("A", IrSort(0)), ("B", IrSort(0))], [],
21
+ [
22
+ IrConstructorDefinition("in", [("a", IrVar("A")), ("b", IrVar("B"))], []),
23
+ ], ans))
24
+
25
+ ans.add(InductiveDef("Or", IrSort(0), [("A", IrSort(0)), ("B", IrSort(0))], [],
26
+ [
27
+ IrConstructorDefinition("inl", [("a", IrVar("A"))], []),
28
+ IrConstructorDefinition("inr", [("b", IrVar("B"))], []),
29
+ ], ans))
30
+
31
+ ans.add(InductiveDef("Eq", IrSort(0), [("A", IrSort(0)), ("x", IrVar("A"))], [("y", IrVar("A"))],
32
+ [
33
+ IrConstructorDefinition("refl", [], [IrVar("x")]),
34
+ ], ans))
35
+
36
+ ans.add(InductiveDef("Exists", IrSort(0), [("A", IrSort(0)), ("P", IrPi("a", IrVar("A"), IrSort(0)))], [],
37
+ [
38
+ IrConstructorDefinition("in", [("a", IrVar("A")), ("pa", IrApp(IrVar("P"), IrVar("a")))], []),
39
+ ], ans))
40
+
41
+ ans.add(InductiveDef("Nat", IrSort(0), [], [],
42
+ [
43
+ IrConstructorDefinition("Z", [], []),
44
+ IrConstructorDefinition("S", [("n", IrInductiveSelfRef([]))], []),
45
+ ], ans))
46
+
47
+
48
+ # Non-constructive:
49
+
50
+ ans.add(AxiomDefinition(
51
+ "",
52
+ {
53
+ "em": parse("Π A: Type0 => (Or A (Π a: A => False))")
54
+ },
55
+ ans))
56
+
57
+ return ans
58
+
59
+
60
+
61
+
62
+
tinyprove/core.py ADDED
@@ -0,0 +1,320 @@
1
+ from dataclasses import dataclass
2
+ from typing import List, Dict, Tuple, Set
3
+ from enum import Enum
4
+
5
+
6
+
7
+ class TypecheckError(Exception):
8
+ pass
9
+
10
+
11
+ # ---- Term AST and DeBruijn Manipulations: ----
12
+
13
+ class Term:
14
+ """ Base class for tinyprove AST. """
15
+ def __str__(self):
16
+ return self.str([])
17
+
18
+ @dataclass(frozen=True)
19
+ class Sort(Term):
20
+ level: int
21
+ def str(self, ctx):
22
+ return f"Type{self.level}"
23
+ def shift(self, shift, keep=0):
24
+ return self
25
+ def subst(self, j, term):
26
+ return self
27
+
28
+ @dataclass(frozen=True)
29
+ class Const(Term):
30
+ name: str
31
+ def str(self, ctx):
32
+ return self.name
33
+ def shift(self, shift, keep=0):
34
+ return self
35
+ def subst(self, j, term):
36
+ return self
37
+
38
+ @dataclass(frozen=True)
39
+ class Var(Term):
40
+ depth: int
41
+ def str(self, ctx):
42
+ if self.depth < len(ctx):
43
+ return ctx[self.depth][0]
44
+ else:
45
+ return f"^{self.depth}"
46
+ def shift(self, shift, keep=0):
47
+ if self.depth < keep: return self
48
+ return Var(self.depth + shift)
49
+ def subst(self, j, term):
50
+ if self.depth == j:
51
+ return term
52
+ if self.depth > j:
53
+ return Var(self.depth - 1) # substitution removes a variable
54
+ return self
55
+
56
+ @dataclass(frozen=True)
57
+ class Pi(Term):
58
+ param: str
59
+ A: Term
60
+ B: Term
61
+ def str(self, ctx):
62
+ return f"(Π {self.param}: {self.A.str(ctx)} => {self.B.str([(self.param, None)] + ctx)})"
63
+ def shift(self, shift, keep=0):
64
+ return Pi(self.param, self.A.shift(shift, keep), self.B.shift(shift, keep + 1)) # keep param
65
+ def subst(self, j, term):
66
+ return Pi(self.param, self.A.subst(j, term), self.B.subst(j + 1, term.shift(1)))
67
+
68
+ @dataclass(frozen=True)
69
+ class Lam(Term):
70
+ param: str
71
+ A: Term
72
+ body: Term
73
+ def str(self, ctx):
74
+ return f"(λ {self.param}: {self.A.str(ctx)} -> {self.body.str([(self.param, None)] + ctx)})"
75
+ def shift(self, shift, keep=0):
76
+ return Lam(self.param, self.A.shift(shift, keep), self.body.shift(shift, keep + 1)) # keep param
77
+ def subst(self, j, term):
78
+ return Lam(self.param, self.A.subst(j, term), self.body.subst(j + 1, term.shift(1)))
79
+
80
+ '''
81
+ @dataclass(frozen=True)
82
+ class Let(Term):
83
+ param:str
84
+ val: Term
85
+ body: Term
86
+ def str(self, ctx):
87
+ return f"let {self.param} = {self.val.str(ctx)}; {self.body.str([(self.param, None)] + ctx)}"
88
+ def shift(self, shift, keep=0):
89
+ return Let(self.param, self.val.shift(shift, keep), self.body.shift(shift, keep + 1))
90
+ def subst(self, j, term):
91
+ return Let(self.param, self.val.subst(j, term), self.body.subst(j + 1, term.shift(1)))
92
+ '''
93
+
94
+ @dataclass(frozen=True)
95
+ class App(Term):
96
+ fn: Term
97
+ arg: Term
98
+ def str(self, ctx):
99
+ return f"({self.fn.str(ctx)} {self.arg.str(ctx)})"
100
+ def shift(self, shift, keep=0):
101
+ return App(self.fn.shift(shift, keep), self.arg.shift(shift, keep))
102
+ def subst(self, j, term):
103
+ return App(self.fn.subst(j, term), self.arg.subst(j, term))
104
+
105
+
106
+ # ---- Proof Environment: ----
107
+
108
+ class Definitions:
109
+ """ An environment class that holds various kinds of definitions that are referenced by Const terms. """
110
+ def __init__(self):
111
+ self.defs = {}
112
+ def add(self, definition):
113
+ def_name = definition.name
114
+ if "." in def_name:
115
+ raise RuntimeError(f"{def_name} is not a legal definition name, as these cannot contain the `.` separator.")
116
+ if def_name in self.defs:
117
+ raise RuntimeError(f"Can't add another definition with the same name ({def_name}) as an existing one.")
118
+ self.defs[def_name] = definition
119
+ def remove(self, def_name:str):
120
+ if def_name not in self.defs:
121
+ raise RuntimeError(f"No definition named {def_name} was found.")
122
+ is_being_used = any(
123
+ def_name in definition.used
124
+ for definition in self.defs.values()
125
+ )
126
+ if is_being_used:
127
+ raise RuntimeError(f"Definition {def_name} is currently in use by other definitions in this environment.")
128
+ del self.defs[def_name]
129
+ def __getitem__(self, key:str) -> Term:
130
+ assert isinstance(key, str)
131
+ name, *rest = key.split(".")
132
+ return self.defs[name].get_type(rest)
133
+ def __contains__(self, key:str) -> bool:
134
+ try:
135
+ self[key]
136
+ except KeyError:
137
+ return False
138
+ else:
139
+ return True
140
+ def match_reduce(self, key:str, argchain: List[Term], defns) -> Tuple[Term, List[Term]] | None:
141
+ name, *rest = key.split(".")
142
+ return self.defs[name].match_reduce(rest, argchain, defns)
143
+
144
+
145
+ # ---- WHNF Reduction and Type-checking / Inference: ----
146
+
147
+ def to_app_list(term:Term) -> Tuple[Term, List[Term]]:
148
+ match term:
149
+ case App(fn, arg):
150
+ head, args = to_app_list(fn)
151
+ args.append(arg)
152
+ return head, args
153
+ case other:
154
+ return other, []
155
+
156
+ def argchain_whnf(head:Term, args:List[Term], defns:Definitions) -> Tuple[Term, List[Term]]:
157
+ """ Workhorse function of whnf reduction. Terms are represented as a non-App head and a list of args.
158
+ beta reduction is built-in, and defns can supply other reductions through .match_reduce() """
159
+ # make head not an App by adding arguments to args
160
+ head, new_args = to_app_list(head)
161
+ args = new_args + args
162
+ # reduce if we can, otherwise return
163
+ match head:
164
+ case Lam(param, A, body):
165
+ if len(args) >= 1: # lambdas can be reduced if there is an arg to apply them to
166
+ head = body.subst(0, args[0])
167
+ args = args[1:] # first argument was used up
168
+ else:
169
+ return head, args
170
+ case Const(name):
171
+ subst = defns.match_reduce(name, args, defns)
172
+ if subst is None: # no reduction supplied
173
+ return head, args
174
+ else:
175
+ head, args = subst # we use the reduction supplied by defns
176
+ case _: # nothing else can be reduced
177
+ return head, args
178
+ # we've done a reduction so head could be an App now
179
+ return argchain_whnf(head, args, defns) # recursive call
180
+
181
+ def whnf(term:Term, defns:Definitions) -> Term:
182
+ """ Reduce term to weak head normal form. """
183
+ head, args = argchain_whnf(term, [], defns)
184
+ ans = head
185
+ while len(args) > 0:
186
+ ans = App(ans, args[0])
187
+ args = args[1:]
188
+ return ans
189
+
190
+
191
+ def conv(t1:Term, t2:Term, defns:Definitions) -> bool:
192
+ t1 = whnf(t1, defns)
193
+ t2 = whnf(t2, defns)
194
+ match t1, t2:
195
+ case Sort(l1), Sort(l2):
196
+ return l1 == l2
197
+ case Var(depth1), Var(depth2):
198
+ return depth1 == depth2
199
+ case Const(name1), Const(name2):
200
+ return name1 == name2
201
+ case App(fn1, arg1), App(fn2, arg2):
202
+ return conv(fn1, fn2, defns) and conv(arg1, arg2, defns)
203
+ case Pi(_, A1, B1), Pi(_, A2, B2):
204
+ return conv(A1, A2, defns) and conv(B1, B2, defns)
205
+ case Lam(_, A1, body1), Lam(_, A2, body2):
206
+ return conv(A1, A2, defns) and conv(body1, body2, defns)
207
+ case _:
208
+ return False # mismatched shapes
209
+
210
+ def infer(term:Term, ctx, defns:Definitions) -> Term:
211
+ match term:
212
+ case Sort(level):
213
+ return Sort(level + 1)
214
+ case Const(name):
215
+ if name not in defns:
216
+ raise TypecheckError(f"Unknown constant {name}.")
217
+ return defns[name]
218
+ case Var(depth):
219
+ if 0 <= depth < len(ctx):
220
+ name, var_ty = ctx[depth]
221
+ return var_ty.shift(depth + 1)
222
+ else:
223
+ raise TypecheckError(f"Tried to lookup a varible with depth {depth} in context of size {len(ctx)}")
224
+ case Pi(param, A, B):
225
+ A_ty = whnf(infer(A, ctx, defns), defns)
226
+ if not isinstance(A_ty, Sort):
227
+ raise TypecheckError(f"Expected A in Pi type {term.str(ctx)} to be a Sort, but found {A_ty.str(ctx)}.")
228
+ ctx_B = [(param, A)] + ctx
229
+ B_ty = whnf(infer(B, ctx_B, defns), defns)
230
+ if not isinstance(B_ty, Sort):
231
+ raise TypecheckError(f"Expected B in Pi type {term.str(ctx)} to be a Sort, but found {B_ty.str(ctx_B)}.")
232
+ return Sort(max(A_ty.level, B_ty.level))
233
+ case Lam(param, A, body):
234
+ A_ty = whnf(infer(A, ctx, defns), defns)
235
+ if not isinstance(A_ty, Sort):
236
+ raise TypecheckError(f"Expected A in Lam {term.str(ctx)} to be a Sort, but found {A_ty.str(ctx)}")
237
+ ctx_body = [(param, A)] + ctx
238
+ body_ty = infer(body, ctx_body, defns)
239
+ return Pi(param, A, body_ty)
240
+ case App(fn, arg):
241
+ fn_ty = whnf(infer(fn, ctx, defns), defns)
242
+ match fn_ty:
243
+ case Pi(param, A, B):
244
+ check(arg, A, ctx, defns)
245
+ ctx_B = [(param, A)] + ctx
246
+ return whnf(B.subst(0, arg), defns)
247
+ case _:
248
+ raise TypecheckError(f"Expected type of fn in application {term.str(ctx)} to be a Pi type, but found {fn_ty.str(ctx)}.")
249
+ case _:
250
+ raise TypecheckError(f"Failed to recognize term {term}")
251
+
252
+ def check(term, expected, ctx, defns:Definitions):
253
+ term_ty = infer(term, ctx, defns)
254
+ if not conv(term_ty, expected, defns):
255
+ raise TypecheckError(f"Expected term {term.str(ctx)} to have type {expected.str(ctx)} but found {term_ty.str(ctx)}.")
256
+
257
+
258
+
259
+ # ---- Definition Classes: ----
260
+
261
+ def find_used_defs(*terms:Tuple[Term]) -> Set[str]:
262
+ terms = list(terms)
263
+ ans = set()
264
+ i = 0 # do a BFS of the Term tree
265
+ while i < len(terms):
266
+ term_i = terms[i]
267
+ match term_i:
268
+ case Pi(param, A, B):
269
+ terms.append(A)
270
+ terms.append(B)
271
+ case Lam(param, A, body):
272
+ terms.append(A)
273
+ terms.append(body)
274
+ case App(fn, arg):
275
+ terms.append(fn)
276
+ terms.append(arg)
277
+ case Const(name): # if it's a Const, it uses other definitions!
278
+ ans.add(name.split(".")[0])
279
+ i += 1
280
+ return ans
281
+
282
+ class AxiomDefinition:
283
+ def __init__(self, name:str, axioms:Dict[str, Term], defns:Definitions):
284
+ self.name = name
285
+ self.axioms = axioms
286
+ axiom_terms = []
287
+ for axiom_name in self.axioms:
288
+ axiom = self.axioms[axiom_name]
289
+ axiom_ty = whnf(infer(axiom, [], defns), defns)
290
+ if not isinstance(axiom_ty, Sort):
291
+ raise TypecheckError(f"Expected type of axiom {self.name}.{axiom_name} to be a Sort.")
292
+ axiom_terms.append(axiom)
293
+ self.used = find_used_defs(*axiom_terms)
294
+ def get_type(self, key:List[str]) -> Term:
295
+ match key:
296
+ case [axiom_name]:
297
+ if axiom_name in self.axioms:
298
+ return self.axioms[axiom_name]
299
+ raise IndexError(f"Couldn't find key {self.name}.{'.'.join(key)}.")
300
+ def match_reduce(self, key:List[str], argchain: List[Term], defns:Definitions) -> Tuple[Term, List[Term]] | None:
301
+ return None
302
+
303
+ class ConstDefinition:
304
+ def __init__(self, name:str, value:Term, defns:Definitions):
305
+ self.name = name
306
+ self.value = whnf(value, defns)
307
+ self.type = whnf(infer(self.value, [], defns), defns)
308
+ self.used = find_used_defs(self.value)
309
+ def get_type(self, key:List[str]) -> Term:
310
+ match key:
311
+ case []:
312
+ return self.type
313
+ raise IndexError(f"Couldn't find key {self.name}.{'.'.join(key)}.")
314
+ def match_reduce(self, key:List[str], argchain: List[Term], defns:Definitions) -> Tuple[Term, List[Term]] | None:
315
+ match key:
316
+ case []:
317
+ return self.value, argchain
318
+ raise IndexError(f"Couldn't find key {self.name}.{'.'.join(key)}.")
319
+
320
+
tinyprove/inductive.py ADDED
@@ -0,0 +1,340 @@
1
+ from __future__ import annotations
2
+ from typing import List, Dict, Tuple
3
+
4
+ from .core import *
5
+ from .ir import *
6
+
7
+
8
+ class DefinitionError(Exception):
9
+ pass
10
+
11
+
12
+ def pi_wrap(inner:IrNode, ctx:List[Tuple[str, IrNode]]):
13
+ """ Wrap an inner type in a context. """
14
+ ans = inner
15
+ for nm, ty in ctx:
16
+ ans = IrPi(nm, ty, ans)
17
+ return ans
18
+
19
+ def app_wrap(fn:IrNode, args:List[IrNode]):
20
+ ans = fn
21
+ for arg in args:
22
+ ans = IrApp(ans, arg)
23
+ return ans
24
+
25
+ def ctx_to_names(ctx:List[Tuple[str, IrNode]]) -> List[str]:
26
+ return [nm for nm, _ in ctx]
27
+
28
+ def names_unique(names:List[str]) -> bool:
29
+ seen = set()
30
+ for nm in names:
31
+ if nm in seen: return False
32
+ seen.add(nm)
33
+ return True
34
+
35
+
36
+ class DefsExtend:
37
+ """ Temporarily extend definitions with a dict of additional definitions. """
38
+ def __init__(self, base_defns, new_defs_dict:dict):
39
+ self.base_defns = base_defns
40
+ self.new_defs_dict = new_defs_dict
41
+ for key in self.new_defs_dict:
42
+ assert key not in self.base_defns, "duplicate key {key}"
43
+ def __getitem__(self, key:str) -> Term:
44
+ if key in self.new_defs_dict:
45
+ return self.new_defs_dict[key]
46
+ return self.base_defns[key]
47
+ def __contains__(self, key:str) -> bool:
48
+ return key in self.new_defs_dict or key in self.base_defns
49
+ def match_reduce(self, key:str, argchain: List[Term], defns:Definitions) -> Tuple[Term, List[Term]] | None:
50
+ return self.base_defns.match_reduce(key, argchain, defns)
51
+
52
+
53
+ def typecheck_args(args:List[Tuple[str, IrNode]], ctx:List[Tuple[str, Term]], selfref_ir:IrNode, defns:Definitions):
54
+ """ Given a list of args that might be type parameters or constructor args,
55
+ check that they are all some kind of Sort. Returns a full ctx containing all args. """
56
+ if len(args) == 0: return ctx
57
+ (arg_nm, arg_ty_ir), *args_rest = args
58
+ arg_ty = selfref_sub(arg_ty_ir, selfref_ir).to_term(ctx_to_names(ctx))
59
+ arg_ty_ty = infer(arg_ty, ctx, defns)
60
+ if not isinstance(arg_ty_ty, Sort):
61
+ raise TypecheckError(f"Expected {arg_ty.str(ctx)} to be a Sort but found type {ty_ty.str(ctx)}.")
62
+ return typecheck_args(args_rest, [(arg_nm, arg_ty)] + ctx, selfref_ir, defns)
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class IrInductiveSelfRef(IrNode):
67
+ index_vals: List[IrNode]
68
+ def to_term(self, ctx_nm):
69
+ raise RuntimeError("Can't convert IrInductiveSelfRef to Term, you should use selfref_sub() to expand it first.")
70
+
71
+ @dataclass(frozen=True)
72
+ class IrConstructorDefinition(IrNode):
73
+ name: str
74
+ args: List[Tuple[str, IrNode]]
75
+ output_indices: List[IrNode]
76
+ def to_term(self, ctx_nm):
77
+ raise RuntimeError("Can't convert IrConstructorDefinition to Term, it is intended for creating InductiveDef's only.")
78
+
79
+ def selfref_sub(node:IrNode, selfref_ir:IrNode) -> IrNode:
80
+ match node:
81
+ case IrLam(param, A, body):
82
+ return IrLam(param, selfref_sub(A, selfref_ir), selfref_sub(body, selfref_ir))
83
+ case IrPi(param, A, B):
84
+ return IrPi(param, selfref_sub(A, selfref_ir), selfref_sub(B, selfref_ir))
85
+ case IrApp(fn, arg):
86
+ return IrApp(selfref_sub(fn, selfref_ir), selfref_sub(arg, selfref_ir))
87
+ case IrSort(level):
88
+ return IrSort(level)
89
+ case IrVar(nm):
90
+ return IrVar(nm)
91
+ case IrConst(name):
92
+ return IrConst(name)
93
+ case IrInductiveSelfRef(index_vals):
94
+ return app_wrap(selfref_ir, index_vals)
95
+ case _:
96
+ raise DefinitionError("Unknown node type.")
97
+
98
+
99
+ def walk(indty_name: str, node:IrNode, polarity:bool=True) -> bool:
100
+ """ Do a polarity check of node to ensure that self-references to our inductive type are positive only.
101
+ polarity: True = positive, and False = negative """
102
+ match node:
103
+ case IrLam():
104
+ raise DefinitionError("Lambdas not supported in constructor definition.")
105
+ case IrPi(param, A, B):
106
+ return walk(indty_name, A, not polarity) and walk(indty_name, B, polarity)
107
+ case IrApp(fn, arg):
108
+ return walk(indty_name, fn, polarity) and walk(indty_name, arg, polarity)
109
+ case IrSort():
110
+ return True
111
+ case IrVar(nm):
112
+ return True
113
+ case IrConst(name):
114
+ if name == indty_name:
115
+ raise DefinitionError("Found an IrConst that refers back to the original inductive type! This should be done solely with IrInductiveSelfRef.")
116
+ return True
117
+ case IrInductiveSelfRef(index_vals):
118
+ return polarity
119
+ case _:
120
+ raise DefinitionError("Unknown node type.")
121
+
122
+
123
+ class ConstructorDef:
124
+ def __init__(self, indty:InductiveDef, name:str, args:List[Tuple[str, IrNode]], output_indices:List[IrNode]):
125
+ if name == "ind": raise DefinitionError("ind is a reserved name and cannot be used as a constructor name.")
126
+ self.indty = indty
127
+ self.name = name
128
+ assert names_unique(ctx_to_names(self.indty.params + args)), "constructor arguments should have unique names"
129
+ self.args = args
130
+ self.output_indices = output_indices
131
+ # type & positivity checking:
132
+ constructor_ctx = typecheck_args(self.args, self.indty.params_ctx, self.indty.selfref_ir, self.indty.defns_ext)
133
+ self.check_positive()
134
+ self.check_output_indices(constructor_ctx, self.indty.inds_ctx)
135
+ # prep data that will be used by match-reduce
136
+ self.matchred_sig = self.get_matchred_sig()
137
+ self.arg_tys = [arg_ty for _, arg_ty in constructor_ctx[:len(self.args)]]
138
+ def get_ty(self):
139
+ return pi_wrap(
140
+ pi_wrap(
141
+ IrInductiveSelfRef(self.output_indices),
142
+ self.args[::-1]),
143
+ self.indty.params[::-1])
144
+ def get_case_fn_ty(self):
145
+ converted_args = [] # args list that will include any necessary recursion
146
+ for arg_nm, arg_ty in self.args:
147
+ converted_args.append((arg_nm, arg_ty)) # always use the arg itself
148
+ if isinstance(arg_ty, IrInductiveSelfRef): # add inductive hypothesis for recursion
149
+ rec_ty = IrApp(
150
+ app_wrap(
151
+ IrVar("@motive"),
152
+ arg_ty.index_vals),
153
+ IrVar(arg_nm))
154
+ converted_args.append((f"@rec_{arg_nm}", rec_ty))
155
+ applied_constructor_ty = app_wrap(
156
+ app_wrap(
157
+ IrConst(f"{self.indty.name}.{self.name}"),
158
+ [IrVar(varnm) for varnm, _ in self.indty.params]),
159
+ [IrVar(argnm) for argnm, _ in self.args])
160
+ return pi_wrap(
161
+ IrApp(
162
+ app_wrap(
163
+ IrVar("@motive"),
164
+ self.output_indices),
165
+ applied_constructor_ty),
166
+ converted_args[::-1])
167
+ def check_positive(self):
168
+ for arg_nm, arg_ty in self.args:
169
+ if not walk(self.indty.name, arg_ty):
170
+ raise DefinitionError(f"Constructor {self.name} arg {arg_nm} fails positivity check.")
171
+ def check_output_indices(self, constructor_ctx:List[Tuple[str, Term]], inds_ctx:List[Tuple[str, Term]]):
172
+ num_inds = len(self.indty.indices)
173
+ assert len(self.output_indices) == num_inds, f"Constructor {self.name} definition has incorrect number of output indices."
174
+ for i in range(num_inds):
175
+ output_index_i = self.output_indices[i].to_term(ctx_to_names(constructor_ctx))
176
+ output_index_ty = infer(output_index_i, constructor_ctx, self.indty.defns_ext)
177
+ target_nm, target_ty = inds_ctx[num_inds - 1 - i]
178
+ if not conv(output_index_ty, target_ty, self.indty.defns):
179
+ raise TypecheckError(f"Constructor {self.name} output index {target_nm} has the wrong type.")
180
+ def get_matchred_sig(self):
181
+ ans = []
182
+ for i, (_, arg_ty) in enumerate(self.args):
183
+ if isinstance(arg_ty, IrInductiveSelfRef):
184
+ arg_names = [arg_nm for arg_nm, _ in reversed(self.indty.params + self.args[:i])] # reverse to make a ctx
185
+ ans.append([index_val.to_term(arg_names) for index_val in arg_ty.index_vals])
186
+ else:
187
+ ans.append(None)
188
+ return ans
189
+
190
+
191
+ def subst_args_as_term_ctx(t:Term, args:List[Term]):
192
+ for i, arg in enumerate(args):
193
+ depth = len(args) - i - 1
194
+ t = t.subst(depth, arg)
195
+ return t
196
+
197
+
198
+ class InductiveDef:
199
+ def __init__(self,
200
+ name:str, sort:IrSort,
201
+ params:List[Tuple[str, IrNode]], indices:List[Tuple[str, IrNode]],
202
+ constructors:List[IrConstructorDefinition],
203
+ defns: Definitions):
204
+ # general type setup:
205
+ self.name = name
206
+ self.sort = sort
207
+ assert names_unique(ctx_to_names(params + indices))
208
+ self.params = params
209
+ self.indices = indices
210
+ self.defns = defns
211
+ # compute intermediate representations:
212
+ self.ty_ir = self._get_ty()
213
+ self.selfref_ir = self._get_selfref_ir()
214
+ # type checking:
215
+ self.params_ctx = typecheck_args(self.params, [], self.selfref_ir, self.defns)
216
+ self.inds_ctx = typecheck_args(self.indices, self.params_ctx, self.selfref_ir, self.defns)
217
+ self.ty = self.ty_ir.to_term([])
218
+ self.defns_ext = DefsExtend(self.defns, {self.name: self.ty})
219
+ # constructors setup:
220
+ self.constructors = [
221
+ ConstructorDef(self, constructor_ir.name, constructor_ir.args, constructor_ir.output_indices)
222
+ for constructor_ir in constructors
223
+ ]
224
+ assert names_unique([constructor.name for constructor in self.constructors]), "Constructor names duplicate with each other."
225
+ self.constructors_dict = {f"{self.name}.{self.constructors[i].name}": i for i in range(len(self.constructors))}
226
+ # dicts containing Term types:
227
+ self.constructor_tys = {
228
+ constructor.name: selfref_sub(constructor.get_ty(), self.selfref_ir).to_term([])
229
+ for constructor in self.constructors
230
+ }
231
+ self.ind_tys = {}
232
+ self.used = find_used_defs(
233
+ self.ty,
234
+ *[self.constructor_tys[cons_nm] for cons_nm in self.constructor_tys])
235
+ self.used.discard(self.name) # don't count self-reference as "use"
236
+ def _get_ty(self):
237
+ return pi_wrap(pi_wrap(self.sort, self.indices[::-1]), self.params[::-1])
238
+ def _get_selfref_ir(self):
239
+ return app_wrap(
240
+ IrConst(self.name),
241
+ [IrVar(nm) for nm, _ in self.params]
242
+ )
243
+ def get_index_vars(self) -> List[IrNode]:
244
+ """ Get a list of vars corresponding to this inductive's indices.
245
+ Note: Assumes that the vars will be present somewhere in the context. """
246
+ return [IrVar(index_nm) for index_nm, _ in self.indices]
247
+ def get_motive_ty(self, output_ty:IrNode) -> IrNode:
248
+ """ get the type of a motive (inductive hypothesis) with a particular output type """
249
+ return pi_wrap(
250
+ IrPi("@instance",
251
+ IrInductiveSelfRef(self.get_index_vars()),
252
+ output_ty),
253
+ self.indices[::-1])
254
+ def get_ind_ty(self, sort:IrSort) -> IrNode:
255
+ motive_ty = self.get_motive_ty(sort)
256
+ ans_ty = self.get_motive_ty(
257
+ IrApp(
258
+ app_wrap(
259
+ IrVar("@motive"),
260
+ self.get_index_vars()),
261
+ IrVar("@instance")))
262
+ constructor_case_fns = [
263
+ ("@case_" + constructor.name, constructor.get_case_fn_ty())
264
+ for constructor in self.constructors
265
+ ]
266
+ ans_ty = pi_wrap(
267
+ ans_ty,
268
+ constructor_case_fns[::-1])
269
+ return pi_wrap(
270
+ IrPi("@motive", motive_ty, ans_ty),
271
+ self.params[::-1])
272
+ def get_type(self, key:List[str]) -> Term:
273
+ match key:
274
+ case ["ind", sortnum]:
275
+ sortnum = to_positive_int(sortnum)
276
+ if sortnum is None: raise IndexError("Induction for Type<n> is denoted by ind.<n> with n a non-negative integer.")
277
+ if sortnum not in self.ind_tys:
278
+ ind_ty_ir = self.get_ind_ty(IrSort(sortnum))
279
+ self.ind_tys[sortnum] = selfref_sub(ind_ty_ir, self.selfref_ir).to_term([])
280
+ return self.ind_tys[sortnum]
281
+ case [constructor_name]:
282
+ if constructor_name not in self.constructor_tys:
283
+ raise IndexError(f"Constructor name {constructor_name} does not exist in this definition.")
284
+ return self.constructor_tys[constructor_name]
285
+ case []:
286
+ return self.ty
287
+ raise IndexError("InductiveDef couldn't find key {'.'.join(key)}.")
288
+ def match_reduce(self, key:List[str], argchain: List[Term], defns:Definitions) -> Tuple[Term, List[Term]] | None:
289
+ match key:
290
+ case ["ind", sortnum]:
291
+ sortnum = to_positive_int(sortnum)
292
+ assert sortnum is not None, f"<n> should be a positive integer in {self.name}.ind.<n>"
293
+ n_params = len(self.params)
294
+ n_constructors = len(self.constructors)
295
+ n_indices = len(self.indices)
296
+ if len(argchain) < (n_params + 1 + n_constructors + n_indices + 1):
297
+ return None # too few args
298
+ # get induction arguments
299
+ params, argchain = argchain[:n_params], argchain[n_params:]
300
+ motive, argchain = argchain[0], argchain[1:]
301
+ cases, argchain = argchain[:n_constructors], argchain[n_constructors:]
302
+ indices, argchain = argchain[:n_indices], argchain[n_indices:]
303
+ scrutinee, argchain = argchain[0], argchain[1:]
304
+ # have to do recursive whnf on the scrutinee, just in case any redexes produce a construtor
305
+ scru_head, scru_args = to_app_list(scrutinee)
306
+ scru_head, scru_args = argchain_whnf(scru_head, scru_args, defns)
307
+ # second part of checking for iota reduction is checking if scrutinee is a constructor
308
+ match scru_head:
309
+ case Const(name):
310
+ if name not in self.constructors_dict: return None # not a constructor for this type
311
+ cons_idx = self.constructors_dict[name]
312
+ constructor = self.constructors[cons_idx]
313
+ if len(scru_args) != n_params + len(constructor.matchred_sig):
314
+ return None # too few or too many args
315
+ case_fn_args = []
316
+ for i, (scru_arg, rec_indices) in enumerate(zip(scru_args[n_params:], constructor.matchred_sig)):
317
+ case_fn_args.append(scru_arg)
318
+ if rec_indices is not None:
319
+ recursive_call = Const(f"{self.name}.ind.{sortnum}")
320
+ for param in params:
321
+ recursive_call = App(recursive_call, param)
322
+ recursive_call = App(recursive_call, motive)
323
+ for case_fn in cases:
324
+ recursive_call = App(recursive_call, case_fn)
325
+ for idx_expr in rec_indices:
326
+ idx_val = subst_args_as_term_ctx(idx_expr, scru_args[:n_params + i])
327
+ recursive_call = App(recursive_call, idx_val)
328
+ recursive_call = App(recursive_call, scru_arg)
329
+ case_fn_args.append(recursive_call)
330
+ case_fn = cases[cons_idx]
331
+ return case_fn, case_fn_args + argchain
332
+ case _: # not a constructor
333
+ return None
334
+ case _: # callee is not .ind
335
+ return None
336
+
337
+
338
+
339
+
340
+
tinyprove/ir.py ADDED
@@ -0,0 +1,84 @@
1
+ from typing import List, Dict, Tuple
2
+
3
+ from .core import *
4
+
5
+
6
+ """
7
+ This class defines an intermediate representation that is useful for
8
+ parsing and writing code to generate inductive definitions & that
9
+ kind of thing.
10
+ """
11
+
12
+
13
+ class IrNode:
14
+ def to_term(self, ctx_nm):
15
+ raise RuntimeError("Not implemented.")
16
+
17
+ @dataclass(frozen=True)
18
+ class IrSort(IrNode):
19
+ level: int
20
+ def to_term(self, ctx_nm):
21
+ if self.level >= 0:
22
+ return Sort(self.level)
23
+ else:
24
+ raise RuntimeError("IrSort: level must be >= 0.")
25
+
26
+ @dataclass(frozen=True)
27
+ class IrConst(IrNode):
28
+ constnm: str
29
+ def to_term(self, ctx_nm):
30
+ if self.constnm in ctx_nm:
31
+ raise RuntimeError(f"Constant name {self.constnm} unexpectedly found in context when converting IrConst to term.")
32
+ return Const(self.constnm)
33
+
34
+ @dataclass(frozen=True)
35
+ class IrVar(IrNode):
36
+ varnm: str
37
+ def to_term(self, ctx_nm):
38
+ for i in range(len(ctx_nm)):
39
+ if ctx_nm[i] == self.varnm:
40
+ return Var(i)
41
+ raise RuntimeError(f"Variable name {self.varnm} not found in context when converting IrVar to term.")
42
+
43
+ @dataclass(frozen=True)
44
+ class IrPi(IrNode):
45
+ param: str
46
+ A: IrNode
47
+ B: IrNode
48
+ def to_term(self, ctx_nm):
49
+ return Pi(
50
+ self.param,
51
+ self.A.to_term(ctx_nm),
52
+ self.B.to_term([self.param] + ctx_nm))
53
+
54
+ @dataclass(frozen=True)
55
+ class IrLam(IrNode):
56
+ param: str
57
+ A: IrNode
58
+ body: IrNode
59
+ def to_term(self, ctx_nm):
60
+ return Lam(
61
+ self.param,
62
+ self.A.to_term(ctx_nm),
63
+ self.body.to_term([self.param] + ctx_nm))
64
+
65
+ @dataclass(frozen=True)
66
+ class IrApp(IrNode):
67
+ fn: IrNode
68
+ arg: IrNode
69
+ def to_term(self, ctx_nm):
70
+ return App(
71
+ self.fn.to_term(ctx_nm),
72
+ self.arg.to_term(ctx_nm))
73
+
74
+
75
+ # utility function(s) for various users of this file:
76
+ def to_positive_int(digits:str) -> int | None:
77
+ try:
78
+ val = int(digits)
79
+ except ValueError:
80
+ return None
81
+ if val < 0: return None
82
+ return val
83
+
84
+
tinyprove/parser.py ADDED
@@ -0,0 +1,141 @@
1
+ import re
2
+ from typing import List, Tuple
3
+
4
+ from .ir import IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp, to_positive_int
5
+ from .core import Term
6
+
7
+
8
+ # Tokeniser:
9
+ _ident_re = r"[\.A-Za-z_][\.A-Za-z0-9_]*"
10
+ _token_re = re.compile(
11
+ r"""
12
+ \s* # skip leading whitespace
13
+ ( # group captures only non-whitespace
14
+ =>|->| # separators
15
+ [():λΠ]| # punctuation (unicode lambdas, etc.)
16
+ """ + _ident_re + """ # identifiers
17
+ )
18
+ """,
19
+ re.VERBOSE,
20
+ )
21
+
22
+
23
+ def _tokenise(src: str) -> List[str]:
24
+ """Return a *list* of string tokens (whitespace already stripped)."""
25
+ return [m.group(1) for m in _token_re.finditer(src)]
26
+
27
+
28
+ def strip_comments(src:str) -> str:
29
+ src = src.split("\n")
30
+ src = [
31
+ (line + "\n")[:line.find("#")]
32
+ for line in src
33
+ ]
34
+ return "\n".join(src)
35
+
36
+
37
+ # Recursive‑descent parser:
38
+ class Parser:
39
+ def __init__(self, tokens: List[str], ctx=None):
40
+ self.toks: List[str] = tokens
41
+ self.pos: int = 0
42
+ self.env: List[str] = [] if ctx is None else [name for name, typ in ctx]
43
+ def _peek(self) -> str | None:
44
+ return self.toks[self.pos] if self.pos < len(self.toks) else None
45
+ def _eat(self, expected: str | None = None) -> str:
46
+ tok = self._peek()
47
+ if tok is None:
48
+ raise SyntaxError("unexpected end‑of‑input")
49
+ if expected is not None and tok != expected:
50
+ raise SyntaxError(f"expected '{expected}', got '{tok}'")
51
+ self.pos += 1
52
+ return tok
53
+ def env_push(self, name):
54
+ self.env.insert(0, name)
55
+ def env_pop(self):
56
+ return self.env.pop(0)
57
+ def parse(self) -> IrNode:
58
+ node = self._parse_expr()
59
+ if self._peek() is not None:
60
+ raise SyntaxError(f"found trailing tokens: {' '.join(self.toks[self.pos:])}")
61
+ return node
62
+ def _parse_expr(self) -> IrNode:
63
+ # Binder constructs have the lowest precedence, so look for them *first*.
64
+ tok = self._peek()
65
+ if tok == "λ":
66
+ return self._parse_lambda()
67
+ if tok == "Π":
68
+ return self._parse_pi()
69
+ # Otherwise we are in application / atom land.
70
+ return self._parse_app()
71
+ def _parse_lambda(self) -> IrNode:
72
+ self._eat("λ")
73
+ name = self._eat() # identifier
74
+ self._eat(":")
75
+ A = self._parse_expr()
76
+ self._eat("->")
77
+ self.env_push(name)
78
+ body = self._parse_expr()
79
+ self.env_pop()
80
+ return IrLam(name, A, body)
81
+ def _parse_pi(self) -> IrNode:
82
+ self._eat("Π")
83
+ name = self._eat()
84
+ self._eat(":")
85
+ A = self._parse_expr()
86
+ self._eat("=>")
87
+ self.env_push(name)
88
+ B = self._parse_expr()
89
+ self.env_pop()
90
+ return IrPi(name, A, B)
91
+ def _parse_app(self) -> IrNode:
92
+ node = self._parse_atom()
93
+ # Without parentheses, we assume application is left-to-right
94
+ while True:
95
+ nxt = self._peek()
96
+ # close-paren or separators break application chain. binder starts do as well.
97
+ if nxt is None or nxt in {")", ":", "=>", "->", "Π", "λ"}:
98
+ break
99
+ arg = self._parse_atom()
100
+ node = IrApp(node, arg)
101
+ return node
102
+ def _parse_atom(self) -> IrNode:
103
+ tok = self._peek()
104
+ if tok is None:
105
+ raise SyntaxError("unexpected end‑of‑input while parsing atom")
106
+ # Parenthesised expression
107
+ if tok == "(":
108
+ self._eat("(")
109
+ expr = self._parse_expr()
110
+ self._eat(")")
111
+ return expr
112
+ # Sorts (Type0, Type1, ...)
113
+ if tok[:4] == "Type":
114
+ level = to_positive_int(tok[4:])
115
+ if level is not None:
116
+ self._eat()
117
+ return IrSort(level)
118
+ # Identifiers (variables / constants)
119
+ if re.match(_ident_re, tok):
120
+ self._eat()
121
+ if tok in self.env:
122
+ return IrVar(tok)
123
+ return IrConst(tok)
124
+ # catchall
125
+ raise SyntaxError(f"unexpected token '{tok}'")
126
+
127
+
128
+ # Parsing functions:
129
+
130
+ def parse_ir(src: str, ctx=None) -> IrNode:
131
+ src = strip_comments(src)
132
+ tokens = _tokenise(src)
133
+ return Parser(tokens, ctx=ctx).parse()
134
+
135
+ def parse(src: str, ctx=None) -> Term:
136
+ ans_ir = parse_ir(src, ctx)
137
+ ctx_names = [] if ctx is None else [nm for nm, _ in ctx]
138
+ return ans_ir.to_term(ctx_names)
139
+
140
+
141
+
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: tinyprove
3
+ Version: 0.1.0
4
+ Summary: Tiny CoC-based theorem prover with inductive types
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+
8
+ # Tinyprove
9
+
10
+ A small, minimal theorem prover.
11
+
12
+ [pytorch](https://pytorch.org/) : [tinygrad](https://github.com/tinygrad/tinygrad) :: [lean](https://lean-lang.org/) : **tinyprove**
13
+
14
+ Get started:
15
+
16
+ ```
17
+ from parser import parse
18
+ from tinyprove import infer, check
19
+ from axiom_defs import DEFNS
20
+ ```
21
+
22
+ Parser supports parsing with a context of existing variables specified.
23
+
24
+ ```
25
+ ctx = [("A", parse("Type0"))]
26
+ identity = parse("λ x: A -> x", ctx)
27
+ ```
28
+
29
+ Terms can be printed (need to pass context).
30
+
31
+ ```
32
+ print(identity.str(ctx))
33
+ ```
34
+
35
+ Type inference:
36
+
37
+ ```
38
+ identity_ty = infer(identity, ctx)
39
+ ```
40
+
41
+ DEFNS supplies some basic inductive types (`False`, `And`, `Or`, `Exists`, `Nat`), plus the classical excluded middle axiom (`.em`).
42
+
43
+ ```
44
+ identity_ty = infer(identity, ctx, defns=DEFNS)
45
+ ```
46
+
47
+ Since `identity` doesn't use any of these definitions, the result is the same.
48
+
49
+ To see how you can prove some basic theorems, check `test.py`.
50
+
@@ -0,0 +1,10 @@
1
+ tinyprove/__init__.py,sha256=KR1qJ2nlzaYHQVxnvUuzMzAgV_Sv4N9HKRbntwV9Vzk,533
2
+ tinyprove/axiom_defs.py,sha256=HGkYzcoBpUgRF5i0PJ381AZmDOU_MQoNKDTRCY3S-6k,1586
3
+ tinyprove/core.py,sha256=CXzobv8mnAVHZW8TiwdXrTVQVEGhIM4Fm7FL9_oNsqE,10770
4
+ tinyprove/inductive.py,sha256=IgFPnDLreq2lOMUFdeA-cUlGqWopdlNIkqD75Azbmrk,14228
5
+ tinyprove/ir.py,sha256=Ut33RVlt3m096HBbIPeOPXXEev54N-73-mdIMrJWKYs,1910
6
+ tinyprove/parser.py,sha256=oAmYLcgmYTkw-gf62ipEx9mK0xTZs-AorqwRu5U0RQw,4108
7
+ tinyprove-0.1.0.dist-info/METADATA,sha256=cxrT25wdkcUEm91p31UCnq79VbwiuI_-bfxcoT4f59c,1097
8
+ tinyprove-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ tinyprove-0.1.0.dist-info/top_level.txt,sha256=A7lFCZM_Mwdys_t2oaLuqYSXELBmC1eWBZWojLKOeuo,10
10
+ tinyprove-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ tinyprove