diff --git a/Deduce.lark b/Deduce.lark index d068f803..6e763e52 100644 --- a/Deduce.lark +++ b/Deduce.lark @@ -532,6 +532,7 @@ imp_block: "{" imp_stmt_list "}" -> imp_block | visibility "fun" identifier type_params_opt "(" variable_list ")" "{" term "}" -> fun | visibility "fun" identifier "<" identifier_list ">" "where" "{" concept_ref_list "}" "(" variable_list ")" "{" term "}" -> fun_where | visibility "recfun" identifier type_params_opt "(" variable_list ")" "->" type "measure" term "of" type "{" term "}" "terminates" proof -> general_recursive_function + | visibility "recfun" identifier "<" identifier_list ">" "where" "{" concept_ref_list "}" "(" variable_list ")" "->" type "measure" term "of" type "{" term "}" "terminates" proof -> general_recursive_function_where | visibility "proc" identifier type_params_opt "(" proc_param_list ")" proc_return_opt proc_spec_list imp_block proc_proof_opt -> proc_decl | visibility "observer" identifier type_params_opt "(" proc_param_list ")" "->" type observer_reads_list observer_body_opt -> observer_decl | visibility "resource" identifier type_params_opt "(" proc_param_list ")" resource_body_opt -> resource_decl diff --git a/abstract_syntax/declarations.py b/abstract_syntax/declarations.py index edade986..b8de7203 100644 --- a/abstract_syntax/declarations.py +++ b/abstract_syntax/declarations.py @@ -39,7 +39,7 @@ if TYPE_CHECKING: from .env import Env from .ops import uniquify_deduce - from .concepts import WhereClause, where_params + from .concepts import ConceptMember, ConceptRef, WhereClause, where_params @dataclass class Declaration(Statement): @@ -1307,8 +1307,12 @@ def _hidden(self) -> int: (added by uniquify).""" return len(self.where.operations()) if self.where else 0 + def own_params(self) -> List[Type]: + """``params`` without the operations of the where clause.""" + return self.params[:len(self.params) - self._hidden()] + def _header(self) -> str: - params = self.params[:len(self.params) - self._hidden()] + params = self.own_params() return complete_name(self.name) \ + ('<' + ','.join([name2str(t) for t in self.type_params]) + '>' \ if len(self.type_params) > 0 else '') \ @@ -1373,10 +1377,16 @@ class GenRecFun(Declaration): body: Term terminates: Proof trusted_terminates: bool = False - # The unique names of the `<` visible where this function is defined, - # recorded by ``uniquify``: the termination conditions compare the - # measure with it (#1250). - less: List[str] = field(default_factory=list, kw_only=True) + # `@WellFounded.<`, recorded by ``uniquify`` with the + # models in scope: the termination conditions compare the measure with + # the `<` of the model of WellFounded at the measure's type, whose + # theorem proves that `<` is well-founded (#1308). + less: Optional[ConceptMember] = field(default=None, kw_only=True) + # A where clause on the type parameters (#1298), as for `RecFun` + # (#1282): uniquify adds the operations of its refinement closure to + # ``vars``, after the function's own parameters. The `terminates` + # proof is in the clause's scope. + where: Optional[WhereClause] = field(default=None, kw_only=True) def uniquify(self, env: object, ctx: object) -> GenRecFun: env_map = cast(UniquifyEnv, env) @@ -1386,9 +1396,8 @@ def uniquify(self, env: object, ctx: object) -> GenRecFun: body_env, new_type_params = uniquify_type_params( env_map, self.type_params, uniq_ctx, self.location, extend) - terminates_env = copy_dict(env_map) - for (old, new) in zip(self.type_params, new_type_params): - extend(terminates_env, old, new, self.location) + where = self.where.bind(body_env, uniq_ctx) if self.where else None + terminates_env = copy_dict(body_env) new_returns = self.returns.uniquify(body_env, uniq_ctx) @@ -1403,15 +1412,25 @@ def uniquify(self, env: object, ctx: object) -> GenRecFun: overwrite(body_env, old, new, self.location) new_measure = self.measure.uniquify(body_env, uniq_ctx) - new_measure_ty = self.measure_ty.uniquify(env_map, uniq_ctx) + new_measure_ty = self.measure_ty.uniquify(body_env, uniq_ctx) + if 'WellFounded' not in body_env: + static_error(self.location, 'a recfun needs the concept WellFounded' + + ' (lib/WellFounded.pf) in scope: its measure decreases' + + ' along the `<` of a model of WellFounded') + less = ConceptMember(self.location, None, + ConceptRef(self.location, 'WellFounded', + [self.measure_ty]).uniquify(body_env, uniq_ctx), + '<', models=list(body_env.get(MODELS_KEY, []))) new_terminates = self.terminates.uniquify(terminates_env, uniq_ctx) new_body = self.body.uniquify(body_env, uniq_ctx) + if where is not None: + new_vars += where_params(where) return GenRecFun(self.location, new_name, new_type_params, new_vars, new_returns, new_measure, new_measure_ty, new_body, new_terminates, self.trusted_terminates, visibility=self.visibility, - less=list(env_map.get('<', []))) + less=less, where=where) _exports_overload = True @@ -1423,18 +1442,26 @@ def __str__(self) -> str: def to_string(self) -> str: return 'recfun ' + self.name + '<' + ','.join(self.type_params) + '>' \ + + (' ' + str(self.where) + ' ' if self.where else '') \ + '(' + ', '.join([x + ':' + str(t) if t else x\ - for (x,t) in self.vars]) + ')' \ + for (x,t) in self.own_vars()]) + ')' \ + ' -> ' + str(self.returns) + '\n' \ + '\tmeasure ' + str(self.measure) \ + ' {\n' + str(self.body) + '\n}\n' \ + 'terminates {\n' + str(self.terminates) + '\n}\n' + def own_vars(self) -> List[Tuple[str, Type]]: + """``vars`` without the operations of the where clause (added by + uniquify).""" + k = len(self.where.operations()) if self.where else 0 + return self.vars[:len(self.vars) - k] + def _header(self) -> str: return complete_name(self.name) \ + ('<' + ','.join([name2str(t) for t in self.type_params]) + '>' \ if len(self.type_params) > 0 else '') \ - + '(' + ', '.join([base_name(x) + ':' + str(t) if t else x for (x,t) in self.vars])\ + + (' ' + str(self.where) + ' ' if self.where else '') \ + + '(' + ', '.join([base_name(x) + ':' + str(t) if t else x for (x,t) in self.own_vars()])\ + ') -> ' + str(self.returns) def opaque_signature(self) -> str | None: diff --git a/abstract_syntax/terms.py b/abstract_syntax/terms.py index 4375fd66..0628d639 100644 --- a/abstract_syntax/terms.py +++ b/abstract_syntax/terms.py @@ -1424,8 +1424,11 @@ def reduce(self, env: Env) -> Term: typarams = gen_fun.type_params params = gen_fun.vars body = gen_fun.body - subst2: dict[str, Term | Type] = {k: v for ((k,t),v) in zip(params, args)} - ret = do_function_call(loc, name, typarams, type_args, [x for (x,t) in params], args, + # The operations for a where clause come after the arguments + # (#1298), as for `RecFun`. + all_args = args + fun.dicts + subst2: dict[str, Term | Type] = {k: v for ((k,t),v) in zip(params, all_args)} + ret = do_function_call(loc, name, typarams, type_args, [x for (x,t) in params], all_args, body, subst2, env, None, display_args=args) diff --git a/checker_concepts.py b/checker_concepts.py index ed5df1d0..5f57a2bd 100644 --- a/checker_concepts.py +++ b/checker_concepts.py @@ -28,14 +28,14 @@ from typing import Callable, cast from abstract_syntax import ( - All, AllElimTypes, And, BoolType, ConceptBinding, ConceptDecl, + All, AllElimTypes, And, BoolType, Call, ConceptBinding, ConceptDecl, ConceptMember, ConceptMemberProof, ConceptRef, Env, Formula, IfThen, ModelBinding, ModelDecl, Proof, ResolvedVar, Term, Type, FunctionType, TypeInst, TypeType, VarRef, WhereClause, WhereMember, base_name, concept_closure, where_body, ) from checker_types import check_formula, check_type, type_check_term -from error import user_error +from error import UserError, user_error, wrap_user_error from lark.tree import Meta # The term that stands for a member of a concept instance: a where @@ -201,10 +201,23 @@ def intro_where(loc: Meta, goal: All, x: str, where: WhereClause, frm = goal.body.substitute({goal.var[0]: ResolvedVar(loc, None, x)}) frm = _strip_operations(loc, frm, goal_where, lookup) frm = _discharge(loc, frm, _premise(body_env, where, lookup, loc)) + return frm, _assume_where(loc, where, body_env, lookup) + + +def where_scope(loc: Meta, where: WhereClause, env: Env) -> Env: + """The scope of the (checked) where clause ``where``, as after + `arbitrary T:type where {...}`: its operations, its theorems as + givens, and its models.""" + env = declare_where_operations(where, env, loc) + return _assume_where(loc, where, env, _binder_lookup(env, where, loc)) + + +def _assume_where(loc: Meta, where: WhereClause, env: Env, + lookup: MemberLookup) -> Env: for wm in where.theorems(): - body_env = body_env.declare_local_proof_var( - loc, wm.binder, axiom(body_env, wm.instance, wm.member, lookup, loc)) - return frm, add_where_models(loc, where, body_env) + env = env.declare_local_proof_var( + loc, wm.binder, axiom(env, wm.instance, wm.member, lookup, loc)) + return add_where_models(loc, where, env) def add_where_models(loc: Meta, where: WhereClause, env: Env) -> Env: @@ -398,6 +411,57 @@ def check_concept_member(term: ConceptMember, env: Env) -> Term: return _unfold(var, [model], env) +def well_founded_less(less: ConceptMember, env: Env) -> Term: + """The `<` that a recfun's measure decreases along (#1308): the + operation of the model of ``WellFounded<τ>`` in scope. The concept must + be the concept of well-founded orders: one operation `<` and the + theorem that `<` admits strong induction, which every model proves.""" + loc = less.location + decl = concept_of(env, less.ref.concept, loc) + if not _is_well_founded(decl): + user_error(loc, 'the concept ' + base_name(decl.name) + ' in scope is not' + + ' the concept of well-founded orders (lib/WellFounded.pf):' + + ' it needs one operation `<` and the theorem\n\t' + + 'all P: fn T -> bool, n:T. if (all j:T. if (all i:T.' + + ' if i < j then P(i)) then P(j)) then P(n)') + try: + return check_concept_member(less, env) + except UserError as e: + raise wrap_user_error(e, '\nA recfun\'s measure decreases along the `<`' + + ' of a model of WellFounded at its type, which' + + ' proves that `<` is well-founded.') + + +def _is_well_founded(decl: ConceptDecl) -> bool: + if len(decl.type_params) != 1 or len(decl.funs) != 1: + return False + (lt, lt_ty) = decl.funs[0] + if base_name(lt) != '<' or not isinstance(lt_ty, FunctionType) \ + or lt_ty.type_params or len(lt_ty.param_types) != 2 \ + or not isinstance(lt_ty.return_type, BoolType): + return False + t = lt_ty.param_types[0] + if not (isinstance(t, VarRef) and t.get_name() == decl.type_params[0] + and lt_ty.param_types[1] == t): + return False + loc = decl.location + bool_ty = BoolType(loc) + pred_ty = FunctionType(loc, [], [t], bool_ty) + def var(x: str, ty: Type) -> Term: + return ResolvedVar(loc, ty, x) + def call(f: Term, args: list[Term]) -> Formula: + return Call(loc, bool_ty, f, args) + p, n, j, i = var('P', pred_ty), var('n', t), var('j', t), var('i', t) + smaller = All(loc, bool_ty, ('i', t), (0, 1), + IfThen(loc, bool_ty, call(var(lt, lt_ty), [i, j]), call(p, [i]))) + step = All(loc, bool_ty, ('j', t), (0, 1), + IfThen(loc, bool_ty, smaller, call(p, [j]))) + strong = All(loc, bool_ty, ('P', pred_ty), (1, 2), + All(loc, bool_ty, ('n', t), (0, 2), + IfThen(loc, bool_ty, step, call(p, [n])))) + return any(frm == strong for (_, frm) in decl.theorems) + + def concept_member_formula(proof: ConceptMemberProof, env: Env) -> Formula: """`@C<τ>.thm` outside a where clause binding ``C<τ>``: the concept's theorem at the operations of the model in scope (which proved it).""" diff --git a/checker_pipeline.py b/checker_pipeline.py index 3b34b646..15dce8b9 100644 --- a/checker_pipeline.py +++ b/checker_pipeline.py @@ -25,6 +25,7 @@ from checker_concepts import ( add_where_models, check_where, collect_model, model_obligations, + well_founded_less, where_scope, process_concept, process_model, ) from abstract_syntax import ( @@ -1009,12 +1010,10 @@ def process_declaration_visibility(decl: Declaration, env: Env, user_error(loc, 'Add type annotations to the parameters.') checked_param_types: List[Type] = [cast(Type, t) for t in param_types] - fun_type = FunctionType(loc, typarams, checked_param_types, checked_returns) - # print('process declaration:') - # print(decl.pretty_print(4)) - check_type(measure_ty, env) - # return? GenRecFun(loc, name, typarams, params, returns, measure, measure_ty, body, terminates) - # changed to decl + where = check_where(decl.where, body_env) if decl.where else None + fun_type = where_fun_type(loc, typarams, checked_param_types, + checked_returns, where) + check_type(measure_ty, body_env) return (decl, env.declare_term_var(loc, name, fun_type, visibility=decl.visibility)) @@ -1742,16 +1741,19 @@ def _type_check_stmt(stmt: Statement, env: Env, for (x, p) in param_pairs] checked_returns = check_type(returns, body_env) checked_measure_ty = check_type(measure_ty, body_env) + where = check_where(stmt.where, body_env) if stmt.where else None fun_type = _alpha_renamed_function_type( loc, typarams, [t for (_, t) in checked_param_pairs], - checked_returns) + checked_returns, where) env = env.define_term_var(loc, name, fun_type, stmt.reduce(env), stmt.visibility) body_env = env.declare_type_vars(loc, typarams) body_env = body_env.declare_term_vars(loc, checked_param_pairs) + if where is not None: + body_env = add_where_models(loc, where, body_env) new_measure = type_check_term(measure, checked_measure_ty, body_env, None, []) new_body = type_check_term(body, checked_returns, body_env, None, []) @@ -1760,7 +1762,8 @@ def _type_check_stmt(stmt: Statement, env: Env, checked_returns, new_measure, checked_measure_ty, new_body, terminates, stmt.trusted_terminates, - visibility=stmt.visibility, less=stmt.less) + visibility=stmt.visibility, less=stmt.less, + where=where) # print('type check stmt:') # print(new_recfun.pretty_print(4)) return new_recfun @@ -1865,7 +1868,8 @@ def collect_env(stmt: Statement, env: Env) -> Env: case GenRecFun(loc, name, typarams, params, returns, _, _, body, _): - fun_type = FunctionType(loc, typarams, [t for (x,t) in params], returns) + fun_type = where_fun_type(loc, typarams, [t for (x,t) in params], + returns, stmt.where) return env.define_term_var(loc, name, fun_type, stmt, stmt.visibility) @@ -2186,7 +2190,17 @@ def _check_proofs(stmt: Statement, env: Env) -> None: if stmt.trusted_terminates: return body_env = env.declare_type_vars(loc, typarams) - + # The obligation quantifies over the function's own parameters; the + # where clause's operations and theorems are in scope (#1298). + params = stmt.own_vars() + if stmt.where is not None: + body_env = where_scope(loc, stmt.where, body_env) + + # The measure decreases along the `<` of the model of WellFounded at + # its type (#1308). + assert stmt.less is not None + less = well_founded_less(stmt.less, body_env) + # find recursive calls in the body calls = find_rec_calls(name, body, body_env) formulas: list[Formula] = [] @@ -2195,9 +2209,8 @@ def _check_proofs(stmt: Statement, env: Env) -> None: for call in calls: lhs = cast(Term, measure.substitute({x: arg for ((x,t),arg) in zip(params,call.args)})) rhs = measure.copy() - less = OverloadedVar(loc, None, stmt.less) # `Call` is a Term in the class hierarchy but acts as a Formula - # when its return type is Bool (here: `<` overloads). + # when its return type is Bool. less_frm = cast(Formula, Call(loc, None, less, [lhs,rhs])) condition = And(loc, None, call.conditions) \ if len(call.conditions) > 0 else None @@ -2218,8 +2231,11 @@ def _check_proofs(stmt: Statement, env: Env) -> None: formula = formulas[0] else: user_error(loc, 'There were no recursive calls in the body of this recfun') + # Quantify over the parameters the obligation mentions. + occurring = formula.free_vars() for (x,t) in reversed(params): - formula = All(loc, None, (x,t), (0,1), formula) + if x in occurring: + formula = All(loc, None, (x,t), (0,1), formula) formula = check_formula(formula, body_env) # check that the terminates proof proves the above formula diff --git a/checker_types.py b/checker_types.py index 39f8a1e9..6851aa00 100644 --- a/checker_types.py +++ b/checker_types.py @@ -1255,7 +1255,7 @@ def type_synth_term( case GenRecFun(loc, name, typarams, params, returns, _, _, body, _): param_types = [t for (p,t) in params] - fun_type = FunctionType(loc, typarams, param_types, returns) + fun_type = where_fun_type(loc, typarams, param_types, returns, term.where) ret = term term.typeof = fun_type diff --git a/compiler/lower.py b/compiler/lower.py index 42fbb24c..13017098 100644 --- a/compiler/lower.py +++ b/compiler/lower.py @@ -307,6 +307,11 @@ def lower_stmt(self, s: ast.Statement, module: str) -> Optional[ir.TopLevel]: or isinstance(s, ast.Export) or isinstance(s, ast.Associative) \ or isinstance(s, ast.Trace): return None + if isinstance(s, (ast.ConceptDecl, ast.ModelDecl)): + # No code of their own: the standard library's models of + # WellFounded only order recfun measures, in proofs (#1308). + # Passing a model's operations at run time is #1292. + return None if isinstance(s, ast.Import): # Imports are lowered to a flat statement list upstream # (the proof checker walks them via `Import.ast`); the @@ -433,6 +438,12 @@ def lower_term(self, t: ast.Term) -> ir.Term: if isinstance(t, ast.Mark): return self.lower_term(t.subject) if isinstance(t, ast.TermInst): + if t.dicts: + raise CompileError( + t.location, + "compiler does not yet pass the operations of a where " + f"clause, in the use of {t.subject} (issue #1292)", + ) return self.lower_term(t.subject) if isinstance(t, ast.Generic): return self.lower_term(t.body) diff --git a/examples/replicate.pf b/examples/replicate.pf index 974310b9..65769abd 100644 --- a/examples/replicate.pf +++ b/examples/replicate.pf @@ -19,7 +19,7 @@ recfun replicate(n : UInt, x : T) -> List else node(x, replicate(n ∸ 1, x)) } terminates { - arbitrary n:UInt, x:T + arbitrary n:UInt uint_monus_one_less[n] } diff --git a/gh_pages/doc/Reference.md b/gh_pages/doc/Reference.md index 4f9beb24..1db485ea 100644 --- a/gh_pages/doc/Reference.md +++ b/gh_pages/doc/Reference.md @@ -127,6 +127,7 @@ forms are parser/AST only today and most require - [Real Number](#real-number) - [Reason](#reason) - [Recall (Proof)](#recall-proof) +- [Recfun (Statement)](#recfun-statement) - [Recursive Function (Statement)](#recursive-function-statement) - [Relation (Statement)](#relation-statement) - [Reflexive (Proof)](#reflexive-proof) @@ -2618,6 +2619,90 @@ is a proof of the formula `P1 and ... and Pn`. The formulas `P1`,...,`Pn` must be in the givens at the current point in the proof. +## Recfun (Statement) + +```deduce-grammar +statement ::= visibility "recfun" identifier type_params_opt "(" variable_list ")" "->" type "measure" term "of" type "{" term "}" "terminates" proof +statement ::= visibility "recfun" identifier "<" identifier_list ">" "where" "{" concept_ref_list "}" "(" variable_list ")" "->" type "measure" term "of" type "{" term "}" "terminates" proof +``` + +The `recfun` statement defines a function by general recursion: the +recursive calls may pass any arguments, not only a part of a union +constructor as in a [`recursive` function](#recursive-function-statement). +Instead, the definition gives a *measure*, a term over the parameters, +and a proof, after `terminates`, that the measure gets smaller at every +recursive call. So every call terminates. + +For example, `replicate(n, x)` makes a list of `n` copies of `x`. It +recurses on `n ∸ 1`, which isn't part of a constructor of `UInt`, so it +is a `recfun` with measure `n`: + +```{.deduce^#recfun_replicate_example} +recfun replicate(n : UInt, x : T) -> List + measure n of UInt +{ + if n = 0 then [] + else node(x, replicate(n ∸ 1, x)) +} +terminates { + arbitrary n:UInt + uint_monus_one_less[n] +} + +assert replicate(3, 7) = [7, 7, 7] +``` + +* The parameters are written with their types, as for `fun`, followed + by `->` and the return type. +* `measure m of τ` gives the measure `m`, a term over the parameters, + and its type `τ`. The measure decreases along the `<` of the + [model](#model-statement) of `WellFounded<τ>` in scope, the concept + of well-founded orders (lib/WellFounded.pf): + + ``` + concept WellFounded { + fun operator < : fn (T, T) -> bool + theorem strong_induction: all P: fn T -> bool, n:T. + if (all j:T. if (all i:T. if i < j then P(i)) then P(j)) + then P(n) + } + ``` + + Its theorem says that `<` admits strong induction, so a measure can't + decrease forever, and every call of the `recfun` terminates. The + standard library has models for `Nat` and `UInt`. For another type, + prove strong induction for its `<` and give a model, e.g. + `model WellFounded { theorem strong_induction = steps_strong_induction }`. + It is an error if there is no model of `WellFounded<τ>` in scope; for + example, `Int` has none, because `<` on `Int` has no least element. A + generic `recfun` can be measured by a type parameter `T` under + `where { WellFounded }`. +* The body is a term, which can use `if`-`then`-`else` and `switch` to + decide when to recurse. +* The proof after `terminates` proves that the measure decreases. For + each recursive call, the measure with the call's arguments in place of + the parameters is less than the measure, under the conditions that + lead to the call: the condition of each enclosing `if` (or its + negation, in the `else` branch), and for each enclosing `switch` + case, that the subject equals the case's pattern, for all the + variables the pattern binds. The calls' facts are combined with `and`, and the + whole formula is quantified over the parameters that occur in it. For + `replicate`, the call is in the `else` branch of `if n = 0`, and `x` + doesn't occur, so the proof proves + + ``` + all n:UInt. if n ≠ 0 then n ∸ 1 < n + ``` + + The type parameters (`T`) are in scope in the proof. + +Use `expand` to unfold a `recfun` in a proof, as for other functions. + +A generic `recfun` may have a [where clause](#where-clause) after its +type parameters, as in `recfun mpow where { Monoid } (n : UInt, x : T) -> T`. +The where clause is in scope in the body and in the `terminates` proof, +so the proof can use the concepts' operations and theorems. + ## Recursive Function (Statement) ```deduce-grammar @@ -2663,7 +2748,8 @@ recursive call `length(next)` because `next` is part of `Node(n, next)`. Recursive functions may have more than one parameter but pattern matching is only supported for the first parameter. If you need to pattern match on a parameter that is not the first, you -can use a `switch` statement. +can use a `switch` statement. For recursion that doesn't follow the +structure of a union, use [`recfun`](#recfun-statement). ## Relation (Statement) @@ -3704,9 +3790,11 @@ opaque), and a theorem is the concept's theorem at the model's operations, e.g. `@Monoid.add_zero` proves `all x:bool. bor(x, false) = x`. -**Functions.** A generic `fun` or `recursive` function may have a -where clause after its type parameters. In its body, the operations of -the concepts can be used at the type parameters: +**Functions.** A generic `fun`, `recursive`, or `recfun` function may +have a where clause after its type parameters (a `recfun`'s +`terminates` proof is also in the scope of the where clause, so the +concepts' theorems are among its givens). In its body, the operations +of the concepts can be used at the type parameters: ``` recursive msum where { Monoid } (List) -> T { diff --git a/gh_pages/doc/StandardLib.md b/gh_pages/doc/StandardLib.md index 6c26de19..774e39b1 100644 --- a/gh_pages/doc/StandardLib.md +++ b/gh_pages/doc/StandardLib.md @@ -49,3 +49,8 @@ Only the top-level module files (such as `UInt.pf`) are listed below. Each modul axioms a file depends on. - ([`Set.thm`](../lib/Set.thm), [`Set.pf`](../lib/Set.pf)): Sets - ([`UInt.thm`](../lib/UInt.thm), [`UInt.pf`](../lib/UInt.pf)): Unsigned integers +- ([`WellFounded.thm`](../lib/WellFounded.thm), [`WellFounded.pf`](../lib/WellFounded.pf)): + The concept `WellFounded` of well-founded orders, whose `<` admits + strong induction. A [`recfun`](./Reference.md#recfun-statement)'s + measure decreases along the `<` of a model of it; `Nat` and `UInt` + have models. diff --git a/imperative_verifier.py b/imperative_verifier.py index bf0dd6c6..a30837f9 100644 --- a/imperative_verifier.py +++ b/imperative_verifier.py @@ -34,8 +34,8 @@ import style from abstract_syntax import ( - And, ArrayGet, Bool, Call, Env, Formula, OverloadedVar, Proof, Term, - base_name, is_true, + And, ArrayGet, Bool, Call, Env, Formula, ModelBinding, OverloadedVar, + Proof, Term, base_name, is_true, ) @@ -174,8 +174,12 @@ def index_in_bounds_goal(loc: Meta, handle: Term, index: Term, writes in the symbolic state).""" from checker_types import type_check_formula from error import user_error + # A model's operations are reached through the model, not by name: the + # model of WellFounded defines a `<` at UInt too (#1308). + model_ops = {define for b in env.dict.values() if isinstance(b, ModelBinding) + for (_, define, _) in b.model.funs} length_names = [n for n in env.dict if base_name(n) == 'length'] - lt_names = [n for n in env.dict if base_name(n) == '<'] + lt_names = [n for n in env.dict if base_name(n) == '<' and n not in model_ops] if not length_names or not lt_names: user_error(loc, 'a mutable-array bounds check needs `length` and `<` in ' 'scope; add `import List` and `import UInt`') diff --git a/lib/NatDiv.pf b/lib/NatDiv.pf index 1e29b631..24c168a9 100644 --- a/lib/NatDiv.pf +++ b/lib/NatDiv.pf @@ -8,6 +8,7 @@ import NatMonus import NatMult import NatLess import NatEvenOdd +public import WellFounded /* Theorems about Nat division, modulo, and divisibility. @@ -236,39 +237,6 @@ proof div2_aux_mono end -/* - Properties of Division and Modulo - */ - -// Division by iterated subtraction. -recfun operator /(n : Nat, m : Nat) -> Nat - measure n of Nat -{ - if n < m then zero - else if m = zero then zero - else suc(zero) + (n ∸ m) / m -} -terminates { - arbitrary n:Nat, m:Nat - assume cond: not (n < m) and not (m = zero) - suffices m + (n ∸ m) < m + n by add_both_sides_of_less[m,n∸m,n] - suffices n < m + n by { - have m_n: m ≤ n by apply not_less_implies_less_equal to conjunct 0 of cond - replace apply monus_add_identity[n,m] to m_n. - } - obtain m' where m_sm: m = suc(m') from apply not_zero_suc to conjunct 1 of cond - suffices n < suc(m') + n by replace m_sm. - suffices n ≤ m' + n by expand operator+ | operator< | operator≤. - replace add_commute - show n ≤ n + m' - less_equal_add -} - -// Modulo: the remainder left after dividing n by m. -fun operator % (n:Nat, m:Nat) { - n ∸ (n / m) * m -} - // Helper for strong_induction: P holds for every k below an arbitrary bound j. lemma strong_induction_aux: all P: fn Nat -> bool. if (all n:Nat. if (all k:Nat. if k < n then P(k)) then P(n)) @@ -324,6 +292,45 @@ proof conclude P(n) by apply X[suc(n),n] to recall n < suc(n) end +// `<` on Nat is well-founded, so it can order a recfun's measure (#1308). +model WellFounded { + theorem strong_induction = strong_induction +} + +/* + Properties of Division and Modulo + */ + +// Division by iterated subtraction. +recfun operator /(n : Nat, m : Nat) -> Nat + measure n of Nat +{ + if n < m then zero + else if m = zero then zero + else suc(zero) + (n ∸ m) / m +} +terminates { + arbitrary n:Nat, m:Nat + assume cond: not (n < m) and not (m = zero) + suffices m + (n ∸ m) < m + n by add_both_sides_of_less[m,n∸m,n] + suffices n < m + n by { + have m_n: m ≤ n by apply not_less_implies_less_equal to conjunct 0 of cond + replace apply monus_add_identity[n,m] to m_n. + } + obtain m' where m_sm: m = suc(m') from apply not_zero_suc to conjunct 1 of cond + suffices n < suc(m') + n by replace m_sm. + suffices n ≤ m' + n by expand operator+ | operator< | operator≤. + replace add_commute + show n ≤ n + m' + less_equal_add +} + +// Modulo: the remainder left after dividing n by m. +fun operator % (n:Nat, m:Nat) { + n ∸ (n / m) * m +} + + // Internal predicate used to prove `division` by strong induction on the dividend. private fun DivPred(n:Nat) { all m:Nat. if zero < m then some r:Nat. (n / m) * m + r = n and r < m diff --git a/lib/UIntAdd.pf b/lib/UIntAdd.pf index 831ac11a..5cd3a14d 100644 --- a/lib/UIntAdd.pf +++ b/lib/UIntAdd.pf @@ -5,6 +5,7 @@ import Nat import UIntDefs import UIntToFrom import UIntLess +public import WellFounded /* Theorems about UInt addition. @@ -773,3 +774,8 @@ proof have Pn: P(fromNat(toNat(n))) by expand Q in Qn conclude P(n) by replace uint_fromNat_toNat in Pn end + +// `<` on UInt is well-founded, so it can order a recfun's measure (#1308). +model WellFounded { + theorem strong_induction = uint_strong_induction +} diff --git a/lib/WellFounded.pf b/lib/WellFounded.pf new file mode 100644 index 00000000..4bad205c --- /dev/null +++ b/lib/WellFounded.pf @@ -0,0 +1,14 @@ +module WellFounded + +// Well-founded orders (#1308). The measure of a `recfun` must have a +// type with a model of `WellFounded`: its `<` is the order the measure +// decreases along, and `strong_induction` proves that the order has no +// infinite descending chain, so the recursion terminates. The standard +// library has models for `Nat` and `UInt`. + +concept WellFounded { + fun operator < : fn (T, T) -> bool + theorem strong_induction: all P: fn T -> bool, n:T. + if (all j:T. if (all i:T. if i < j then P(i)) then P(j)) + then P(n) +} diff --git a/lsp/query.py b/lsp/query.py index d31b2c72..678b8908 100644 --- a/lsp/query.py +++ b/lsp/query.py @@ -1920,24 +1920,26 @@ def _symbol_info_for(stmt: "Statement", path: str) -> Optional[SymbolInfo]: signature = f"define {base_name(stmt.name)}{ty_text}" elif isinstance(stmt, RecFun): kind = SymbolKind.FUNCTION - params = ", ".join(str(p) for p in stmt.params) + params = ", ".join(str(p) for p in stmt.own_params()) typarams = ( f"<{', '.join(stmt.type_params)}>" if stmt.type_params else "" ) + where = f" {stmt.where} " if stmt.where else "" signature = ( - f"function {base_name(stmt.name)}{typarams}({params}) -> {stmt.returns}" + f"function {base_name(stmt.name)}{typarams}{where}({params}) -> {stmt.returns}" ) elif isinstance(stmt, GenRecFun): # ``recfun'' -- the polymorphic-recursion form. Same surface # as ``RecFun'' but parameter list is a list of (name, type) # tuples rather than parsed ``Param'' nodes. kind = SymbolKind.FUNCTION - params = ", ".join(f"{n}: {t}" for (n, t) in stmt.vars) + params = ", ".join(f"{base_name(n)}: {t}" for (n, t) in stmt.own_vars()) typarams = ( f"<{', '.join(stmt.type_params)}>" if stmt.type_params else "" ) + where = f" {stmt.where} " if stmt.where else "" signature = ( - f"function {base_name(stmt.name)}{typarams}({params}) -> {stmt.returns}" + f"function {base_name(stmt.name)}{typarams}{where}({params}) -> {stmt.returns}" ) elif isinstance(stmt, Union): kind = SymbolKind.UNION diff --git a/parser.py b/parser.py index 4b21f724..7bb4236a 100644 --- a/parser.py +++ b/parser.py @@ -1223,17 +1223,20 @@ def parse_tree_to_ast(e: ParseNode, parent: ParseParent) -> Any: return statement # general recursion - elif e.data == 'general_recursive_function': + elif e.data in ('general_recursive_function', 'general_recursive_function_where'): + w = 1 if e.data == 'general_recursive_function_where' else 0 visibility = parse_tree_to_ast(e.children[0], e) statement = GenRecFun(e.meta, parse_tree_to_ast(e.children[1], e), parse_tree_to_list(e.children[2], e), - parse_tree_to_list(e.children[3], e), - parse_tree_to_ast(e.children[4], e), - parse_tree_to_ast(e.children[5], e), - parse_tree_to_ast(e.children[6], e), - parse_tree_to_ast(e.children[7], e), - parse_tree_to_ast(e.children[8], e)) + parse_tree_to_list(e.children[3 + w], e), + parse_tree_to_ast(e.children[4 + w], e), + parse_tree_to_ast(e.children[5 + w], e), + parse_tree_to_ast(e.children[6 + w], e), + parse_tree_to_ast(e.children[7 + w], e), + parse_tree_to_ast(e.children[8 + w], e), + where=WhereClause(e.meta, parse_tree_to_list(e.children[3], e)) + if w else None) set_visibility(statement, visibility) return statement diff --git a/rec_desc_parser.py b/rec_desc_parser.py index 537f08da..987851eb 100644 --- a/rec_desc_parser.py +++ b/rec_desc_parser.py @@ -1603,6 +1603,7 @@ def parse_gen_rec_function(visibility: str) -> Statement: advance() name = parse_identifier() typarams = parse_type_parameters() + where = parse_where_clause_opt() if typarams else None if current_token().type == 'LPAR': advance() @@ -1625,7 +1626,8 @@ def parse_gen_rec_function(visibility: str) -> Statement: meta = meta_from_tokens(start_token, previous_token()) return GenRecFun(meta, name, typarams, params, return_type, - measure, measure_ty, body, terminates, visibility=visibility) + measure, measure_ty, body, terminates, visibility=visibility, + where=where) def parse_concept_ref() -> ConceptRef: diff --git a/test/compile/lower/genrecfun.cir b/test/compile/lower/genrecfun.cir index ad41257c..a4da7cbf 100644 --- a/test/compile/lower/genrecfun.cir +++ b/test/compile/lower/genrecfun.cir @@ -2,5 +2,5 @@ union MyNat.s0_0 {zero.s0_1/0, suc.s0_2/1} fn iszero.s1_2(n.s1_0) = match n.s1_0 { | zero.s0_1 -> true | suc.s0_2(n'.s1_1) -> false } fn pred.s2_2(n.s2_0) = match n.s2_0 { | zero.s0_1 -> zero.s0_1 | suc.s0_2(n'.s2_1) -> n'.s2_1 } fn <.s3_0($scr0, m.s3_1) = match $scr0 { | zero.s0_1 -> match m.s3_1 { | zero.s0_1 -> false | suc.s0_2(m'.s3_2) -> true } | suc.s0_2(n'.s3_3) -> match m.s3_1 { | zero.s0_1 -> false | suc.s0_2(m'.s3_5) -> <.s3_0(n'.s3_3, m'.s3_5) } } -fn count_down.s6_0(n.s6_1) = if iszero.s1_2(n.s6_1) then zero.s0_1 else count_down.s6_0(pred.s2_2(n.s6_1)) -print count_down.s6_0(suc.s0_2(suc.s0_2(suc.s0_2(zero.s0_1)))) +fn count_down.s9_0(n.s9_1) = if iszero.s1_2(n.s9_1) then zero.s0_1 else count_down.s9_0(pred.s2_2(n.s9_1)) +print count_down.s9_0(suc.s0_2(suc.s0_2(suc.s0_2(zero.s0_1)))) diff --git a/test/compile/lower/genrecfun.ir b/test/compile/lower/genrecfun.ir index ad41257c..a4da7cbf 100644 --- a/test/compile/lower/genrecfun.ir +++ b/test/compile/lower/genrecfun.ir @@ -2,5 +2,5 @@ union MyNat.s0_0 {zero.s0_1/0, suc.s0_2/1} fn iszero.s1_2(n.s1_0) = match n.s1_0 { | zero.s0_1 -> true | suc.s0_2(n'.s1_1) -> false } fn pred.s2_2(n.s2_0) = match n.s2_0 { | zero.s0_1 -> zero.s0_1 | suc.s0_2(n'.s2_1) -> n'.s2_1 } fn <.s3_0($scr0, m.s3_1) = match $scr0 { | zero.s0_1 -> match m.s3_1 { | zero.s0_1 -> false | suc.s0_2(m'.s3_2) -> true } | suc.s0_2(n'.s3_3) -> match m.s3_1 { | zero.s0_1 -> false | suc.s0_2(m'.s3_5) -> <.s3_0(n'.s3_3, m'.s3_5) } } -fn count_down.s6_0(n.s6_1) = if iszero.s1_2(n.s6_1) then zero.s0_1 else count_down.s6_0(pred.s2_2(n.s6_1)) -print count_down.s6_0(suc.s0_2(suc.s0_2(suc.s0_2(zero.s0_1)))) +fn count_down.s9_0(n.s9_1) = if iszero.s1_2(n.s9_1) then zero.s0_1 else count_down.s9_0(pred.s2_2(n.s9_1)) +print count_down.s9_0(suc.s0_2(suc.s0_2(suc.s0_2(zero.s0_1)))) diff --git a/test/compile/lower/genrecfun.pf b/test/compile/lower/genrecfun.pf index ed6e5a62..77aa0dc9 100644 --- a/test/compile/lower/genrecfun.pf +++ b/test/compile/lower/genrecfun.pf @@ -50,6 +50,24 @@ proof less_suc[n] end +// A recfun's measure needs a model of WellFounded (#1308). This test +// runs without the standard library, so it declares the concept, and +// postulates strong induction for MyNat (the lowering doesn't use it). +concept WellFounded { + fun operator < : fn (T, T) -> bool + theorem strong_induction: all P: fn T -> bool, n:T. + if (all j:T. if (all i:T. if i < j then P(i)) then P(j)) + then P(n) +} + +postulate mynat_strong_induction: all P: fn MyNat -> bool, n:MyNat. + if (all j:MyNat. if (all i:MyNat. if i < j then P(i)) then P(j)) + then P(n) + +model WellFounded { + theorem strong_induction = mynat_strong_induction +} + recfun count_down(n : MyNat) -> MyNat measure n of MyNat { diff --git a/test/compile/lower/genrecfun.pir b/test/compile/lower/genrecfun.pir index c60f0445..3e33bc9f 100644 --- a/test/compile/lower/genrecfun.pir +++ b/test/compile/lower/genrecfun.pir @@ -1,5 +1,5 @@ union MyNat.s0_0 {zero.s0_1/0, suc.s0_2/1} fn iszero.s1_2(n.s1_0) = match n.s1_0 { | zero.s0_1 -> true | suc.s0_2(n'.s1_1) -> false } fn pred.s2_2(n.s2_0) = match n.s2_0 { | zero.s0_1 -> zero.s0_1 | suc.s0_2(n'.s2_1) -> n'.s2_1 } -fn count_down.s6_0(n.s6_1) = if iszero.s1_2(n.s6_1) then zero.s0_1 else count_down.s6_0(pred.s2_2(n.s6_1)) -print count_down.s6_0(suc.s0_2(suc.s0_2(suc.s0_2(zero.s0_1)))) +fn count_down.s9_0(n.s9_1) = if iszero.s1_2(n.s9_1) then zero.s0_1 else count_down.s9_0(pred.s2_2(n.s9_1)) +print count_down.s9_0(suc.s0_2(suc.s0_2(suc.s0_2(zero.s0_1)))) diff --git a/test/lsp/test_symbols.py b/test/lsp/test_symbols.py index 369d119d..b392c23d 100644 --- a/test/lsp/test_symbols.py +++ b/test/lsp/test_symbols.py @@ -135,6 +135,42 @@ def test_list_symbols_includes_imperative_declarations() -> None: assert by_name["cell"].location.range.start.line == 16 +def test_list_symbols_hides_where_operations() -> None: + # The operations of a where clause become extra parameters after + # uniquify (#1282, #1298); a signature shows only the source's own. + src = ( + "import UInt\n" + "\n" + "concept Monoid {\n" + " fun operator+ : fn (T, T) -> T\n" + " fun zero : T\n" + "}\n" + "\n" + "recursive msum where { Monoid } (List) -> T {\n" + " msum([]) = zero\n" + " msum(node(x, xs)) = x + msum(xs)\n" + "}\n" + "\n" + "recfun replicate where { Monoid } (n:UInt, x:T) -> List\n" + " measure n of UInt\n" + "{\n" + " if n = 0 then [] else node(x, replicate(n ∸ 1, x))\n" + "}\n" + "terminates {\n" + " arbitrary n:UInt\n" + " assume: not (n = 0)\n" + " uint_monus_one_less[n]\n" + "}\n" + ) + by_name = {s.name: s for s in list_symbols("test.pf", src)} + msum = by_name["msum"].signature + replicate = by_name["replicate"].signature + assert msum == "function msum where { Monoid } (List) -> T" + assert replicate == ( + "function replicate where { Monoid } (n: UInt, x: T) -> List" + ) + + def test_list_symbols_returns_empty_on_parse_error() -> None: # Truncated source: parser error before any declaration is built. src = "theorem t: true\nproof\n" diff --git a/test/should-error/recfun_fake_well_founded.pf b/test/should-error/recfun_fake_well_founded.pf new file mode 100644 index 00000000..bfc72fac --- /dev/null +++ b/test/should-error/recfun_fake_well_founded.pf @@ -0,0 +1,24 @@ +// A concept named WellFounded that doesn't state strong induction for +// its `<` can't order a recfun's measure (#1308): otherwise any model +// of it could make a non-terminating recfun pass. + +concept WellFounded { + fun operator < : fn (T, T) -> bool +} + +union Tick { tick } + +fun always(a : Tick, b : Tick) { true } + +model WellFounded { + fun operator < = always +} + +recfun loop(n : Tick) -> Tick + measure n of Tick +{ + loop(n) +} +terminates { + evaluate +} diff --git a/test/should-error/recfun_fake_well_founded.pf.err b/test/should-error/recfun_fake_well_founded.pf.err new file mode 100644 index 00000000..f00a84bb --- /dev/null +++ b/test/should-error/recfun_fake_well_founded.pf.err @@ -0,0 +1,2 @@ +./test/should-error/recfun_fake_well_founded.pf:17.1-24.2: the concept WellFounded in scope is not the concept of well-founded orders (lib/WellFounded.pf): it needs one operation `<` and the theorem + all P: fn T -> bool, n:T. if (all j:T. if (all i:T. if i < j then P(i)) then P(j)) then P(n) diff --git a/test/should-error/recfun_measure_int.pf b/test/should-error/recfun_measure_int.pf new file mode 100644 index 00000000..ceee0b56 --- /dev/null +++ b/test/should-error/recfun_measure_int.pf @@ -0,0 +1,13 @@ +// `<` on Int is not well-founded, so Int can't be a recfun's measure +// (#1308): `h` never terminates, although each call decreases `n`. + +import Int + +recfun h(n : Int) -> UInt + measure n of Int +{ + 1 + h(n - +1) +} +terminates { + ? +} diff --git a/test/should-error/recfun_measure_int.pf.err b/test/should-error/recfun_measure_int.pf.err new file mode 100644 index 00000000..f738048e --- /dev/null +++ b/test/should-error/recfun_measure_int.pf.err @@ -0,0 +1,2 @@ +./test/should-error/recfun_measure_int.pf:6.1-13.2: no model of WellFounded in scope +A recfun's measure decreases along the `<` of a model of WellFounded at its type, which proves that `<` is well-founded. diff --git a/test/should-error/recfun_measure_not_well_founded.pf b/test/should-error/recfun_measure_not_well_founded.pf new file mode 100644 index 00000000..34d5018d --- /dev/null +++ b/test/should-error/recfun_measure_not_well_founded.pf @@ -0,0 +1,27 @@ +// A recfun's measure must decrease along a well-founded `<` (#1308): +// here `<` on Tick is always true, so without the check `loop` would +// be accepted and its equation `loop(0) = 1 + loop(0)` would prove +// false. There is no model of WellFounded. + +import UInt + +union Tick { tick } + +fun operator < (a : Tick, b : Tick) { true } + +recfun loop(n : UInt) -> UInt + measure tick of Tick +{ + 1 + loop(n) +} +terminates { + arbitrary n:UInt + evaluate +} + +theorem oops: false +proof + have eq: # loop(0) # = 1 + loop(0) by expand loop. + have bad: loop(0) < # loop(0) # by replace eq. + apply uint_less_irreflexive[loop(0)] to bad +end diff --git a/test/should-error/recfun_measure_not_well_founded.pf.err b/test/should-error/recfun_measure_not_well_founded.pf.err new file mode 100644 index 00000000..75c3ac01 --- /dev/null +++ b/test/should-error/recfun_measure_not_well_founded.pf.err @@ -0,0 +1,2 @@ +./test/should-error/recfun_measure_not_well_founded.pf:12.1-20.2: no model of WellFounded in scope +A recfun's measure decreases along the `<` of a model of WellFounded at its type, which proves that `<` is well-founded. diff --git a/test/should-error/where_recfun_no_model.pf b/test/should-error/where_recfun_no_model.pf new file mode 100644 index 00000000..58aea2ee --- /dev/null +++ b/test/should-error/where_recfun_no_model.pf @@ -0,0 +1,7 @@ +// A call to a recfun with a where clause (#1298) needs a model of the +// clause's concepts at the call's types. + +import ConceptMonoidSum +import UInt + +assert mpow(2, 3) = 6 diff --git a/test/should-error/where_recfun_no_model.pf.err b/test/should-error/where_recfun_no_model.pf.err new file mode 100644 index 00000000..796e2d48 --- /dev/null +++ b/test/should-error/where_recfun_no_model.pf.err @@ -0,0 +1 @@ +./test/should-error/where_recfun_no_model.pf:7.8-7.18: no model of Monoid in scope diff --git a/test/should-validate/recfun_roundtrip.pf b/test/should-validate/recfun_roundtrip.pf index 319cca2a..c1255abe 100644 --- a/test/should-validate/recfun_roundtrip.pf +++ b/test/should-validate/recfun_roundtrip.pf @@ -23,7 +23,7 @@ recfun replicate(n : UInt, x : T) -> List else node(x, replicate(n ∸ 1, x)) } terminates { - arbitrary n:UInt, x:T + arbitrary n:UInt uint_monus_one_less[n] } diff --git a/test/should-validate/recfun_well_founded.pf b/test/should-validate/recfun_well_founded.pf new file mode 100644 index 00000000..ccfc807a --- /dev/null +++ b/test/should-validate/recfun_well_founded.pf @@ -0,0 +1,85 @@ +// A recfun's measure decreases along the `<` of a model of WellFounded +// (#1308). A new type can be a measure once its `<` is proved +// well-founded in a model, and a generic recfun can be measured by its +// type parameter under a where clause. + +import UInt + +// A count of steps, ordered by the count. +union Steps { steps(UInt) } + +fun count(s : Steps) { + switch s { case steps(n) { n } } +} + +fun operator < (a : Steps, b : Steps) { count(a) < count(b) } + +theorem steps_strong_induction: all P: fn Steps -> bool, n:Steps. + if (all j:Steps. if (all i:Steps. if i < j then P(i)) then P(j)) + then P(n) +proof + arbitrary P: fn Steps -> bool, n:Steps + assume step + define Q = fun k:UInt { P(steps(k)) } + have q_step: all j:UInt. if (all i:UInt. if i < j then Q(i)) then Q(j) by { + arbitrary j:UInt + assume IH: all i:UInt. if i < j then Q(i) + have smaller: all i:Steps. if i < steps(j) then P(i) by { + arbitrary i:Steps + switch i { + case steps(k) { + assume lt + have k_lt: k < j by expand operator< | count in lt + expand Q in apply IH[k] to k_lt + } + } + } + expand Q + apply step[steps(j)] to smaller + } + switch n { + case steps(k) { + expand Q in apply uint_strong_induction[Q, k] to q_step + } + } +end + +model WellFounded { + theorem strong_induction = steps_strong_induction +} + +recfun countdown(s : Steps) -> UInt + measure s of Steps +{ + switch s { + case steps(n) { + if n = 0 then 0 + else 1 + countdown(steps(n ∸ 1)) + } + } +} +terminates { + arbitrary s:Steps, n:UInt + assume prem: s = steps(n) and n ≠ 0 + replace conjunct 0 of prem + expand operator< | count + apply uint_monus_one_less[n] to conjunct 1 of prem +} + +assert countdown(steps(3)) = 3 + +// A generic recfun measured by its type parameter: the where clause +// provides the well-founded `<`. +recfun down where { WellFounded } (x : T, y : T) -> UInt + measure x of T +{ + if y < x then 1 + down(y, y) else 0 +} +terminates { + arbitrary x:T, y:T + assume lt: y < x + lt +} + +assert down(3, 1) = 1 +assert down(1, 3) = 0 diff --git a/test/should-validate/uint_replicate.pf b/test/should-validate/uint_replicate.pf index 65ae9f5c..d36afc98 100644 --- a/test/should-validate/uint_replicate.pf +++ b/test/should-validate/uint_replicate.pf @@ -8,7 +8,7 @@ recfun replicate(n : UInt, x : T) -> List else node(x, replicate(n ∸ 1, x)) } terminates { - arbitrary n:UInt, x:T + arbitrary n:UInt uint_monus_one_less[n] } diff --git a/test/should-validate/where_functions.pf b/test/should-validate/where_functions.pf index 114bc1c6..fc505e2e 100644 --- a/test/should-validate/where_functions.pf +++ b/test/should-validate/where_functions.pf @@ -6,6 +6,7 @@ import ConceptMonoidSum import ConceptBoolModel import ConceptOpaqueModel import List +import UInt // At a model's type, the call computes with the model's operations. assert msum([false, true, false]) = true @@ -103,3 +104,31 @@ fun pick where { Marker } (x:T) { x } assert pick(true) = true assert map([false], @pick) = [false] + +// General recursion with a where clause (#1298): `mpow` (in +// ConceptMonoidSum) computes with Monoid's operations, and is a +// value once instantiated. +assert mpow(3, true) = true +assert mpow(0, true) = false +assert map([0, 2], fun n:UInt { @mpow(n, true) }) = [false, true] + +theorem mpow_one_bool: all x:bool. mpow(1, x) = x +proof + mpow_one +end + +// The `terminates` proof is in the scope of the where clause: its +// theorems are givens there. +recfun mtimes where { Monoid } (n : UInt, x : T) -> T + measure n of UInt +{ + if n = 0 then zero + else x + mtimes(n ∸ 1, x) +} +terminates { + arbitrary n:UInt + have az: all y:T. y + zero = y by add_zero + uint_monus_one_less[n] +} + +assert mtimes(2, true) = true diff --git a/test/test-imports/ConceptMonoidSum.pf b/test/test-imports/ConceptMonoidSum.pf index 3755c8d8..e12fa4ef 100644 --- a/test/test-imports/ConceptMonoidSum.pf +++ b/test/test-imports/ConceptMonoidSum.pf @@ -5,6 +5,7 @@ module ConceptMonoidSum public import ConceptMonoid import List +import UInt recursive msum where { Monoid } (List) -> T { msum(empty) = zero @@ -21,3 +22,23 @@ proof expand 2*msum add_zero[x] end + +// General recursion with a where clause (#1298): x + (x + ... + zero). +recfun mpow where { Monoid } (n : UInt, x : T) -> T + measure n of UInt +{ + if n = 0 then zero + else x + mpow(n ∸ 1, x) +} +terminates { + arbitrary n:UInt + uint_monus_one_less[n] +} + +theorem mpow_one: all T:type where { Monoid }. all x:T. mpow(1, x) = x +proof + arbitrary T:type where { Monoid } + arbitrary x:T + expand 2*mpow + add_zero[x] +end diff --git a/test/unit/test_compile_where.py b/test/unit/test_compile_where.py new file mode 100644 index 00000000..327e175c --- /dev/null +++ b/test/unit/test_compile_where.py @@ -0,0 +1,60 @@ +"""Compiling a call that passes a where clause's operations is a +compile-time error until the back end passes them (#1292).""" +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize("decl, call", [ + ("fun twice where { Monoid } (x:T) { x + x }", "twice(true)"), + ("recfun count where { Monoid } (n:N, x:T) -> T\n" + " measure n of N\n" + "{\n" + " switch n { case z { x } case s(m) { x + count(m, x) } }\n" + "}\n" + "terminates {\n" + " sorry\n" + "}", + "count(s(z), true)"), +]) +def test_where_operations_are_a_compile_error(tmp_path: Path, decl: str, + call: str) -> None: + from compiler import lower + from lsp.library import check_file + + src = tmp_path / "uses_where.pf" + src.write_text( + "union N { z s(N) }\n" + "fun operator < (a:N, b:N) { false }\n" + "concept WellFounded {\n" + " fun operator < : fn (T, T) -> bool\n" + " theorem strong_induction: all P: fn T -> bool, n:T.\n" + " if (all j:T. if (all i:T. if i < j then P(i)) then P(j))\n" + " then P(n)\n" + "}\n" + "postulate n_strong: all P: fn N -> bool, n:N.\n" + " if (all j:N. if (all i:N. if i < j then P(i)) then P(j))\n" + " then P(n)\n" + "model WellFounded {\n" + " fun operator < = operator <\n" + " theorem strong_induction = n_strong\n" + "}\n" + "concept Monoid {\n" + " fun operator+ : fn (T, T) -> T\n" + " fun zero : T\n" + "}\n" + "fun bor(a:bool, b:bool) { a or b }\n" + "model Monoid {\n" + " fun operator+ = bor\n" + " fun zero = false\n" + "}\n" + + decl + "\n" + "print " + call + "\n") + sys.argv = [str(ROOT / "deduce.py")] + result = check_file(str(src), prelude=[]) + assert result.ok, result.error_message + with pytest.raises(lower.CompileError, match="#1292"): + lower.lower_program(result.ast, main_module=src.stem)