| 1 | # Coercion |
| 2 | |
| 3 | The `coercion` app enables to program Coq coercions in Elpi. |
| 4 | |
| 5 | This app is experimental. |
| 6 | |
| 7 | ## The coercion predicate |
| 8 | |
| 9 | The `coercion` predicate lives in the database `coercion.db` |
| 10 | |
| 11 | ```elpi |
| 12 | % [coercion Ctx V Inferred Expected Res] is queried to cast V to Res |
| 13 | % - [Ctx] is the context |
| 14 | % - [V] is the value to be coerced |
| 15 | % - [Inferred] is the type of [V] |
| 16 | % - [Expected] is the type [V] should be coerced to |
| 17 | % - [Res] is the result (of type [Expected]) |
| 18 | pred coercion i:goal-ctx, i:term, i:term, i:term, o:term. |
| 19 | ``` |
| 20 | |
| 21 | By addings rules for this predicate one can recover from a type error, that is |
| 22 | when `Inferred` and `Expected` are not unifiable. |
| 23 | |
| 24 | ## Simple example of coercion |
| 25 | |
| 26 | This example maps `True : Prop` to `true : bool`, which is a function you |
| 27 | cannot express in type theory, hence in the standard Coercion system. |
| 28 | |
| 29 | ```coq |
| 30 | From elpi.apps Require Import coercion. |
| 31 | From Coq Require Import Bool. |
| 32 | |
| 33 | Elpi Accumulate coercion.db lp:{{ |
| 34 | |
| 35 | coercion _ {{ True }} {{ Prop }} {{ bool }} {{ true }}. |
| 36 | coercion _ {{ False }} {{ Prop }} {{ bool }} {{ false }}. |
| 37 | |
| 38 | }}. |
| 39 | |
| 40 | Check True && False. |
| 41 | ``` |
| 42 | |
| 43 | ## Example of coercion with proof automation |
| 44 | |
| 45 | This coercion enriches `x : T` to a `{x : T | P x}` by using |
| 46 | `my_solver` to prove `P x`. |
| 47 | |
| 48 | ```coq |
| 49 | From elpi.apps Require Import coercion. |
| 50 | From Coq Require Import Arith ssreflect. |
| 51 | |
| 52 | Ltac my_solver := trivial with arith. |
| 53 | |
| 54 | Elpi Accumulate coercion.db lp:{{ |
| 55 | |
| 56 | coercion _ X Ty {{ @sig lp:Ty lp:P }} Solution :- std.do! [ |
| 57 | % we unfold letins since the solver is dumb and the `as` in the second |
| 58 | % example introduces a letin |
| 59 | (pi a b b1\ copy a b :- def a _ _ b, copy b b1) => copy X X1, |
| 60 | % we build the solution |
| 61 | Solution = {{ @exist lp:Ty lp:P lp:X1 _ }}, |
| 62 | % we call the solver |
| 63 | coq.ltac.collect-goals Solution [G] [], |
| 64 | coq.ltac.open (x\y\coq.ltac.call-ltac1 "my_solver" x y ok) G [], |
| 65 | ]. |
| 66 | |
| 67 | }}. |
| 68 | Elpi Typecheck coercion. |
| 69 | |
| 70 | Goal {x : nat | x > 0}. |
| 71 | apply: 3. |
| 72 | Qed. |
| 73 | |
| 74 | Definition ensure_pos n : {x : nat | x > 0} := |
| 75 | match n with |
| 76 | | O => 1 |
| 77 | | S x as y => y |
| 78 | end. |
| 79 | ``` |