diff --git a/abstract_syntax/declarations.py b/abstract_syntax/declarations.py index db562c70..46cfb756 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): @@ -1373,10 +1373,11 @@ 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` @@ -1407,7 +1408,15 @@ 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: @@ -1417,7 +1426,7 @@ def uniquify(self, env: object, ctx: object) -> GenRecFun: new_vars, new_returns, new_measure, new_measure_ty, new_body, new_terminates, self.trusted_terminates, visibility=self.visibility, - less=list(env_map.get('<', [])), where=where) + less=less, where=where) _exports_overload = True diff --git a/checker_concepts.py b/checker_concepts.py index 89143e80..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 @@ -411,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 96dfb050..15dce8b9 100644 --- a/checker_pipeline.py +++ b/checker_pipeline.py @@ -25,7 +25,7 @@ from checker_concepts import ( add_where_models, check_where, collect_model, model_obligations, - where_scope, + well_founded_less, where_scope, process_concept, process_model, ) from abstract_syntax import ( @@ -1013,11 +1013,7 @@ def process_declaration_visibility(decl: Declaration, env: Env, 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) - # 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 + check_type(measure_ty, body_env) return (decl, env.declare_term_var(loc, name, fun_type, visibility=decl.visibility)) @@ -2200,6 +2196,11 @@ def _check_proofs(stmt: Statement, env: Env) -> None: 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] = [] @@ -2208,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 diff --git a/compiler/lower.py b/compiler/lower.py index 42fbb24c..1435c4ee 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 diff --git a/gh_pages/doc/Reference.md b/gh_pages/doc/Reference.md index ecbfbbcb..1db485ea 100644 --- a/gh_pages/doc/Reference.md +++ b/gh_pages/doc/Reference.md @@ -2655,9 +2655,28 @@ 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 by `<` on `τ`, which must be - well-founded, so use `UInt` or `Nat`. Deduce doesn't check this yet - (issue #1308). + 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 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/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/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-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