tinyprove 0.1.1__tar.gz → 0.1.2__tar.gz
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-0.1.1 → tinyprove-0.1.2}/PKG-INFO +31 -21
- {tinyprove-0.1.1 → tinyprove-0.1.2}/README.md +30 -20
- {tinyprove-0.1.1 → tinyprove-0.1.2}/pyproject.toml +1 -1
- tinyprove-0.1.2/src/tinyprove/axiom_defs.py +63 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove/inductive.py +12 -0
- tinyprove-0.1.2/src/tinyprove/parser.py +236 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove.egg-info/PKG-INFO +31 -21
- {tinyprove-0.1.1 → tinyprove-0.1.2}/test/test.py +21 -130
- tinyprove-0.1.1/src/tinyprove/axiom_defs.py +0 -62
- tinyprove-0.1.1/src/tinyprove/parser.py +0 -141
- {tinyprove-0.1.1 → tinyprove-0.1.2}/setup.cfg +0 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove/__init__.py +0 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove/core.py +0 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove/ir.py +0 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove.egg-info/SOURCES.txt +0 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove.egg-info/dependency_links.txt +0 -0
- {tinyprove-0.1.1 → tinyprove-0.1.2}/src/tinyprove.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tinyprove
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Tiny CoC-based theorem prover with inductive types
|
|
5
5
|
Project-URL: Homepage, https://github.com/pb1729/tinyprove
|
|
6
6
|
Project-URL: Repository, https://github.com/pb1729/tinyprove
|
|
@@ -63,7 +63,7 @@ The last thing you might be curious about is: "What does `Type0` mean?" It is ne
|
|
|
63
63
|
|
|
64
64
|
### Entering Symbols
|
|
65
65
|
|
|
66
|
-
You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only
|
|
66
|
+
You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. You can write `ι` using the hex code `3b9`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only three codes, go ahead and memorize them.
|
|
67
67
|
|
|
68
68
|
### Applications
|
|
69
69
|
|
|
@@ -192,7 +192,7 @@ Because definitions can depend on other definitions, we need to pass `DEFNS` whe
|
|
|
192
192
|
|
|
193
193
|
### Inductive Types
|
|
194
194
|
|
|
195
|
-
One
|
|
195
|
+
One thing we need to be able to do most of modern mathematics is to define inductive types. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
|
|
196
196
|
|
|
197
197
|
```python
|
|
198
198
|
print(DEFNS["Nat.Z"].str([]))
|
|
@@ -210,7 +210,7 @@ So `Nat.Z` is already a natural number. In fact, it's the smallest natural numbe
|
|
|
210
210
|
|
|
211
211
|
One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it means we can't just define our constructors using `Term`s. After all, the `Nat` type is not yet defined, so there's no way for us to specify that a constructor should take an argument of type `Nat`.
|
|
212
212
|
|
|
213
|
-
Tinyprove's solution to this is to
|
|
213
|
+
Tinyprove's solution to this is to have an **intermediate representation** (IR) to represent the *syntax* of tinyprove expressions. While we can think of `Term`s more or less as actual values, `IrNode`s (the datatype of our intermediate representation) just encode the *representations* of those values. An `IrNode` can be converted to an actual `Term` by calling its `.to_term([])` method. You can get the `IrNode` for an expression by using the `parse_ir()` function. Indeed, the `parse` function itself actually works by first using `parse_ir` to obtain the IR for the expression, and then calling `.to_term([])` on the result.
|
|
214
214
|
|
|
215
215
|
You can also build up the intermediate representation yourself from scratch. This is the intended clean way for you to generate tinyprove code programatically. (You could generate strings and then parse them, but it's easier to just work with the IR directly.) The basic IR datatypes are:
|
|
216
216
|
* IrSort(level)
|
|
@@ -220,26 +220,38 @@ You can also build up the intermediate representation yourself from scratch. Thi
|
|
|
220
220
|
* IrLam(param_name, input\_type, body)
|
|
221
221
|
* IrApp(fn, arg)
|
|
222
222
|
|
|
223
|
-
These are the
|
|
223
|
+
These are the kinds of `IrNode` we need to make arbitrary `Term`s, but to define inductive types we need a couple more:
|
|
224
224
|
* IrInductiveSelfRef(indices)
|
|
225
225
|
* IrConstructorDefinition(constructor_name, args, result\_indices)
|
|
226
|
+
* IrInductiveDefinition(name, sort, params, indices, constructors)
|
|
226
227
|
|
|
227
|
-
|
|
228
|
+
The way to think about this is that there's no sensible way to say that the definition of an inductive type has a *value*, but it does certainly have a syntactic representation. And therefore it can be built from `IrNode`s. If `my_inductive_def_ir` is an instance of `IrInductiveDefinition`, then you can add the inductive type it defines to your `Definitions` object as follows (note that you need to pass the `Definitions` object so that you have access to the definitions of existing constants):
|
|
228
229
|
|
|
229
230
|
```python
|
|
230
|
-
|
|
231
|
+
DEFNS.add(my_inductive_def_ir.to_definition(DEFNS))
|
|
231
232
|
```
|
|
232
233
|
|
|
233
|
-
|
|
234
|
+
If you are writing tinyprove code by hand (as opposed to programatically) and want to define an inductive type there is a syntax for that, which can then be parsed into an `IrInductiveDefinition`. You write `ι TypeName (param_1: Param1Type, param_2: Param2Type...) [index_1: Index1Type, index_2: Index2Type...] : Sort` where `Sort` is `Type0` or `Type1`, etc. After that, you write all the constructors. Each constructor is written as `| constructor_name (arg_1: Arg1Type, arg_2: Arg2Type...) => TypeName[index_1_val, index_2_val...]`. Any constructor arguments whose type is the type being defined are written with indices after the type name in brackets.
|
|
235
|
+
|
|
236
|
+
So, for example, the constructor `Nat.S` has the following tinyprove syntax:
|
|
237
|
+
|
|
238
|
+
```
|
|
239
|
+
ι Nat () [] : Type0
|
|
240
|
+
| Z () => Nat[]
|
|
241
|
+
| S (n: Nat[]) => Nat[]
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
It would be added to `DEFNS` as follows (note that we call `parse_ir`, rather than `parse`:
|
|
234
245
|
|
|
235
246
|
```python
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
247
|
+
ans.add(parse_ir("""
|
|
248
|
+
ι Nat () [] : Type0
|
|
249
|
+
| Z () => Nat[]
|
|
250
|
+
| S (n: Nat[]) => Nat[]
|
|
251
|
+
""").to_definition(ans))
|
|
241
252
|
```
|
|
242
253
|
|
|
254
|
+
|
|
243
255
|
#### induction
|
|
244
256
|
|
|
245
257
|
Let's review our definition of addition. I've expanded the code a little bit and added comments so it's easier to read.
|
|
@@ -328,16 +340,14 @@ To summarize the difference between parameters and indices in a few words:
|
|
|
328
340
|
|
|
329
341
|
Indices are one of the more difficult-to-understand parts of inductive types. Equality will be our example for this section. Here is how `Eq` is defined:
|
|
330
342
|
|
|
331
|
-
```
|
|
332
|
-
|
|
333
|
-
[
|
|
334
|
-
IrConstructorDefinition("refl", [], [IrVar("x")]),
|
|
335
|
-
], DEFNS))
|
|
343
|
+
```
|
|
344
|
+
ι Eq (A: Type0, x: A) [y: A] : Type0
|
|
345
|
+
| refl () => Eq[x]
|
|
336
346
|
```
|
|
337
347
|
|
|
338
|
-
Here we have
|
|
348
|
+
Here we have type parameters `A: Type0` and `x: A`, and we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`()` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
|
|
339
349
|
|
|
340
|
-
Each constructor has to tell us the indices that it produces. The
|
|
350
|
+
Each constructor has to tell us the indices that it produces. The `=> Eq[x]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
|
|
341
351
|
|
|
342
352
|
```python
|
|
343
353
|
# Functions of equals are equal
|
|
@@ -362,7 +372,7 @@ check(
|
|
|
362
372
|
[], DEFNS)
|
|
363
373
|
```
|
|
364
374
|
|
|
365
|
-
As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality
|
|
375
|
+
As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality using `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
|
|
366
376
|
|
|
367
377
|
### Current listing of inductive types created by get_usual_axioms()
|
|
368
378
|
|
|
@@ -53,7 +53,7 @@ The last thing you might be curious about is: "What does `Type0` mean?" It is ne
|
|
|
53
53
|
|
|
54
54
|
### Entering Symbols
|
|
55
55
|
|
|
56
|
-
You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only
|
|
56
|
+
You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. You can write `ι` using the hex code `3b9`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only three codes, go ahead and memorize them.
|
|
57
57
|
|
|
58
58
|
### Applications
|
|
59
59
|
|
|
@@ -182,7 +182,7 @@ Because definitions can depend on other definitions, we need to pass `DEFNS` whe
|
|
|
182
182
|
|
|
183
183
|
### Inductive Types
|
|
184
184
|
|
|
185
|
-
One
|
|
185
|
+
One thing we need to be able to do most of modern mathematics is to define inductive types. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
|
|
186
186
|
|
|
187
187
|
```python
|
|
188
188
|
print(DEFNS["Nat.Z"].str([]))
|
|
@@ -200,7 +200,7 @@ So `Nat.Z` is already a natural number. In fact, it's the smallest natural numbe
|
|
|
200
200
|
|
|
201
201
|
One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it means we can't just define our constructors using `Term`s. After all, the `Nat` type is not yet defined, so there's no way for us to specify that a constructor should take an argument of type `Nat`.
|
|
202
202
|
|
|
203
|
-
Tinyprove's solution to this is to
|
|
203
|
+
Tinyprove's solution to this is to have an **intermediate representation** (IR) to represent the *syntax* of tinyprove expressions. While we can think of `Term`s more or less as actual values, `IrNode`s (the datatype of our intermediate representation) just encode the *representations* of those values. An `IrNode` can be converted to an actual `Term` by calling its `.to_term([])` method. You can get the `IrNode` for an expression by using the `parse_ir()` function. Indeed, the `parse` function itself actually works by first using `parse_ir` to obtain the IR for the expression, and then calling `.to_term([])` on the result.
|
|
204
204
|
|
|
205
205
|
You can also build up the intermediate representation yourself from scratch. This is the intended clean way for you to generate tinyprove code programatically. (You could generate strings and then parse them, but it's easier to just work with the IR directly.) The basic IR datatypes are:
|
|
206
206
|
* IrSort(level)
|
|
@@ -210,26 +210,38 @@ You can also build up the intermediate representation yourself from scratch. Thi
|
|
|
210
210
|
* IrLam(param_name, input\_type, body)
|
|
211
211
|
* IrApp(fn, arg)
|
|
212
212
|
|
|
213
|
-
These are the
|
|
213
|
+
These are the kinds of `IrNode` we need to make arbitrary `Term`s, but to define inductive types we need a couple more:
|
|
214
214
|
* IrInductiveSelfRef(indices)
|
|
215
215
|
* IrConstructorDefinition(constructor_name, args, result\_indices)
|
|
216
|
+
* IrInductiveDefinition(name, sort, params, indices, constructors)
|
|
216
217
|
|
|
217
|
-
|
|
218
|
+
The way to think about this is that there's no sensible way to say that the definition of an inductive type has a *value*, but it does certainly have a syntactic representation. And therefore it can be built from `IrNode`s. If `my_inductive_def_ir` is an instance of `IrInductiveDefinition`, then you can add the inductive type it defines to your `Definitions` object as follows (note that you need to pass the `Definitions` object so that you have access to the definitions of existing constants):
|
|
218
219
|
|
|
219
220
|
```python
|
|
220
|
-
|
|
221
|
+
DEFNS.add(my_inductive_def_ir.to_definition(DEFNS))
|
|
221
222
|
```
|
|
222
223
|
|
|
223
|
-
|
|
224
|
+
If you are writing tinyprove code by hand (as opposed to programatically) and want to define an inductive type there is a syntax for that, which can then be parsed into an `IrInductiveDefinition`. You write `ι TypeName (param_1: Param1Type, param_2: Param2Type...) [index_1: Index1Type, index_2: Index2Type...] : Sort` where `Sort` is `Type0` or `Type1`, etc. After that, you write all the constructors. Each constructor is written as `| constructor_name (arg_1: Arg1Type, arg_2: Arg2Type...) => TypeName[index_1_val, index_2_val...]`. Any constructor arguments whose type is the type being defined are written with indices after the type name in brackets.
|
|
225
|
+
|
|
226
|
+
So, for example, the constructor `Nat.S` has the following tinyprove syntax:
|
|
227
|
+
|
|
228
|
+
```
|
|
229
|
+
ι Nat () [] : Type0
|
|
230
|
+
| Z () => Nat[]
|
|
231
|
+
| S (n: Nat[]) => Nat[]
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
It would be added to `DEFNS` as follows (note that we call `parse_ir`, rather than `parse`:
|
|
224
235
|
|
|
225
236
|
```python
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
237
|
+
ans.add(parse_ir("""
|
|
238
|
+
ι Nat () [] : Type0
|
|
239
|
+
| Z () => Nat[]
|
|
240
|
+
| S (n: Nat[]) => Nat[]
|
|
241
|
+
""").to_definition(ans))
|
|
231
242
|
```
|
|
232
243
|
|
|
244
|
+
|
|
233
245
|
#### induction
|
|
234
246
|
|
|
235
247
|
Let's review our definition of addition. I've expanded the code a little bit and added comments so it's easier to read.
|
|
@@ -318,16 +330,14 @@ To summarize the difference between parameters and indices in a few words:
|
|
|
318
330
|
|
|
319
331
|
Indices are one of the more difficult-to-understand parts of inductive types. Equality will be our example for this section. Here is how `Eq` is defined:
|
|
320
332
|
|
|
321
|
-
```
|
|
322
|
-
|
|
323
|
-
[
|
|
324
|
-
IrConstructorDefinition("refl", [], [IrVar("x")]),
|
|
325
|
-
], DEFNS))
|
|
333
|
+
```
|
|
334
|
+
ι Eq (A: Type0, x: A) [y: A] : Type0
|
|
335
|
+
| refl () => Eq[x]
|
|
326
336
|
```
|
|
327
337
|
|
|
328
|
-
Here we have
|
|
338
|
+
Here we have type parameters `A: Type0` and `x: A`, and we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`()` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
|
|
329
339
|
|
|
330
|
-
Each constructor has to tell us the indices that it produces. The
|
|
340
|
+
Each constructor has to tell us the indices that it produces. The `=> Eq[x]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
|
|
331
341
|
|
|
332
342
|
```python
|
|
333
343
|
# Functions of equals are equal
|
|
@@ -352,7 +362,7 @@ check(
|
|
|
352
362
|
[], DEFNS)
|
|
353
363
|
```
|
|
354
364
|
|
|
355
|
-
As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality
|
|
365
|
+
As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality using `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
|
|
356
366
|
|
|
357
367
|
### Current listing of inductive types created by get_usual_axioms()
|
|
358
368
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from .ir import *
|
|
2
|
+
from .parser import parse, parse_ir
|
|
3
|
+
from .core import Definitions, AxiomDefinition
|
|
4
|
+
from .inductive import InductiveDef, IrConstructorDefinition, IrInductiveSelfRef
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get_usual_axioms(classical:bool=True):
|
|
9
|
+
ans = Definitions()
|
|
10
|
+
|
|
11
|
+
# Constructive:
|
|
12
|
+
|
|
13
|
+
ans.add(parse_ir("""
|
|
14
|
+
ι False () [] : Type0
|
|
15
|
+
""").to_definition(ans))
|
|
16
|
+
|
|
17
|
+
ans.add(parse_ir("""
|
|
18
|
+
ι Unit () [] : Type0
|
|
19
|
+
| in () => Unit[]
|
|
20
|
+
""").to_definition(ans))
|
|
21
|
+
|
|
22
|
+
ans.add(parse_ir("""
|
|
23
|
+
ι And (A: Type0, B: Type0) [] : Type0
|
|
24
|
+
| in (a: A, b: B) => And[]
|
|
25
|
+
""").to_definition(ans))
|
|
26
|
+
|
|
27
|
+
ans.add(parse_ir("""
|
|
28
|
+
ι Or (A: Type0, B: Type0) [] : Type0
|
|
29
|
+
| inl (a: A) => Or[]
|
|
30
|
+
| inr (b: B) => Or[]
|
|
31
|
+
""").to_definition(ans))
|
|
32
|
+
|
|
33
|
+
ans.add(parse_ir("""
|
|
34
|
+
ι Eq (A: Type0, x: A) [y: A] : Type0
|
|
35
|
+
| refl () => Eq[x]
|
|
36
|
+
""").to_definition(ans))
|
|
37
|
+
|
|
38
|
+
ans.add(parse_ir("""
|
|
39
|
+
ι Exists (A: Type0, P: (Π a: A => Type0)) [] : Type0
|
|
40
|
+
| in (a: A, pa: (P a)) => Exists[]
|
|
41
|
+
""").to_definition(ans))
|
|
42
|
+
|
|
43
|
+
ans.add(parse_ir("""
|
|
44
|
+
ι Nat () [] : Type0
|
|
45
|
+
| Z () => Nat[]
|
|
46
|
+
| S (n: Nat[]) => Nat[]
|
|
47
|
+
""").to_definition(ans))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if classical: # Non-constructive:
|
|
51
|
+
ans.add(AxiomDefinition(
|
|
52
|
+
"",
|
|
53
|
+
{
|
|
54
|
+
"em": parse("Π A: Type0 => (Or A (Π a: A => False))")
|
|
55
|
+
},
|
|
56
|
+
ans))
|
|
57
|
+
|
|
58
|
+
return ans
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
@@ -76,6 +76,18 @@ class IrConstructorDefinition(IrNode):
|
|
|
76
76
|
def to_term(self, ctx_nm):
|
|
77
77
|
raise RuntimeError("Can't convert IrConstructorDefinition to Term, it is intended for creating InductiveDef's only.")
|
|
78
78
|
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class IrInductiveDefinition(IrNode):
|
|
81
|
+
name: str
|
|
82
|
+
sort: IrSort
|
|
83
|
+
params: List[Tuple[str, IrNode]]
|
|
84
|
+
indices: List[Tuple[str, IrNode]]
|
|
85
|
+
constructors:List[IrConstructorDefinition]
|
|
86
|
+
def to_term(self, ctx_nm):
|
|
87
|
+
raise RuntimeError("Can't convert IrInductiveDefinition to Term, it is intended for creating InductiveDef's only.")
|
|
88
|
+
def to_definition(self, defns: Definitions):
|
|
89
|
+
return InductiveDef(self.name, self.sort, self.params, self.indices, self.constructors, defns)
|
|
90
|
+
|
|
79
91
|
def selfref_sub(node:IrNode, selfref_ir:IrNode) -> IrNode:
|
|
80
92
|
match node:
|
|
81
93
|
case IrLam(param, A, body):
|
|
@@ -0,0 +1,236 @@
|
|
|
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
|
+
from .inductive import IrInductiveSelfRef, IrConstructorDefinition, IrInductiveDefinition
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# Tokeniser:
|
|
10
|
+
_ident_re = r"[\.A-Za-z_][\.A-Za-z0-9_]*"
|
|
11
|
+
_token_re = re.compile(
|
|
12
|
+
r"""
|
|
13
|
+
\s* # skip leading whitespace
|
|
14
|
+
( # group captures only non-whitespace
|
|
15
|
+
=>|->| # separators
|
|
16
|
+
[\[\]()\|,:λΠι]| # punctuation (unicode lambdas, etc.)
|
|
17
|
+
""" + _ident_re + """ # identifiers
|
|
18
|
+
)
|
|
19
|
+
""",
|
|
20
|
+
re.VERBOSE,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _tokenise(src: str) -> List[str]:
|
|
25
|
+
"""Return a *list* of string tokens (whitespace already stripped)."""
|
|
26
|
+
return [m.group(1) for m in _token_re.finditer(src)]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def strip_comments(src:str) -> str:
|
|
30
|
+
src = src.split("\n")
|
|
31
|
+
src = [
|
|
32
|
+
(line + "\n")[:line.find("#")]
|
|
33
|
+
for line in src
|
|
34
|
+
]
|
|
35
|
+
return "\n".join(src)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Recursive‑descent parser:
|
|
39
|
+
class Parser:
|
|
40
|
+
def __init__(self, tokens: List[str], ctx=None):
|
|
41
|
+
self.toks: List[str] = tokens
|
|
42
|
+
self.pos: int = 0
|
|
43
|
+
self.env: List[str] = [] if ctx is None else [name for name, typ in ctx]
|
|
44
|
+
self.indty_name = None
|
|
45
|
+
def _peek(self) -> str | None:
|
|
46
|
+
return self.toks[self.pos] if self.pos < len(self.toks) else None
|
|
47
|
+
def _eat(self, expected: str | None = None) -> str:
|
|
48
|
+
tok = self._peek()
|
|
49
|
+
if tok is None:
|
|
50
|
+
raise SyntaxError("unexpected end‑of‑input")
|
|
51
|
+
if expected is not None and tok != expected:
|
|
52
|
+
raise SyntaxError(f"expected '{expected}', got '{tok}'")
|
|
53
|
+
self.pos += 1
|
|
54
|
+
return tok
|
|
55
|
+
def env_push(self, name):
|
|
56
|
+
self.env.insert(0, name)
|
|
57
|
+
def env_pop(self):
|
|
58
|
+
return self.env.pop(0)
|
|
59
|
+
def parse(self) -> IrNode:
|
|
60
|
+
node = self._parse_expr()
|
|
61
|
+
if self._peek() is not None:
|
|
62
|
+
raise SyntaxError(f"found trailing tokens: {' '.join(self.toks[self.pos:])}")
|
|
63
|
+
return node
|
|
64
|
+
def _parse_expr(self) -> IrNode:
|
|
65
|
+
# Binder constructs have the lowest precedence, so look for them *first*.
|
|
66
|
+
tok = self._peek()
|
|
67
|
+
if tok == "λ":
|
|
68
|
+
return self._parse_lambda()
|
|
69
|
+
if tok == "Π":
|
|
70
|
+
return self._parse_pi()
|
|
71
|
+
if tok == "ι":
|
|
72
|
+
return self._parse_iota()
|
|
73
|
+
# Otherwise we are in application / atom land.
|
|
74
|
+
return self._parse_app()
|
|
75
|
+
def _parse_lambda(self) -> IrNode:
|
|
76
|
+
self._eat("λ")
|
|
77
|
+
name = self._eat() # identifier
|
|
78
|
+
assert re.match(_ident_re, name), f"expected a valid parameter name instead of {name}"
|
|
79
|
+
self._eat(":")
|
|
80
|
+
A = self._parse_expr()
|
|
81
|
+
self._eat("->")
|
|
82
|
+
self.env_push(name)
|
|
83
|
+
body = self._parse_expr()
|
|
84
|
+
self.env_pop()
|
|
85
|
+
return IrLam(name, A, body)
|
|
86
|
+
def _parse_pi(self) -> IrNode:
|
|
87
|
+
self._eat("Π")
|
|
88
|
+
name = self._eat()
|
|
89
|
+
assert re.match(_ident_re, name), f"expected a valid parameter name instead of {name}"
|
|
90
|
+
self._eat(":")
|
|
91
|
+
A = self._parse_expr()
|
|
92
|
+
self._eat("=>")
|
|
93
|
+
self.env_push(name)
|
|
94
|
+
B = self._parse_expr()
|
|
95
|
+
self.env_pop()
|
|
96
|
+
return IrPi(name, A, B)
|
|
97
|
+
def _parse_iota(self) -> IrNode:
|
|
98
|
+
assert self.indty_name is None, "can't create an inductive typedef inside an existing one"
|
|
99
|
+
self._eat("ι")
|
|
100
|
+
name = self._eat()
|
|
101
|
+
assert re.match(_ident_re, name), f"expected a valid inductive type name instead of {name}"
|
|
102
|
+
# get the list of parameters
|
|
103
|
+
self._eat("(")
|
|
104
|
+
params = []
|
|
105
|
+
while True:
|
|
106
|
+
if self._peek() == ")": break
|
|
107
|
+
param_name = self._eat()
|
|
108
|
+
assert re.match(_ident_re, param_name), f"expected a valid parameter name instead of {param_name}"
|
|
109
|
+
self._eat(":")
|
|
110
|
+
param_ty = self._parse_expr()
|
|
111
|
+
self.env_push(param_name)
|
|
112
|
+
params.append((param_name, param_ty))
|
|
113
|
+
if self._peek() == ")": break
|
|
114
|
+
self._eat(",")
|
|
115
|
+
self._eat(")")
|
|
116
|
+
# get the list of indices
|
|
117
|
+
self._eat("[")
|
|
118
|
+
indices = []
|
|
119
|
+
while True:
|
|
120
|
+
if self._peek() == "]": break
|
|
121
|
+
index_name = self._eat()
|
|
122
|
+
assert re.match(_ident_re, index_name), f"expected a valid index name instead of {index_name}"
|
|
123
|
+
self._eat(":")
|
|
124
|
+
index_ty = self._parse_expr()
|
|
125
|
+
self.env_push(index_name)
|
|
126
|
+
indices.append((index_name, index_ty))
|
|
127
|
+
if self._peek() == "]": break
|
|
128
|
+
self._eat(",")
|
|
129
|
+
self._eat("]")
|
|
130
|
+
# params remain part of the environment, indices don't
|
|
131
|
+
for i in range(len(indices)):
|
|
132
|
+
self.env_pop()
|
|
133
|
+
# get the overall sort of this inductive type
|
|
134
|
+
self._eat(":")
|
|
135
|
+
sort = self._parse_atom()
|
|
136
|
+
assert isinstance(sort, IrSort), "expected to be given a Type<n> for the sort of this definition"
|
|
137
|
+
# Turn on recognizing this name as recursive while parsing constructors
|
|
138
|
+
self.indty_name = name
|
|
139
|
+
# get the list of constructors
|
|
140
|
+
constructors = []
|
|
141
|
+
while True:
|
|
142
|
+
if self._peek() != "|": break
|
|
143
|
+
self._eat("|")
|
|
144
|
+
constructor_name = self._eat()
|
|
145
|
+
assert re.match(_ident_re, constructor_name), f"expected a valid constructor name instead of {constructor_name}"
|
|
146
|
+
self._eat("(")
|
|
147
|
+
args = []
|
|
148
|
+
while True:
|
|
149
|
+
if self._peek() == ")": break
|
|
150
|
+
arg_name = self._eat()
|
|
151
|
+
assert re.match(_ident_re, arg_name), f"expected a valid parameter name instead of {arg_name}"
|
|
152
|
+
self._eat(":")
|
|
153
|
+
arg_ty = self._parse_expr()
|
|
154
|
+
self.env_push(arg_name)
|
|
155
|
+
args.append((arg_name, arg_ty))
|
|
156
|
+
if self._peek() == ")": break
|
|
157
|
+
self._eat(",")
|
|
158
|
+
self._eat(")")
|
|
159
|
+
self._eat("=>")
|
|
160
|
+
constructor_return_ty = self._parse_atom()
|
|
161
|
+
assert isinstance(constructor_return_ty, IrInductiveSelfRef), "constructors must return an instance of the type"
|
|
162
|
+
# remove constructor args from the environment
|
|
163
|
+
for i in range(len(args)):
|
|
164
|
+
self.env_pop()
|
|
165
|
+
constructors.append(IrConstructorDefinition(constructor_name, args, constructor_return_ty.index_vals))
|
|
166
|
+
# remove type parameters from the environment
|
|
167
|
+
for i in range(len(params)):
|
|
168
|
+
self.env_pop()
|
|
169
|
+
# Turn off recognizing this name as recursive now that we're done
|
|
170
|
+
self.indty_name = None
|
|
171
|
+
# put everything together to make the answer
|
|
172
|
+
return IrInductiveDefinition(
|
|
173
|
+
name, sort,
|
|
174
|
+
params, indices,
|
|
175
|
+
constructors)
|
|
176
|
+
def _parse_app(self) -> IrNode:
|
|
177
|
+
node = self._parse_atom()
|
|
178
|
+
# Without parentheses, we assume application is left-to-right
|
|
179
|
+
while True:
|
|
180
|
+
nxt = self._peek()
|
|
181
|
+
# close-paren or separators break application chain. binder starts do as well.
|
|
182
|
+
if nxt is None or nxt in {")", "]", ":", ",", "=>", "->", "Π", "λ"}:
|
|
183
|
+
break
|
|
184
|
+
arg = self._parse_atom()
|
|
185
|
+
node = IrApp(node, arg)
|
|
186
|
+
return node
|
|
187
|
+
def _parse_atom(self) -> IrNode:
|
|
188
|
+
tok = self._peek()
|
|
189
|
+
if tok is None:
|
|
190
|
+
raise SyntaxError("unexpected end‑of‑input while parsing atom")
|
|
191
|
+
# Parenthesised expression
|
|
192
|
+
if tok == "(":
|
|
193
|
+
self._eat("(")
|
|
194
|
+
expr = self._parse_expr()
|
|
195
|
+
self._eat(")")
|
|
196
|
+
return expr
|
|
197
|
+
# Sorts (Type0, Type1, ...)
|
|
198
|
+
if tok[:4] == "Type":
|
|
199
|
+
level = to_positive_int(tok[4:])
|
|
200
|
+
if level is not None:
|
|
201
|
+
self._eat()
|
|
202
|
+
return IrSort(level)
|
|
203
|
+
# Identifiers (variables / constants)
|
|
204
|
+
if re.match(_ident_re, tok):
|
|
205
|
+
self._eat()
|
|
206
|
+
if tok in self.env:
|
|
207
|
+
return IrVar(tok)
|
|
208
|
+
elif tok == self.indty_name:
|
|
209
|
+
self._eat("[")
|
|
210
|
+
index_vals = []
|
|
211
|
+
while True:
|
|
212
|
+
if self._peek() == "]": break
|
|
213
|
+
index_vals.append(self._parse_expr())
|
|
214
|
+
if self._peek() == "]": break
|
|
215
|
+
self._eat(",")
|
|
216
|
+
self._eat("]")
|
|
217
|
+
return IrInductiveSelfRef(index_vals)
|
|
218
|
+
else:
|
|
219
|
+
return IrConst(tok)
|
|
220
|
+
# catchall
|
|
221
|
+
raise SyntaxError(f"unexpected token '{tok}'")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# Parsing functions:
|
|
225
|
+
|
|
226
|
+
def parse_ir(src: str, ctx=None) -> IrNode:
|
|
227
|
+
src = strip_comments(src)
|
|
228
|
+
tokens = _tokenise(src)
|
|
229
|
+
return Parser(tokens, ctx=ctx).parse()
|
|
230
|
+
|
|
231
|
+
def parse(src: str, ctx=None) -> Term:
|
|
232
|
+
ans_ir = parse_ir(src, ctx)
|
|
233
|
+
ctx_names = [] if ctx is None else [nm for nm, _ in ctx]
|
|
234
|
+
return ans_ir.to_term(ctx_names)
|
|
235
|
+
|
|
236
|
+
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tinyprove
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Tiny CoC-based theorem prover with inductive types
|
|
5
5
|
Project-URL: Homepage, https://github.com/pb1729/tinyprove
|
|
6
6
|
Project-URL: Repository, https://github.com/pb1729/tinyprove
|
|
@@ -63,7 +63,7 @@ The last thing you might be curious about is: "What does `Type0` mean?" It is ne
|
|
|
63
63
|
|
|
64
64
|
### Entering Symbols
|
|
65
65
|
|
|
66
|
-
You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only
|
|
66
|
+
You can write `Π` using the hex code `3a0`. You can write `λ` using the hex code `3bb`. You can write `ι` using the hex code `3b9`. These are worth memorizing, copy-pasting those symbols around all the time is *not* fun. Writing unicode characters depends a bit on your computer, but `Ctl-Shift-U` followed by typing the hex code and pressing `Enter` is pretty common. Seriously, it's only three codes, go ahead and memorize them.
|
|
67
67
|
|
|
68
68
|
### Applications
|
|
69
69
|
|
|
@@ -192,7 +192,7 @@ Because definitions can depend on other definitions, we need to pass `DEFNS` whe
|
|
|
192
192
|
|
|
193
193
|
### Inductive Types
|
|
194
194
|
|
|
195
|
-
One
|
|
195
|
+
One thing we need to be able to do most of modern mathematics is to define inductive types. `False`, `And`, `Or`, `Nat`, and even `Eq` (equality) are all in fact defined as inductive types! You define an inductive type by defining its paramters, indices, and constructors. The `Nat` type does not have any parameters or indices, so it makes a nice starting example. Nat has two constructors, `Nat.Z` and `Nat.S`. Let's see their types:
|
|
196
196
|
|
|
197
197
|
```python
|
|
198
198
|
print(DEFNS["Nat.Z"].str([]))
|
|
@@ -210,7 +210,7 @@ So `Nat.Z` is already a natural number. In fact, it's the smallest natural numbe
|
|
|
210
210
|
|
|
211
211
|
One thing that's interesting here is that the type `Nat` is *recursive*. Some of its constructors (i.e. `Nat.S`) need arguments that are themselves of type `Nat`. This kind of recursion is very powerful, but it means we can't just define our constructors using `Term`s. After all, the `Nat` type is not yet defined, so there's no way for us to specify that a constructor should take an argument of type `Nat`.
|
|
212
212
|
|
|
213
|
-
Tinyprove's solution to this is to
|
|
213
|
+
Tinyprove's solution to this is to have an **intermediate representation** (IR) to represent the *syntax* of tinyprove expressions. While we can think of `Term`s more or less as actual values, `IrNode`s (the datatype of our intermediate representation) just encode the *representations* of those values. An `IrNode` can be converted to an actual `Term` by calling its `.to_term([])` method. You can get the `IrNode` for an expression by using the `parse_ir()` function. Indeed, the `parse` function itself actually works by first using `parse_ir` to obtain the IR for the expression, and then calling `.to_term([])` on the result.
|
|
214
214
|
|
|
215
215
|
You can also build up the intermediate representation yourself from scratch. This is the intended clean way for you to generate tinyprove code programatically. (You could generate strings and then parse them, but it's easier to just work with the IR directly.) The basic IR datatypes are:
|
|
216
216
|
* IrSort(level)
|
|
@@ -220,26 +220,38 @@ You can also build up the intermediate representation yourself from scratch. Thi
|
|
|
220
220
|
* IrLam(param_name, input\_type, body)
|
|
221
221
|
* IrApp(fn, arg)
|
|
222
222
|
|
|
223
|
-
These are the
|
|
223
|
+
These are the kinds of `IrNode` we need to make arbitrary `Term`s, but to define inductive types we need a couple more:
|
|
224
224
|
* IrInductiveSelfRef(indices)
|
|
225
225
|
* IrConstructorDefinition(constructor_name, args, result\_indices)
|
|
226
|
+
* IrInductiveDefinition(name, sort, params, indices, constructors)
|
|
226
227
|
|
|
227
|
-
|
|
228
|
+
The way to think about this is that there's no sensible way to say that the definition of an inductive type has a *value*, but it does certainly have a syntactic representation. And therefore it can be built from `IrNode`s. If `my_inductive_def_ir` is an instance of `IrInductiveDefinition`, then you can add the inductive type it defines to your `Definitions` object as follows (note that you need to pass the `Definitions` object so that you have access to the definitions of existing constants):
|
|
228
229
|
|
|
229
230
|
```python
|
|
230
|
-
|
|
231
|
+
DEFNS.add(my_inductive_def_ir.to_definition(DEFNS))
|
|
231
232
|
```
|
|
232
233
|
|
|
233
|
-
|
|
234
|
+
If you are writing tinyprove code by hand (as opposed to programatically) and want to define an inductive type there is a syntax for that, which can then be parsed into an `IrInductiveDefinition`. You write `ι TypeName (param_1: Param1Type, param_2: Param2Type...) [index_1: Index1Type, index_2: Index2Type...] : Sort` where `Sort` is `Type0` or `Type1`, etc. After that, you write all the constructors. Each constructor is written as `| constructor_name (arg_1: Arg1Type, arg_2: Arg2Type...) => TypeName[index_1_val, index_2_val...]`. Any constructor arguments whose type is the type being defined are written with indices after the type name in brackets.
|
|
235
|
+
|
|
236
|
+
So, for example, the constructor `Nat.S` has the following tinyprove syntax:
|
|
237
|
+
|
|
238
|
+
```
|
|
239
|
+
ι Nat () [] : Type0
|
|
240
|
+
| Z () => Nat[]
|
|
241
|
+
| S (n: Nat[]) => Nat[]
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
It would be added to `DEFNS` as follows (note that we call `parse_ir`, rather than `parse`:
|
|
234
245
|
|
|
235
246
|
```python
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
247
|
+
ans.add(parse_ir("""
|
|
248
|
+
ι Nat () [] : Type0
|
|
249
|
+
| Z () => Nat[]
|
|
250
|
+
| S (n: Nat[]) => Nat[]
|
|
251
|
+
""").to_definition(ans))
|
|
241
252
|
```
|
|
242
253
|
|
|
254
|
+
|
|
243
255
|
#### induction
|
|
244
256
|
|
|
245
257
|
Let's review our definition of addition. I've expanded the code a little bit and added comments so it's easier to read.
|
|
@@ -328,16 +340,14 @@ To summarize the difference between parameters and indices in a few words:
|
|
|
328
340
|
|
|
329
341
|
Indices are one of the more difficult-to-understand parts of inductive types. Equality will be our example for this section. Here is how `Eq` is defined:
|
|
330
342
|
|
|
331
|
-
```
|
|
332
|
-
|
|
333
|
-
[
|
|
334
|
-
IrConstructorDefinition("refl", [], [IrVar("x")]),
|
|
335
|
-
], DEFNS))
|
|
343
|
+
```
|
|
344
|
+
ι Eq (A: Type0, x: A) [y: A] : Type0
|
|
345
|
+
| refl () => Eq[x]
|
|
336
346
|
```
|
|
337
347
|
|
|
338
|
-
Here we have
|
|
348
|
+
Here we have type parameters `A: Type0` and `x: A`, and we have one index `y: A`. `Eq` has only one constructor, `Eq.refl`. This constructor takes no arguments (`()` in the constructor definition), but remember that we still have to tell it the type parameters, so a call to `Eq.refl` would look something like `(Eq.refl Nat Nat.Z)`, which produces a proof of type `(Eq Nat Nat.Z Nat.Z)`, aka "0 = 0".
|
|
339
349
|
|
|
340
|
-
Each constructor has to tell us the indices that it produces. The
|
|
350
|
+
Each constructor has to tell us the indices that it produces. The `=> Eq[x]` says that the `Eq.refl` constructor produces `x` as the index of the resulting equaltiy type. Just like all the other inductive types, `Eq.ind.0` is a thing, and it lets us use proofs of equalities to construct various other things. Here's an example of how we'd use it:
|
|
341
351
|
|
|
342
352
|
```python
|
|
343
353
|
# Functions of equals are equal
|
|
@@ -362,7 +372,7 @@ check(
|
|
|
362
372
|
[], DEFNS)
|
|
363
373
|
```
|
|
364
374
|
|
|
365
|
-
As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality
|
|
375
|
+
As an exercise, can you prove the three standard properties (reflexivity, symmetry, transitivity) of equality using `Eq.ind.0`? (Hint: as you may be able to guess by the looking at the name of `Eq`'s only constructor, one of these proofs is very easy.)
|
|
366
376
|
|
|
367
377
|
### Current listing of inductive types created by get_usual_axioms()
|
|
368
378
|
|
|
@@ -150,31 +150,25 @@ print(DEFNS.defs["eq_1_1"].type.str([]))
|
|
|
150
150
|
print(DEFNS.defs["eq_2_2"].type.str([]))
|
|
151
151
|
|
|
152
152
|
|
|
153
|
-
DEFNS.add(
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
[IrApp(IrConst("Nat.S"), IrVar("l"))]),
|
|
159
|
-
], DEFNS))
|
|
153
|
+
DEFNS.add(parse_ir("""
|
|
154
|
+
ι Vec (A: Type0) [l: Nat] : Type0
|
|
155
|
+
| empty () => Vec[Nat.Z]
|
|
156
|
+
| append (l: Nat, a: A, rest: Vec[l]) => Vec[(Nat.S l)]
|
|
157
|
+
""").to_definition(DEFNS))
|
|
160
158
|
|
|
161
159
|
# bullshit inductive type that is both recursive and has multiple indices for testing purposes
|
|
162
|
-
DEFNS.add(
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
[
|
|
175
|
-
IrConstructorDefinition("empty", [("nn", IrConst("Nat"))], [IrVar("nn"), IrConst("Nat.Z")]),
|
|
176
|
-
IrConstructorDefinition("append", [("nn", IrConst("Nat")), ("mm", IrConst("Nat")), ("row", IrApp(IrApp(IrConst("Vec"), IrVar("A")), IrVar("nn"))), ("rest", IrInductiveSelfRef([IrVar("nn"), IrVar("mm")]))], [IrVar("nn"), IrApp(IrConst("Nat.S"), IrVar("mm"))])
|
|
177
|
-
], DEFNS))
|
|
160
|
+
DEFNS.add(parse_ir("""
|
|
161
|
+
ι Blorb () [n: Nat, m: Nat] : Type0
|
|
162
|
+
| base () => Blorb[Nat.Z, Nat.Z]
|
|
163
|
+
| inl (n: Nat, m: Nat, child: Blorb[n, m]) => Blorb[(Nat.S n), m]
|
|
164
|
+
| inr (n: Nat, m: Nat, child: Blorb[n, m]) => Blorb[n, (Nat.S m)]
|
|
165
|
+
""").to_definition(DEFNS))
|
|
166
|
+
|
|
167
|
+
DEFNS.add(parse_ir("""
|
|
168
|
+
ι Mat (A: Type0) [n: Nat, m: Nat] : Type0
|
|
169
|
+
| empty (n: Nat) => Mat[n, Nat.Z]
|
|
170
|
+
| append (n: Nat, m: Nat, row: (Vec A n), rest: Mat[n, m]) => Mat[n, (Nat.S m)]
|
|
171
|
+
""").to_definition(DEFNS))
|
|
178
172
|
|
|
179
173
|
|
|
180
174
|
DEFNS.add(ConstDefinition("inc_vec",
|
|
@@ -757,113 +751,6 @@ test("add left cancellation",
|
|
|
757
751
|
|
|
758
752
|
|
|
759
753
|
|
|
760
|
-
# ----------------------------------
|
|
761
|
-
# Decently hard challenge: Cantor-Schroeder-Bernstein theorem
|
|
762
|
-
# ----------------------------------
|
|
763
|
-
|
|
764
|
-
# Logic Utilities
|
|
765
|
-
|
|
766
|
-
DEFNS.add(ConstDefinition("Not",
|
|
767
|
-
parse("λ A: Type0 -> Π a: A => False"),
|
|
768
|
-
DEFNS))
|
|
769
|
-
|
|
770
|
-
DEFNS.add(ConstDefinition("exfalso",
|
|
771
|
-
parse("λ A: Type0 -> λ false: False -> (False.ind.0 (λ _: False -> A) false)"),
|
|
772
|
-
DEFNS))
|
|
773
|
-
|
|
774
|
-
# And projections
|
|
775
|
-
DEFNS.add(ConstDefinition("And_l",
|
|
776
|
-
parse(
|
|
777
|
-
"λ A: Type0 -> λ B: Type0 -> λ p: (And A B) -> "
|
|
778
|
-
"(And.ind.0 A B "
|
|
779
|
-
"(λ _: (And A B) -> A) "
|
|
780
|
-
"(λ a: A -> λ b: B -> a) "
|
|
781
|
-
"p)"
|
|
782
|
-
),
|
|
783
|
-
DEFNS))
|
|
784
|
-
|
|
785
|
-
DEFNS.add(ConstDefinition("And_r",
|
|
786
|
-
parse(
|
|
787
|
-
"λ A: Type0 -> λ B: Type0 -> λ p: (And A B) -> "
|
|
788
|
-
"(And.ind.0 A B "
|
|
789
|
-
"(λ _: (And A B) -> B) "
|
|
790
|
-
"(λ a: A -> λ b: B -> b) "
|
|
791
|
-
"p)"
|
|
792
|
-
),
|
|
793
|
-
DEFNS))
|
|
794
|
-
|
|
795
|
-
# Or eliminator (non-dependent convenience)
|
|
796
|
-
DEFNS.add(ConstDefinition("or_elim",
|
|
797
|
-
parse(
|
|
798
|
-
"λ A: Type0 -> λ B: Type0 -> λ C: Type0 -> "
|
|
799
|
-
"λ x: (Or A B) -> "
|
|
800
|
-
"λ f: (Π a: A => C) -> "
|
|
801
|
-
"λ g: (Π b: B => C) -> "
|
|
802
|
-
"(Or.ind.0 A B "
|
|
803
|
-
"(λ _: (Or A B) -> C) "
|
|
804
|
-
"f "
|
|
805
|
-
"g "
|
|
806
|
-
"x)"
|
|
807
|
-
),
|
|
808
|
-
DEFNS))
|
|
809
|
-
|
|
810
|
-
# Choose witness from Exists
|
|
811
|
-
DEFNS.add(ConstDefinition("choose",
|
|
812
|
-
parse(
|
|
813
|
-
"λ A: Type0 -> λ P: (Π a: A => Type0) -> "
|
|
814
|
-
"λ e: (Exists A P) -> "
|
|
815
|
-
"(Exists.ind.0 A P "
|
|
816
|
-
"(λ _: (Exists A P) -> A) "
|
|
817
|
-
"(λ a: A -> λ pa: (P a) -> a) "
|
|
818
|
-
"e)"
|
|
819
|
-
),
|
|
820
|
-
DEFNS))
|
|
821
|
-
|
|
822
|
-
DEFNS.add(ConstDefinition("choose_pr",
|
|
823
|
-
parse(
|
|
824
|
-
"λ A: Type0 -> λ P: (Π a: A => Type0) -> "
|
|
825
|
-
"λ e: (Exists A P) -> "
|
|
826
|
-
"(Exists.ind.0 A P "
|
|
827
|
-
"(λ e2: (Exists A P) -> (P (choose A P e2))) "
|
|
828
|
-
"(λ a: A -> λ pa: (P a) -> pa) "
|
|
829
|
-
"e)"
|
|
830
|
-
),
|
|
831
|
-
DEFNS))
|
|
832
|
-
|
|
833
|
-
# Double-negation elimination from excluded middle:
|
|
834
|
-
# dne P : Not(Not P) -> P
|
|
835
|
-
DEFNS.add(ConstDefinition("dne",
|
|
836
|
-
parse(
|
|
837
|
-
"λ P: Type0 -> λ nnP: (Not (Not P)) -> "
|
|
838
|
-
"(Or.ind.0 P (Not P) "
|
|
839
|
-
"(λ _: (Or P (Not P)) -> P) "
|
|
840
|
-
"(λ p: P -> p) "
|
|
841
|
-
"(λ nP: (Not P) -> (exfalso P (nnP nP))) "
|
|
842
|
-
"(.em P))"
|
|
843
|
-
),
|
|
844
|
-
DEFNS))
|
|
845
|
-
|
|
846
|
-
'''
|
|
847
|
-
DEFNS.add(ConstDefinition("bijection",
|
|
848
|
-
parse("""
|
|
849
|
-
λ A: Type0 -> λ B: Type0 ->
|
|
850
|
-
(Exists (Π a: A => B) (λ h: (Π a: A => B) -> # there exists h: A => B such that:
|
|
851
|
-
(Exists (Π b: B => A) (λ k: (Π b: B => A) -> # there exists k: B => A such that:
|
|
852
|
-
... # TODO
|
|
853
|
-
))
|
|
854
|
-
))
|
|
855
|
-
"""),
|
|
856
|
-
DEFNS))
|
|
857
|
-
'''
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
754
|
# ----------------------------------
|
|
868
755
|
# Show all current definitions
|
|
869
756
|
# ----------------------------------
|
|
@@ -895,4 +782,8 @@ for name in DEFNS.defs:
|
|
|
895
782
|
|
|
896
783
|
|
|
897
784
|
|
|
785
|
+
# TODO: add negative tests!!!!!
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
|
|
898
789
|
|
|
@@ -1,62 +0,0 @@
|
|
|
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
|
-
|
|
@@ -1,141 +0,0 @@
|
|
|
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
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|