tinyprove 0.1.3__tar.gz → 0.1.5__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.3
3
+ Version: 0.1.5
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tinyprove"
7
- version = "0.1.3"
7
+ version = "0.1.5"
8
8
  description = "Tiny CoC-based theorem prover with inductive types"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -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
 
@@ -306,7 +320,7 @@ class ConstDefinition:
306
320
  self.value = whnf(value, defns)
307
321
  self.type = whnf(infer(self.value, [], defns), defns)
308
322
  if expected_ty is not None:
309
- if not conv(self.type, expected_ty, defns):
323
+ if not is_assignable(self.type, expected_ty, defns):
310
324
  raise TypecheckError(f"When defining constant {self.name}, expected a type of {expected_ty.str([])} but actually got {self.type.str([])}.")
311
325
  self.used = find_used_defs(self.value)
312
326
  def get_type(self, key:List[str]) -> Term:
@@ -47,19 +47,38 @@ 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_whnf:Term, ctx:List[Tuple[str, Term]], defns:Definitions):
56
+ """ Compute the effective universe level of a type. """
57
+ if isinstance(ty_whnf, Sort):
58
+ return ty_whnf.level
59
+ else:
60
+ ty_ty = whnf(infer(ty_whnf, ctx, defns), defns)
61
+ if not isinstance(ty_ty, Sort):
62
+ raise TypecheckError(f"Expected {ty_whnf.str(ctx)} to be a Sort but found type {ty_ty.str(ctx)}.")
63
+ return ty_ty.level
64
+
65
+
66
+ def typecheck_args(args:List[Tuple[str, IrNode]], ctx:List[Tuple[str, Term]], selfref_ir:IrNode, defns:Definitions,
67
+ max_level:int|None=None, positive_typenm:str|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
+ arg_ty_whnf = whnf(arg_ty, defns)
74
+ ty_level = type_level(arg_ty_whnf, ctx, defns) # typecheck and get the type's level
75
+ if max_level is not None and ty_level > max_level: # ensure constructor arguments lie within the correct universe
76
+ raise TypecheckError(f"Argument {arg_nm} is at the Type{ty_level} level but at most Type{max_level} would be sound.")
77
+ if positive_typenm is not None: # do a positivity check if a typename that must be positive was specificed
78
+ if not all(walk(positive_typenm, arg_ty_whnf, defns)):
79
+ raise DefinitionError(f"Constructor arg {arg_nm} fails positivity check.")
80
+ return typecheck_args(args_rest, [(arg_nm, arg_ty)] + ctx, selfref_ir, defns,
81
+ max_level, positive_typenm)
63
82
 
64
83
 
65
84
  @dataclass(frozen=True)
@@ -108,28 +127,31 @@ def selfref_sub(node:IrNode, selfref_ir:IrNode) -> IrNode:
108
127
  raise DefinitionError("Unknown node type.")
109
128
 
110
129
 
111
- def walk(indty_name: str, node:IrNode, polarity:bool=True) -> bool:
112
- """ Do a polarity check of node to ensure that self-references to our inductive type are positive only.
130
+ def walk(indty_name: str, arg_ty:Term, defns:Definitions, polarity:bool=True) -> List[bool]:
131
+ """ Do a polarity check of node and returns a list of polarities of self-references.
113
132
  polarity: True = positive, and False = negative """
114
- match node:
115
- case IrLam():
133
+ arg_ty = whnf(arg_ty, defns)
134
+ match arg_ty:
135
+ case Lam():
116
136
  raise DefinitionError("Lambdas not supported in constructor definition.")
117
- case IrPi(param, A, B):
118
- return walk(indty_name, A, not polarity) and walk(indty_name, B, polarity)
119
- case IrApp(fn, arg):
120
- return walk(indty_name, fn, polarity) and walk(indty_name, arg, polarity)
121
- case IrSort():
122
- return True
123
- case IrVar(nm):
124
- return True
125
- case IrConst(name):
137
+ case Pi(param, A, B):
138
+ return walk(indty_name, A, defns, not polarity) + walk(indty_name, B, defns, polarity)
139
+ case App(fn, arg):
140
+ arg_appearances = [
141
+ False # this application could produce a result where the inductive type appears negatively
142
+ for _ in walk(indty_name, arg, defns, polarity)
143
+ ]
144
+ return walk(indty_name, fn, defns, polarity) + arg_appearances
145
+ case Sort():
146
+ return []
147
+ case Var():
148
+ return []
149
+ case Const(name):
126
150
  if name == indty_name:
127
- raise DefinitionError("Found an IrConst that refers back to the original inductive type! This should be done solely with IrInductiveSelfRef.")
128
- return True
129
- case IrInductiveSelfRef(index_vals):
130
- return polarity
151
+ return [polarity]
152
+ return []
131
153
  case _:
132
- raise DefinitionError("Unknown node type.")
154
+ raise DefinitionError("Unknown term.")
133
155
 
134
156
 
135
157
  class ConstructorDef:
@@ -141,8 +163,8 @@ class ConstructorDef:
141
163
  self.args = args
142
164
  self.output_indices = output_indices
143
165
  # type & positivity checking:
144
- constructor_ctx = typecheck_args(self.args, self.indty.params_ctx, self.indty.selfref_ir, self.indty.defns_ext)
145
- self.check_positive()
166
+ constructor_ctx = typecheck_args(self.args, self.indty.params_ctx, self.indty.selfref_ir, self.indty.defns_ext,
167
+ max_level=self.indty.get_level(), positive_typenm=self.indty.name)
146
168
  self.check_output_indices(constructor_ctx, self.indty.inds_ctx)
147
169
  # prep data that will be used by match-reduce
148
170
  self.matchred_sig = self.get_matchred_sig()
@@ -176,10 +198,6 @@ class ConstructorDef:
176
198
  self.output_indices),
177
199
  applied_constructor_ty),
178
200
  converted_args[::-1])
179
- def check_positive(self):
180
- for arg_nm, arg_ty in self.args:
181
- if not walk(self.indty.name, arg_ty):
182
- raise DefinitionError(f"Constructor {self.name} arg {arg_nm} fails positivity check.")
183
201
  def check_output_indices(self, constructor_ctx:List[Tuple[str, Term]], inds_ctx:List[Tuple[str, Term]]):
184
202
  num_inds = len(self.indty.indices)
185
203
  assert len(self.output_indices) == num_inds, f"Constructor {self.name} definition has incorrect number of output indices."
@@ -252,6 +270,8 @@ class InductiveDef:
252
270
  IrConst(self.name),
253
271
  [IrVar(nm) for nm, _ in self.params]
254
272
  )
273
+ def get_level(self) -> int:
274
+ return self.sort.level
255
275
  def get_index_vars(self) -> List[IrNode]:
256
276
  """ Get a list of vars corresponding to this inductive's indices.
257
277
  Note: Assumes that the vars will be present somewhere in the context. """
@@ -348,5 +368,3 @@ class InductiveDef:
348
368
 
349
369
 
350
370
 
351
-
352
-
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyprove
3
- Version: 0.1.3
3
+ Version: 0.1.5
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
File without changes
File without changes
File without changes
File without changes