tinyprove 0.1.2__tar.gz → 0.1.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyprove
3
- Version: 0.1.2
3
+ Version: 0.1.4
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,12 @@ 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`. 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.
66
+ Tinyprove syntax uses four greek letters as special symbols. Here are their unicode codes:
67
+ * `Π` has code `3a0`
68
+ * `λ` has code `3bb`
69
+ * `δ` has code `3b4`
70
+ * `ι` has code `3b9`
71
+ These are worth memorizing, copy-pasting those symbols around all the time is no 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 four codes, go ahead and memorize them.
67
72
 
68
73
  ### Applications
69
74
 
@@ -165,13 +170,16 @@ which is exactly what we expected.
165
170
 
166
171
  ### Making Definitions
167
172
 
168
- You can make your own definitions and add them to `DEFNS`. This is done by making a `ConstDefinition` and then feeding it to `DEFNS.add()`:
173
+ You can make your own definitions and add them to `DEFNS`. This is done with the `extend_definitions` function. This function will *update* the definitions object passed as its first argument to add (in order) each definition in the list of definitions passed as its second argument. Here's how we'd define addition with this system:
169
174
 
170
175
  ```python
171
176
  # define addition
172
- DEFNS.add(ConstDefinition("add",
173
- parse("λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)"),
174
- DEFNS))
177
+ extend_definitions(DEFNS, [
178
+ """
179
+ δ add =
180
+ λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)
181
+ """
182
+ ])
175
183
  ```
176
184
 
177
185
  I'll explain what `Nat.ind.0` means later, but we can check what the type of the `add` function is by running:
@@ -188,7 +196,9 @@ which prints
188
196
 
189
197
  I.e. `add` takes two `Nat`s and produces a `Nat`, as expected.
190
198
 
191
- Because definitions can depend on other definitions, we need to pass `DEFNS` when creating a new definition. For example, `add` depended on having an existing `Nat` definition. So to make a ConstDefinition, we need to pass a unique name for the definition, a defined value, and our `Definitions` object.
199
+ The symbol `δ` (for "define") is used like `let` or `const` in javascript to tell the language that we're making defining a constant. Then the constant name follows. Optionally, we can put the expected type of the constant next using `:` to denote type annotation. If we do this, tinyprove will typecheck the constant to ensure it has the type we specified. Finally, we put `=` followed by the actual value of the constant. We could have defined addition using either `δ add = ...` or `δ add: (Π a: Nat => Π b: Nat => Nat) = ...`.
200
+
201
+ Note that extend_definitions has parsing built in, and so definitions are given as strings of tinyprove code. Because definitions are added in order, it's possible for definitions to refer to previous definitions in the passed list.
192
202
 
193
203
  ### Inductive Types
194
204
 
@@ -208,30 +218,9 @@ Nat
208
218
 
209
219
  So `Nat.Z` is already a natural number. In fact, it's the smallest natural number, zero. `Nat.S` is the successor function, it accepts a natural number `n` and produces the natural number `n + 1`. Every natural number except zero can be written as the successor of some other natural number. So the actual representation of the number 3 is `(Nat.S (Nat.S (Nat.S Nat.Z)))`.
210
220
 
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
-
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
-
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
- * IrSort(level)
217
- * IrConst(name)
218
- * IrVar(name)
219
- * IrPi(param_name, input\_type, output\_type)
220
- * IrLam(param_name, input\_type, body)
221
- * IrApp(fn, arg)
222
-
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
- * IrInductiveSelfRef(indices)
225
- * IrConstructorDefinition(constructor_name, args, result\_indices)
226
- * IrInductiveDefinition(name, sort, params, indices, constructors)
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):
229
-
230
- ```python
231
- DEFNS.add(my_inductive_def_ir.to_definition(DEFNS))
232
- ```
221
+ 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 makes writing down inductive types slightly complicated. Inductive types can't simply be written as `Term`s in the existing language, so we can't define them as constants using the `δ ...` syntax described above. Instead, we have a special `ι` syntax for creating new inductive types.
233
222
 
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.
223
+ An inductive type definition is written: `ι 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
224
 
236
225
  So, for example, the constructor `Nat.S` has the following tinyprove syntax:
237
226
 
@@ -241,14 +230,16 @@ So, for example, the constructor `Nat.S` has the following tinyprove syntax:
241
230
  | S (n: Nat[]) => Nat[]
242
231
  ```
243
232
 
244
- It would be added to `DEFNS` as follows (note that we call `parse_ir`, rather than `parse`:
233
+ It would be added to `DEFNS` using `extend_definitions`, the same as a regular definition:
245
234
 
246
235
  ```python
247
- ans.add(parse_ir("""
236
+ extend_definitions(DEFNS, [
237
+ """
248
238
  ι Nat () [] : Type0
249
239
  | Z () => Nat[]
250
240
  | S (n: Nat[]) => Nat[]
251
- """).to_definition(ans))
241
+ """
242
+ ])
252
243
  ```
253
244
 
254
245
 
@@ -259,22 +250,23 @@ Let's review our definition of addition. I've expanded the code a little bit and
259
250
  Here's the intuitive explanation of how it works: If we want to define addition, one very simple way of doing it is to say that `0 + b = b` and `(n + 1) + b = (n + b) + 1`. Since we already have a function `Nat.S` for adding 1, we can use these rules to make a function that allows us to add any two numbers:
260
251
 
261
252
  ```python
262
- DEFNS.add(ConstDefinition("add",
263
- parse("""
264
- λ a: Nat -> λ b: Nat ->
265
- (Nat.ind.0
266
- (λ _: Nat -> Nat) # motive: our return type is simply Nat
267
- # case where a = 0:
268
- b
269
- # case where a = n + 1:
270
- (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
271
- a # match on a
272
- )
273
- """),
274
- DEFNS))
275
- ```
276
-
277
- We have to use recursion though. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
253
+ extend_definitions(DEFNS, [
254
+ """
255
+ δ add =
256
+ λ a: Nat -> λ b: Nat ->
257
+ (Nat.ind.0
258
+ (λ _: Nat -> Nat) # motive: our return type is simply Nat
259
+ # case where a = 0:
260
+ b
261
+ # case where a = n + 1:
262
+ (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
263
+ a # match on a
264
+ )
265
+ """
266
+ ])
267
+ ```
268
+
269
+ We have to use recursion here. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
278
270
 
279
271
  What `Nat.ind.0` does is to provide a formal way of making a recursive function for the type `Nat`. It first asks for a motive, a function that gives us the type we want this whole recursion process to return. Then we need to provide cases to handle the constructors one by one. First we handle the `Nat.Z` constructor, then the `Nat.S` one. If a constructor accepts a recursive argument (i.e. one of its args is an inductive self-ref) then that case function gets passed a bonus argument: the result of recursively calling our `Nat.ind.0` expression on that argument.
280
272
 
@@ -424,9 +416,7 @@ Nat.ind.0 (Π @motive: (Π @instance: Nat => Type0) => (Π @case_
424
416
 
425
417
  ### Conclusion
426
418
 
427
- You now have all the basic knowledge you need to start proving things. When writing proofs, you should be making new `ConstDefinition`s all the time, new `InductiveDef`s every once in a while, and new `AxiomDefinition`s only if you really know what you're doing.
428
-
429
- If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
419
+ You now have all the basic knowledge you need to start proving things. If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
430
420
 
431
421
  If you manage to prove `False` without adding any new `AxiomDefinition`s, that means there's something seriously wrong and you should submit an issue the includes the offending tinyprove code. Actually, if you find *any* bugs, please submit an issue. I'll also consider QoL improvements or feature requests, but keep in mind that I am very lazy.
432
422
 
@@ -53,7 +53,12 @@ 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`. 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.
56
+ Tinyprove syntax uses four greek letters as special symbols. Here are their unicode codes:
57
+ * `Π` has code `3a0`
58
+ * `λ` has code `3bb`
59
+ * `δ` has code `3b4`
60
+ * `ι` has code `3b9`
61
+ These are worth memorizing, copy-pasting those symbols around all the time is no 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 four codes, go ahead and memorize them.
57
62
 
58
63
  ### Applications
59
64
 
@@ -155,13 +160,16 @@ which is exactly what we expected.
155
160
 
156
161
  ### Making Definitions
157
162
 
158
- You can make your own definitions and add them to `DEFNS`. This is done by making a `ConstDefinition` and then feeding it to `DEFNS.add()`:
163
+ You can make your own definitions and add them to `DEFNS`. This is done with the `extend_definitions` function. This function will *update* the definitions object passed as its first argument to add (in order) each definition in the list of definitions passed as its second argument. Here's how we'd define addition with this system:
159
164
 
160
165
  ```python
161
166
  # define addition
162
- DEFNS.add(ConstDefinition("add",
163
- parse("λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)"),
164
- DEFNS))
167
+ extend_definitions(DEFNS, [
168
+ """
169
+ δ add =
170
+ λ a: Nat -> λ b: Nat -> (Nat.ind.0 (λ _: Nat -> Nat) b (λ n: Nat -> λ r: Nat -> (Nat.S r)) a)
171
+ """
172
+ ])
165
173
  ```
166
174
 
167
175
  I'll explain what `Nat.ind.0` means later, but we can check what the type of the `add` function is by running:
@@ -178,7 +186,9 @@ which prints
178
186
 
179
187
  I.e. `add` takes two `Nat`s and produces a `Nat`, as expected.
180
188
 
181
- Because definitions can depend on other definitions, we need to pass `DEFNS` when creating a new definition. For example, `add` depended on having an existing `Nat` definition. So to make a ConstDefinition, we need to pass a unique name for the definition, a defined value, and our `Definitions` object.
189
+ The symbol `δ` (for "define") is used like `let` or `const` in javascript to tell the language that we're making defining a constant. Then the constant name follows. Optionally, we can put the expected type of the constant next using `:` to denote type annotation. If we do this, tinyprove will typecheck the constant to ensure it has the type we specified. Finally, we put `=` followed by the actual value of the constant. We could have defined addition using either `δ add = ...` or `δ add: (Π a: Nat => Π b: Nat => Nat) = ...`.
190
+
191
+ Note that extend_definitions has parsing built in, and so definitions are given as strings of tinyprove code. Because definitions are added in order, it's possible for definitions to refer to previous definitions in the passed list.
182
192
 
183
193
  ### Inductive Types
184
194
 
@@ -198,30 +208,9 @@ Nat
198
208
 
199
209
  So `Nat.Z` is already a natural number. In fact, it's the smallest natural number, zero. `Nat.S` is the successor function, it accepts a natural number `n` and produces the natural number `n + 1`. Every natural number except zero can be written as the successor of some other natural number. So the actual representation of the number 3 is `(Nat.S (Nat.S (Nat.S Nat.Z)))`.
200
210
 
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
-
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
-
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
- * IrSort(level)
207
- * IrConst(name)
208
- * IrVar(name)
209
- * IrPi(param_name, input\_type, output\_type)
210
- * IrLam(param_name, input\_type, body)
211
- * IrApp(fn, arg)
212
-
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
- * IrInductiveSelfRef(indices)
215
- * IrConstructorDefinition(constructor_name, args, result\_indices)
216
- * IrInductiveDefinition(name, sort, params, indices, constructors)
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):
219
-
220
- ```python
221
- DEFNS.add(my_inductive_def_ir.to_definition(DEFNS))
222
- ```
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 makes writing down inductive types slightly complicated. Inductive types can't simply be written as `Term`s in the existing language, so we can't define them as constants using the `δ ...` syntax described above. Instead, we have a special `ι` syntax for creating new inductive types.
223
212
 
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.
213
+ An inductive type definition is written: `ι 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
214
 
226
215
  So, for example, the constructor `Nat.S` has the following tinyprove syntax:
227
216
 
@@ -231,14 +220,16 @@ So, for example, the constructor `Nat.S` has the following tinyprove syntax:
231
220
  | S (n: Nat[]) => Nat[]
232
221
  ```
233
222
 
234
- It would be added to `DEFNS` as follows (note that we call `parse_ir`, rather than `parse`:
223
+ It would be added to `DEFNS` using `extend_definitions`, the same as a regular definition:
235
224
 
236
225
  ```python
237
- ans.add(parse_ir("""
226
+ extend_definitions(DEFNS, [
227
+ """
238
228
  ι Nat () [] : Type0
239
229
  | Z () => Nat[]
240
230
  | S (n: Nat[]) => Nat[]
241
- """).to_definition(ans))
231
+ """
232
+ ])
242
233
  ```
243
234
 
244
235
 
@@ -249,22 +240,23 @@ Let's review our definition of addition. I've expanded the code a little bit and
249
240
  Here's the intuitive explanation of how it works: If we want to define addition, one very simple way of doing it is to say that `0 + b = b` and `(n + 1) + b = (n + b) + 1`. Since we already have a function `Nat.S` for adding 1, we can use these rules to make a function that allows us to add any two numbers:
250
241
 
251
242
  ```python
252
- DEFNS.add(ConstDefinition("add",
253
- parse("""
254
- λ a: Nat -> λ b: Nat ->
255
- (Nat.ind.0
256
- (λ _: Nat -> Nat) # motive: our return type is simply Nat
257
- # case where a = 0:
258
- b
259
- # case where a = n + 1:
260
- (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
261
- a # match on a
262
- )
263
- """),
264
- DEFNS))
265
- ```
266
-
267
- We have to use recursion though. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
243
+ extend_definitions(DEFNS, [
244
+ """
245
+ δ add =
246
+ λ a: Nat -> λ b: Nat ->
247
+ (Nat.ind.0
248
+ (λ _: Nat -> Nat) # motive: our return type is simply Nat
249
+ # case where a = 0:
250
+ b
251
+ # case where a = n + 1:
252
+ (λ n: Nat -> λ r: Nat -> (Nat.S r)) # in this line, r is the recursive result, (n + b)
253
+ a # match on a
254
+ )
255
+ """
256
+ ])
257
+ ```
258
+
259
+ We have to use recursion here. In the case where `a = n + 1`, we now have to add `n + b`. Thus, the case functions are applied recursively all the way until we reach zero. Then `b` is returned without a recursive call. It's a nice fact about inductive types that recursion on such a type *always terminates*. Maybe it's not obvious that this could be true, but it arises from the fact that instances of the type have to be built up in order. We start out with `Nat.Z`, and can only reach any higher number by applying `Nat.S` repeatedly. In the C programming language, you're allowed to make a struct with a pointer in it that points to itself. But this is not allowed in a proof language. Anything you feed to a constructor must *already fully exist*, and it can't be modified after the fact either. And because things must have been built by a finite process, we must be able to disassemble them by a finite process too.
268
260
 
269
261
  What `Nat.ind.0` does is to provide a formal way of making a recursive function for the type `Nat`. It first asks for a motive, a function that gives us the type we want this whole recursion process to return. Then we need to provide cases to handle the constructors one by one. First we handle the `Nat.Z` constructor, then the `Nat.S` one. If a constructor accepts a recursive argument (i.e. one of its args is an inductive self-ref) then that case function gets passed a bonus argument: the result of recursively calling our `Nat.ind.0` expression on that argument.
270
262
 
@@ -414,9 +406,7 @@ Nat.ind.0 (Π @motive: (Π @instance: Nat => Type0) => (Π @case_
414
406
 
415
407
  ### Conclusion
416
408
 
417
- You now have all the basic knowledge you need to start proving things. When writing proofs, you should be making new `ConstDefinition`s all the time, new `InductiveDef`s every once in a while, and new `AxiomDefinition`s only if you really know what you're doing.
418
-
419
- If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
409
+ You now have all the basic knowledge you need to start proving things. If you get stuck, ask ChatGPT or another language model. But feed it this document first so it knows what's going on.
420
410
 
421
411
  If you manage to prove `False` without adding any new `AxiomDefinition`s, that means there's something seriously wrong and you should submit an issue the includes the offending tinyprove code. Actually, if you find *any* bugs, please submit an issue. I'll also consider QoL improvements or feature requests, but keep in mind that I am very lazy.
422
412
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tinyprove"
7
- version = "0.1.2"
7
+ version = "0.1.4"
8
8
  description = "Tiny CoC-based theorem prover with inductive types"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -5,7 +5,7 @@ from .core import (
5
5
  infer, check,
6
6
  )
7
7
  from .ir import (
8
- IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp,
8
+ IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp, IrConstantDefinition
9
9
  )
10
10
  from .parser import (
11
11
  parse_ir, parse,
@@ -15,7 +15,7 @@ from .inductive import (
15
15
  InductiveDef, IrConstructorDefinition, IrInductiveSelfRef,
16
16
  )
17
17
  from .axiom_defs import (
18
- get_usual_axioms,
18
+ extend_definitions, get_usual_axioms,
19
19
  )
20
20
 
21
21
 
@@ -0,0 +1,64 @@
1
+ from typing import List
2
+
3
+ from .ir import *
4
+ from .parser import parse, parse_ir
5
+ from .core import Definitions, AxiomDefinition
6
+ from .inductive import InductiveDef, IrConstructorDefinition, IrInductiveSelfRef
7
+
8
+
9
+
10
+ def extend_definitions(defns:Definitions, src:List[str]):
11
+ """ MUTATES defns by adding all definitions from src """
12
+ for defn_str in src:
13
+ defn_ir = parse_ir(defn_str)
14
+ if hasattr(defn_ir, "to_definition"):
15
+ defns.add(defn_ir.to_definition(defns))
16
+ else:
17
+ raise RuntimeError(f"The following code does not constitute a definition:\n{defn_str}")
18
+
19
+
20
+ def get_usual_axioms(classical:bool=True) -> Definitions:
21
+ ans = Definitions()
22
+
23
+ # Constructive:
24
+ extend_definitions(ans, [
25
+ """
26
+ ι False () [] : Type0
27
+ """, """
28
+ ι Unit () [] : Type0
29
+ | in () => Unit[]
30
+ """, """
31
+ ι And (A: Type0, B: Type0) [] : Type0
32
+ | in (a: A, b: B) => And[]
33
+ """, """
34
+ ι Or (A: Type0, B: Type0) [] : Type0
35
+ | inl (a: A) => Or[]
36
+ | inr (b: B) => Or[]
37
+ """, """
38
+ ι Eq (A: Type0, x: A) [y: A] : Type0
39
+ | refl () => Eq[x]
40
+ """, """
41
+ ι Exists (A: Type0, P: (Π a: A => Type0)) [] : Type0
42
+ | in (a: A, pa: (P a)) => Exists[]
43
+ """, """
44
+ ι Nat () [] : Type0
45
+ | Z () => Nat[]
46
+ | S (n: Nat[]) => Nat[]
47
+ """
48
+ ])
49
+
50
+ # Non-constructive:
51
+ if classical:
52
+ ans.add(AxiomDefinition(
53
+ "",
54
+ {
55
+ "em": parse("Π A: Type0 => (Or A (Π a: A => False))")
56
+ },
57
+ ans))
58
+
59
+ return ans
60
+
61
+
62
+
63
+
64
+
@@ -188,22 +188,30 @@ def whnf(term:Term, defns:Definitions) -> Term:
188
188
  return ans
189
189
 
190
190
 
191
- def conv(t1:Term, t2:Term, defns:Definitions) -> bool:
191
+ def conv(t1:Term, t2:Term, defns:Definitions, accept_assignable:bool=False) -> bool:
192
+ """ Check structural equality for two terms. The check is exact and symmetric by
193
+ default, if accept_assignable is set, we instead check if t1 is assignable to t2. """
192
194
  t1 = whnf(t1, defns)
193
195
  t2 = whnf(t2, defns)
194
196
  match t1, t2:
195
197
  case Sort(l1), Sort(l2):
196
- return l1 == l2
198
+ return l1 == l2 or (accept_assignable and l1 <= l2)
197
199
  case Var(depth1), Var(depth2):
198
200
  return depth1 == depth2
199
201
  case Const(name1), Const(name2):
200
202
  return name1 == name2
201
203
  case App(fn1, arg1), App(fn2, arg2):
202
- return conv(fn1, fn2, defns) and conv(arg1, arg2, defns)
204
+ return (
205
+ conv(fn1, fn2, defns) and
206
+ conv(arg1, arg2, defns))
203
207
  case Pi(_, A1, B1), Pi(_, A2, B2):
204
- return conv(A1, A2, defns) and conv(B1, B2, defns)
208
+ return ( # NOTE: we preserve the accept_assignable flag for Pi types
209
+ conv(A2, A1, defns, accept_assignable) and # swap argument order to ensure contravariance
210
+ conv(B1, B2, defns, accept_assignable)) # output has same order for covariance
205
211
  case Lam(_, A1, body1), Lam(_, A2, body2):
206
- return conv(A1, A2, defns) and conv(body1, body2, defns)
212
+ return (
213
+ conv(A2, A1, defns) and
214
+ conv(body1, body2, defns))
207
215
  case _:
208
216
  return False # mismatched shapes
209
217
 
@@ -249,10 +257,16 @@ def infer(term:Term, ctx, defns:Definitions) -> Term:
249
257
  case _:
250
258
  raise TypecheckError(f"Failed to recognize term {term}")
251
259
 
260
+
261
+
262
+ def is_assignable(actual:Term, expected:Term, defns:Definitions) -> bool:
263
+ return conv(actual, expected, defns, accept_assignable=True)
264
+
265
+
252
266
  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)}.")
267
+ actual = infer(term, ctx, defns)
268
+ if not is_assignable(actual, expected, defns):
269
+ raise TypecheckError(f"Term {term.str(ctx)} not assignable to type {expected.str(ctx)}.\nActual type was {actual.str(ctx)}.")
256
270
 
257
271
 
258
272
 
@@ -301,10 +315,13 @@ class AxiomDefinition:
301
315
  return None
302
316
 
303
317
  class ConstDefinition:
304
- def __init__(self, name:str, value:Term, defns:Definitions):
318
+ def __init__(self, name:str, value:Term, defns:Definitions, expected_ty:(Term|None)=None):
305
319
  self.name = name
306
320
  self.value = whnf(value, defns)
307
321
  self.type = whnf(infer(self.value, [], defns), defns)
322
+ if expected_ty is not None:
323
+ if not is_assignable(self.type, expected_ty, defns):
324
+ raise TypecheckError(f"When defining constant {self.name}, expected a type of {expected_ty.str([])} but actually got {self.type.str([])}.")
308
325
  self.used = find_used_defs(self.value)
309
326
  def get_type(self, key:List[str]) -> Term:
310
327
  match key:
@@ -47,19 +47,33 @@ class DefsExtend:
47
47
  def __contains__(self, key:str) -> bool:
48
48
  return key in self.new_defs_dict or key in self.base_defns
49
49
  def match_reduce(self, key:str, argchain: List[Term], defns:Definitions) -> Tuple[Term, List[Term]] | None:
50
+ if key in self.new_defs_dict:
51
+ return None # Adding new reduction rules is not supported here
50
52
  return self.base_defns.match_reduce(key, argchain, defns)
51
53
 
52
54
 
53
- def typecheck_args(args:List[Tuple[str, IrNode]], ctx:List[Tuple[str, Term]], selfref_ir:IrNode, defns:Definitions):
55
+ def type_level(ty:Term, ctx:List[Tuple[str, Term]], defns:Definitions):
56
+ """ Compute the effective universe level of a type. """
57
+ ty_whnf = whnf(ty, defns)
58
+ if isinstance(ty_whnf, Sort):
59
+ return ty_whnf.level
60
+ else:
61
+ ty_ty = whnf(infer(ty_whnf, ctx, defns), defns)
62
+ if not isinstance(ty_ty, Sort):
63
+ raise TypecheckError(f"Expected {ty.str(ctx)} to be a Sort but found type {ty_ty.str(ctx)}.")
64
+ return ty_ty.level
65
+
66
+
67
+ def typecheck_args(args:List[Tuple[str, IrNode]], ctx:List[Tuple[str, Term]], selfref_ir:IrNode, defns:Definitions, max_level:int|None=None):
54
68
  """ Given a list of args that might be type parameters or constructor args,
55
69
  check that they are all some kind of Sort. Returns a full ctx containing all args. """
56
70
  if len(args) == 0: return ctx
57
71
  (arg_nm, arg_ty_ir), *args_rest = args
58
72
  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)
73
+ ty_level = type_level(arg_ty, ctx, defns) # typecheck and get the type's level
74
+ if max_level is not None and ty_level > max_level:
75
+ raise TypecheckError(f"Argument {arg_nm} is at the Type{ty_level} level but at most Type{max_level} would be sound.")
76
+ return typecheck_args(args_rest, [(arg_nm, arg_ty)] + ctx, selfref_ir, defns, max_level)
63
77
 
64
78
 
65
79
  @dataclass(frozen=True)
@@ -141,7 +155,7 @@ class ConstructorDef:
141
155
  self.args = args
142
156
  self.output_indices = output_indices
143
157
  # type & positivity checking:
144
- constructor_ctx = typecheck_args(self.args, self.indty.params_ctx, self.indty.selfref_ir, self.indty.defns_ext)
158
+ constructor_ctx = typecheck_args(self.args, self.indty.params_ctx, self.indty.selfref_ir, self.indty.defns_ext, self.indty.get_level())
145
159
  self.check_positive()
146
160
  self.check_output_indices(constructor_ctx, self.indty.inds_ctx)
147
161
  # prep data that will be used by match-reduce
@@ -252,6 +266,8 @@ class InductiveDef:
252
266
  IrConst(self.name),
253
267
  [IrVar(nm) for nm, _ in self.params]
254
268
  )
269
+ def get_level(self) -> int:
270
+ return self.sort.level
255
271
  def get_index_vars(self) -> List[IrNode]:
256
272
  """ Get a list of vars corresponding to this inductive's indices.
257
273
  Note: Assumes that the vars will be present somewhere in the context. """
@@ -348,5 +364,3 @@ class InductiveDef:
348
364
 
349
365
 
350
366
 
351
-
352
-
@@ -1,4 +1,4 @@
1
- from typing import List, Dict, Tuple
1
+ from typing import List, Dict, Tuple, Optional
2
2
 
3
3
  from .core import *
4
4
 
@@ -82,3 +82,16 @@ def to_positive_int(digits:str) -> int | None:
82
82
  return val
83
83
 
84
84
 
85
+ # IR node for constant definitions:
86
+ @dataclass(frozen=True)
87
+ class IrConstantDefinition(IrNode):
88
+ name: str
89
+ value: IrNode
90
+ expected_ty: Optional[IrNode]
91
+ def to_term(self, ctx_nm):
92
+ raise RuntimeError("Can't convert IrConstantDefinition to Term, it is intended for defining constants only.")
93
+ def to_definition(self, defns: Definitions):
94
+ expected_ty = self.expected_ty.to_term([]) if self.expected_ty is not None else None
95
+ return ConstDefinition(self.name, self.value.to_term([]), defns, expected_ty)
96
+
97
+
@@ -1,7 +1,7 @@
1
1
  import re
2
2
  from typing import List, Tuple
3
3
 
4
- from .ir import IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp, to_positive_int
4
+ from .ir import IrNode, IrSort, IrConst, IrVar, IrPi, IrLam, IrApp, IrConstantDefinition, to_positive_int
5
5
  from .core import Term
6
6
  from .inductive import IrInductiveSelfRef, IrConstructorDefinition, IrInductiveDefinition
7
7
 
@@ -13,7 +13,7 @@ _token_re = re.compile(
13
13
  \s* # skip leading whitespace
14
14
  ( # group captures only non-whitespace
15
15
  =>|->| # separators
16
- [\[\]()\|,:λΠι]| # punctuation (unicode lambdas, etc.)
16
+ [\[\]()\|,:=λΠδι]| # punctuation (unicode lambdas, etc.)
17
17
  """ + _ident_re + """ # identifiers
18
18
  )
19
19
  """,
@@ -68,6 +68,8 @@ class Parser:
68
68
  return self._parse_lambda()
69
69
  if tok == "Π":
70
70
  return self._parse_pi()
71
+ if tok == "δ":
72
+ return self._parse_delta()
71
73
  if tok == "ι":
72
74
  return self._parse_iota()
73
75
  # Otherwise we are in application / atom land.
@@ -94,6 +96,18 @@ class Parser:
94
96
  B = self._parse_expr()
95
97
  self.env_pop()
96
98
  return IrPi(name, A, B)
99
+ def _parse_delta(self) -> IrNode:
100
+ self._eat("δ")
101
+ name = self._eat()
102
+ assert re.match(_ident_re, name), f"expected a valid constant name instead of {name}"
103
+ if self._peek() == ":": # type annotation / theorem statement supplied
104
+ self._eat(":")
105
+ expected_ty = self._parse_expr()
106
+ else:
107
+ expected_ty = None
108
+ self._eat("=")
109
+ value = self._parse_expr()
110
+ return IrConstantDefinition(name, value, expected_ty)
97
111
  def _parse_iota(self) -> IrNode:
98
112
  assert self.indty_name is None, "can't create an inductive typedef inside an existing one"
99
113
  self._eat("ι")
@@ -179,7 +193,7 @@ class Parser:
179
193
  while True:
180
194
  nxt = self._peek()
181
195
  # close-paren or separators break application chain. binder starts do as well.
182
- if nxt is None or nxt in {")", "]", ":", ",", "=>", "->", "Π", "λ"}:
196
+ if nxt is None or nxt in {")", "]", ":", ",", "=>", "->", "Π", "λ", "="}:
183
197
  break
184
198
  arg = self._parse_atom()
185
199
  node = IrApp(node, arg)
@@ -234,3 +248,4 @@ def parse(src: str, ctx=None) -> Term:
234
248
  return ans_ir.to_term(ctx_names)
235
249
 
236
250
 
251
+