src/Pure/Proof/extraction.ML
author wenzelm
Wed Mar 25 16:54:49 2009 +0100 (2009-03-25)
changeset 30718 15041c7e51e4
parent 30528 7173bf123335
child 32032 a6a6e8031c14
permissions -rw-r--r--
Proofterm.approximate_proof_body;
berghofe@13402
     1
(*  Title:      Pure/Proof/extraction.ML
berghofe@13402
     2
    Author:     Stefan Berghofer, TU Muenchen
berghofe@13402
     3
berghofe@13402
     4
Extraction of programs from proofs.
berghofe@13402
     5
*)
berghofe@13402
     6
berghofe@13402
     7
signature EXTRACTION =
berghofe@13402
     8
sig
wenzelm@16458
     9
  val set_preprocessor : (theory -> Proofterm.proof -> Proofterm.proof) -> theory -> theory
berghofe@13402
    10
  val add_realizes_eqns_i : ((term * term) list * (term * term)) list -> theory -> theory
berghofe@13402
    11
  val add_realizes_eqns : string list -> theory -> theory
berghofe@13402
    12
  val add_typeof_eqns_i : ((term * term) list * (term * term)) list -> theory -> theory
berghofe@13402
    13
  val add_typeof_eqns : string list -> theory -> theory
berghofe@13402
    14
  val add_realizers_i : (string * (string list * term * Proofterm.proof)) list
berghofe@13402
    15
    -> theory -> theory
berghofe@13402
    16
  val add_realizers : (thm * (string list * string * string)) list
berghofe@13402
    17
    -> theory -> theory
berghofe@13402
    18
  val add_expand_thms : thm list -> theory -> theory
berghofe@13732
    19
  val add_types : (xstring * ((term -> term option) list *
berghofe@13732
    20
    (term -> typ -> term -> typ -> term) option)) list -> theory -> theory
berghofe@13732
    21
  val extract : (thm * string list) list -> theory -> theory
berghofe@13402
    22
  val nullT : typ
berghofe@13402
    23
  val nullt : term
berghofe@13714
    24
  val mk_typ : typ -> term
berghofe@13714
    25
  val etype_of : theory -> string list -> typ list -> term -> typ
berghofe@13714
    26
  val realizes_of: theory -> string list -> term -> term -> term
berghofe@13402
    27
end;
berghofe@13402
    28
berghofe@13402
    29
structure Extraction : EXTRACTION =
berghofe@13402
    30
struct
berghofe@13402
    31
berghofe@13402
    32
open Proofterm;
berghofe@13402
    33
berghofe@13402
    34
(**** tools ****)
berghofe@13402
    35
berghofe@13402
    36
fun add_syntax thy =
berghofe@13402
    37
  thy
berghofe@13402
    38
  |> Theory.copy
wenzelm@24712
    39
  |> Sign.root_path
wenzelm@30344
    40
  |> Sign.add_types [(Binding.name "Type", 0, NoSyn), (Binding.name "Null", 0, NoSyn)]
wenzelm@22796
    41
  |> Sign.add_consts
wenzelm@30344
    42
      [(Binding.name "typeof", "'b::{} => Type", NoSyn),
wenzelm@30344
    43
       (Binding.name "Type", "'a::{} itself => Type", NoSyn),
wenzelm@30344
    44
       (Binding.name "Null", "Null", NoSyn),
wenzelm@30344
    45
       (Binding.name "realizes", "'a::{} => 'b::{} => 'b", NoSyn)];
berghofe@13402
    46
berghofe@13402
    47
val nullT = Type ("Null", []);
berghofe@13402
    48
val nullt = Const ("Null", nullT);
berghofe@13402
    49
berghofe@13402
    50
fun mk_typ T =
wenzelm@19391
    51
  Const ("Type", Term.itselfT T --> Type ("Type", [])) $ Logic.mk_type T;
berghofe@13402
    52
berghofe@13402
    53
fun typeof_proc defaultS vs (Const ("typeof", _) $ u) =
skalberg@15531
    54
      SOME (mk_typ (case strip_comb u of
berghofe@13402
    55
          (Var ((a, i), _), _) =>
wenzelm@20664
    56
            if member (op =) vs a then TFree ("'" ^ a ^ ":" ^ string_of_int i, defaultS)
berghofe@13402
    57
            else nullT
berghofe@13402
    58
        | (Free (a, _), _) =>
wenzelm@20664
    59
            if member (op =) vs a then TFree ("'" ^ a, defaultS) else nullT
berghofe@13402
    60
        | _ => nullT))
skalberg@15531
    61
  | typeof_proc _ _ _ = NONE;
berghofe@13402
    62
skalberg@15531
    63
fun rlz_proc (Const ("realizes", Type (_, [Type ("Null", []), _])) $ r $ t) = SOME t
berghofe@13732
    64
  | rlz_proc (Const ("realizes", Type (_, [T, _])) $ r $ t) =
berghofe@13732
    65
      (case strip_comb t of
skalberg@15531
    66
         (Var (ixn, U), ts) => SOME (list_comb (Var (ixn, T --> U), r :: ts))
skalberg@15531
    67
       | (Free (s, U), ts) => SOME (list_comb (Free (s, T --> U), r :: ts))
skalberg@15531
    68
       | _ => NONE)
skalberg@15531
    69
  | rlz_proc _ = NONE;
berghofe@13402
    70
berghofe@13402
    71
val unpack_ixn = apfst implode o apsnd (fst o read_int o tl) o
wenzelm@28375
    72
  take_prefix (fn s => s <> ":") o explode;
berghofe@13402
    73
berghofe@13402
    74
type rules =
berghofe@13402
    75
  {next: int, rs: ((term * term) list * (term * term)) list,
berghofe@13402
    76
   net: (int * ((term * term) list * (term * term))) Net.net};
berghofe@13402
    77
berghofe@13402
    78
val empty_rules : rules = {next = 0, rs = [], net = Net.empty};
berghofe@13402
    79
berghofe@13402
    80
fun add_rule (r as (_, (lhs, _)), {next, rs, net} : rules) =
wenzelm@16800
    81
  {next = next - 1, rs = r :: rs, net = Net.insert_term (K false)
wenzelm@18956
    82
     (Envir.eta_contract lhs, (next, r)) net};
berghofe@13402
    83
berghofe@13417
    84
fun merge_rules
berghofe@13417
    85
  ({next, rs = rs1, net} : rules) ({next = next2, rs = rs2, ...} : rules) =
wenzelm@23178
    86
  List.foldr add_rule {next = next, rs = rs1, net = net} (subtract (op =) rs1 rs2);
berghofe@13402
    87
wenzelm@16458
    88
fun condrew thy rules procs =
berghofe@13402
    89
  let
berghofe@13402
    90
    fun rew tm =
wenzelm@17203
    91
      Pattern.rewrite_term thy [] (condrew' :: procs) tm
berghofe@15399
    92
    and condrew' tm =
berghofe@13402
    93
      let
berghofe@15399
    94
        val cache = ref ([] : (term * term) list);
haftmann@17232
    95
        fun lookup f x = (case AList.lookup (op =) (!cache) x of
skalberg@15531
    96
            NONE =>
berghofe@15399
    97
              let val y = f x
berghofe@15399
    98
              in (cache := (x, y) :: !cache; y) end
skalberg@15531
    99
          | SOME y => y);
berghofe@15399
   100
      in
berghofe@15399
   101
        get_first (fn (_, (prems, (tm1, tm2))) =>
berghofe@15399
   102
        let
wenzelm@19466
   103
          fun ren t = the_default t (Term.rename_abs tm1 tm t);
berghofe@15399
   104
          val inc = Logic.incr_indexes ([], maxidx_of_term tm + 1);
wenzelm@18184
   105
          val env as (Tenv, tenv) = Pattern.match thy (inc tm1, tm) (Vartab.empty, Vartab.empty);
berghofe@15798
   106
          val prems' = map (pairself (Envir.subst_vars env o inc o ren)) prems;
berghofe@15399
   107
          val env' = Envir.Envir
skalberg@15570
   108
            {maxidx = Library.foldl Int.max
berghofe@15399
   109
              (~1, map (Int.max o pairself maxidx_of_term) prems'),
berghofe@15798
   110
             iTs = Tenv, asol = tenv};
wenzelm@18184
   111
          val env'' = fold (Pattern.unify thy o pairself (lookup rew)) prems' env';
skalberg@15531
   112
        in SOME (Envir.norm_term env'' (inc (ren tm2)))
skalberg@15531
   113
        end handle Pattern.MATCH => NONE | Pattern.Unif => NONE)
wenzelm@16486
   114
          (sort (int_ord o pairself fst)
wenzelm@18956
   115
            (Net.match_term rules (Envir.eta_contract tm)))
berghofe@15399
   116
      end;
berghofe@13402
   117
berghofe@13402
   118
  in rew end;
berghofe@13402
   119
skalberg@15531
   120
val chtype = change_type o SOME;
berghofe@13402
   121
wenzelm@30364
   122
fun extr_name s vs = Long_Name.append "extr" (space_implode "_" (s :: vs));
wenzelm@16195
   123
fun corr_name s vs = extr_name s vs ^ "_correctness";
berghofe@13402
   124
wenzelm@16195
   125
fun msg d s = priority (Symbol.spaces d ^ s);
berghofe@13402
   126
berghofe@28812
   127
fun vars_of t = map Var (rev (Term.add_vars t []));
berghofe@28812
   128
fun frees_of t = map Free (rev (Term.add_frees t []));
berghofe@28812
   129
fun vfs_of t = vars_of t @ frees_of t;
berghofe@13402
   130
berghofe@13402
   131
fun forall_intr_prf (t, prf) =
berghofe@13402
   132
  let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
skalberg@15531
   133
  in Abst (a, SOME T, prf_abstract_over t prf) end;
berghofe@13402
   134
wenzelm@23178
   135
val mkabs = List.foldr (fn (v, t) => Abs ("x", fastype_of v, abstract_over (v, t)));
berghofe@13402
   136
berghofe@13732
   137
fun strip_abs 0 t = t
berghofe@13732
   138
  | strip_abs n (Abs (_, _, t)) = strip_abs (n-1) t
berghofe@13732
   139
  | strip_abs _ _ = error "strip_abs: not an abstraction";
berghofe@13732
   140
berghofe@13402
   141
fun prf_subst_TVars tye =
berghofe@13402
   142
  map_proof_terms (subst_TVars tye) (typ_subst_TVars tye);
berghofe@13402
   143
wenzelm@23178
   144
fun relevant_vars types prop = List.foldr (fn
berghofe@13402
   145
      (Var ((a, i), T), vs) => (case strip_type T of
wenzelm@20664
   146
        (_, Type (s, _)) => if member (op =) types s then a :: vs else vs
berghofe@13402
   147
      | _ => vs)
skalberg@15574
   148
    | (_, vs) => vs) [] (vars_of prop);
berghofe@13402
   149
berghofe@13732
   150
fun tname_of (Type (s, _)) = s
berghofe@13732
   151
  | tname_of _ = "";
berghofe@13732
   152
berghofe@13732
   153
fun get_var_type t =
berghofe@13732
   154
  let
wenzelm@16865
   155
    val vs = Term.add_vars t [];
wenzelm@16865
   156
    val fs = Term.add_frees t [];
berghofe@13732
   157
  in fn 
haftmann@17232
   158
      Var (ixn, _) => (case AList.lookup (op =) vs ixn of
skalberg@15531
   159
          NONE => error "get_var_type: no such variable in term"
skalberg@15531
   160
        | SOME T => Var (ixn, T))
haftmann@17232
   161
    | Free (s, _) => (case AList.lookup (op =) fs s of
skalberg@15531
   162
          NONE => error "get_var_type: no such variable in term"
skalberg@15531
   163
        | SOME T => Free (s, T))
berghofe@13732
   164
    | _ => error "get_var_type: not a variable"
berghofe@13732
   165
  end;
berghofe@13732
   166
berghofe@13402
   167
berghofe@13402
   168
(**** theory data ****)
berghofe@13402
   169
wenzelm@22846
   170
(* theory data *)
berghofe@13402
   171
wenzelm@16458
   172
structure ExtractionData = TheoryDataFun
wenzelm@22846
   173
(
berghofe@13402
   174
  type T =
berghofe@13402
   175
    {realizes_eqns : rules,
berghofe@13402
   176
     typeof_eqns : rules,
berghofe@13732
   177
     types : (string * ((term -> term option) list *
berghofe@13732
   178
       (term -> typ -> term -> typ -> term) option)) list,
berghofe@13402
   179
     realizers : (string list * (term * proof)) list Symtab.table,
berghofe@13402
   180
     defs : thm list,
berghofe@13402
   181
     expand : (string * term) list,
wenzelm@16458
   182
     prep : (theory -> proof -> proof) option}
berghofe@13402
   183
berghofe@13402
   184
  val empty =
berghofe@13402
   185
    {realizes_eqns = empty_rules,
berghofe@13402
   186
     typeof_eqns = empty_rules,
berghofe@13402
   187
     types = [],
berghofe@13402
   188
     realizers = Symtab.empty,
berghofe@13402
   189
     defs = [],
berghofe@13402
   190
     expand = [],
skalberg@15531
   191
     prep = NONE};
berghofe@13402
   192
  val copy = I;
wenzelm@16458
   193
  val extend = I;
berghofe@13402
   194
wenzelm@16458
   195
  fun merge _
berghofe@13402
   196
    (({realizes_eqns = realizes_eqns1, typeof_eqns = typeof_eqns1, types = types1,
berghofe@13402
   197
       realizers = realizers1, defs = defs1, expand = expand1, prep = prep1},
berghofe@13402
   198
      {realizes_eqns = realizes_eqns2, typeof_eqns = typeof_eqns2, types = types2,
berghofe@13402
   199
       realizers = realizers2, defs = defs2, expand = expand2, prep = prep2}) : T * T) =
berghofe@13402
   200
    {realizes_eqns = merge_rules realizes_eqns1 realizes_eqns2,
berghofe@13402
   201
     typeof_eqns = merge_rules typeof_eqns1 typeof_eqns2,
haftmann@22717
   202
     types = AList.merge (op =) (K true) (types1, types2),
wenzelm@19305
   203
     realizers = Symtab.merge_list (gen_eq_set (op =) o pairself #1) (realizers1, realizers2),
haftmann@22662
   204
     defs = Library.merge Thm.eq_thm (defs1, defs2),
haftmann@22662
   205
     expand = Library.merge (op =) (expand1, expand2),
skalberg@15531
   206
     prep = (case prep1 of NONE => prep2 | _ => prep1)};
wenzelm@22846
   207
);
berghofe@13402
   208
berghofe@13402
   209
fun read_condeq thy =
wenzelm@16458
   210
  let val thy' = add_syntax thy
berghofe@13402
   211
  in fn s =>
wenzelm@24707
   212
    let val t = Logic.varify (Syntax.read_prop_global thy' s)
berghofe@13402
   213
    in (map Logic.dest_equals (Logic.strip_imp_prems t),
berghofe@13402
   214
      Logic.dest_equals (Logic.strip_imp_concl t))
berghofe@13402
   215
    end handle TERM _ => error ("Not a (conditional) meta equality:\n" ^ s)
berghofe@13402
   216
  end;
berghofe@13402
   217
berghofe@13402
   218
(** preprocessor **)
berghofe@13402
   219
berghofe@13402
   220
fun set_preprocessor prep thy =
berghofe@13402
   221
  let val {realizes_eqns, typeof_eqns, types, realizers,
berghofe@13402
   222
    defs, expand, ...} = ExtractionData.get thy
berghofe@13402
   223
  in
berghofe@13402
   224
    ExtractionData.put
berghofe@13402
   225
      {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
skalberg@15531
   226
       realizers = realizers, defs = defs, expand = expand, prep = SOME prep} thy
berghofe@13402
   227
  end;
berghofe@13402
   228
berghofe@13402
   229
(** equations characterizing realizability **)
berghofe@13402
   230
berghofe@13402
   231
fun gen_add_realizes_eqns prep_eq eqns thy =
berghofe@13402
   232
  let val {realizes_eqns, typeof_eqns, types, realizers,
berghofe@13402
   233
    defs, expand, prep} = ExtractionData.get thy;
berghofe@13402
   234
  in
berghofe@13402
   235
    ExtractionData.put
wenzelm@23178
   236
      {realizes_eqns = List.foldr add_rule realizes_eqns (map (prep_eq thy) eqns),
berghofe@13402
   237
       typeof_eqns = typeof_eqns, types = types, realizers = realizers,
berghofe@13402
   238
       defs = defs, expand = expand, prep = prep} thy
berghofe@13402
   239
  end
berghofe@13402
   240
berghofe@13402
   241
val add_realizes_eqns_i = gen_add_realizes_eqns (K I);
berghofe@13402
   242
val add_realizes_eqns = gen_add_realizes_eqns read_condeq;
berghofe@13402
   243
berghofe@13402
   244
(** equations characterizing type of extracted program **)
berghofe@13402
   245
berghofe@13402
   246
fun gen_add_typeof_eqns prep_eq eqns thy =
berghofe@13402
   247
  let
berghofe@13402
   248
    val {realizes_eqns, typeof_eqns, types, realizers,
berghofe@13402
   249
      defs, expand, prep} = ExtractionData.get thy;
berghofe@13732
   250
    val eqns' = map (prep_eq thy) eqns
berghofe@13402
   251
  in
berghofe@13402
   252
    ExtractionData.put
berghofe@13402
   253
      {realizes_eqns = realizes_eqns, realizers = realizers,
wenzelm@23178
   254
       typeof_eqns = List.foldr add_rule typeof_eqns eqns',
berghofe@13732
   255
       types = types, defs = defs, expand = expand, prep = prep} thy
berghofe@13402
   256
  end
berghofe@13402
   257
berghofe@13402
   258
val add_typeof_eqns_i = gen_add_typeof_eqns (K I);
berghofe@13402
   259
val add_typeof_eqns = gen_add_typeof_eqns read_condeq;
berghofe@13402
   260
berghofe@13402
   261
fun thaw (T as TFree (a, S)) =
wenzelm@28375
   262
      if exists_string (fn s => s = ":") a then TVar (unpack_ixn a, S) else T
berghofe@13402
   263
  | thaw (Type (a, Ts)) = Type (a, map thaw Ts)
berghofe@13402
   264
  | thaw T = T;
berghofe@13402
   265
berghofe@13402
   266
fun freeze (TVar ((a, i), S)) = TFree (a ^ ":" ^ string_of_int i, S)
berghofe@13402
   267
  | freeze (Type (a, Ts)) = Type (a, map freeze Ts)
berghofe@13402
   268
  | freeze T = T;
berghofe@13402
   269
berghofe@13402
   270
fun freeze_thaw f x =
wenzelm@20548
   271
  map_types thaw (f (map_types freeze x));
berghofe@13402
   272
wenzelm@16458
   273
fun etype_of thy vs Ts t =
berghofe@13402
   274
  let
wenzelm@16458
   275
    val {typeof_eqns, ...} = ExtractionData.get thy;
berghofe@13402
   276
    fun err () = error ("Unable to determine type of extracted program for\n" ^
wenzelm@26939
   277
      Syntax.string_of_term_global thy t)
wenzelm@16458
   278
  in case strip_abs_body (freeze_thaw (condrew thy (#net typeof_eqns)
wenzelm@16458
   279
    [typeof_proc (Sign.defaultS thy) vs]) (list_abs (map (pair "x") (rev Ts),
berghofe@13402
   280
      Const ("typeof", fastype_of1 (Ts, t) --> Type ("Type", [])) $ t))) of
berghofe@13402
   281
      Const ("Type", _) $ u => (Logic.dest_type u handle TERM _ => err ())
berghofe@13402
   282
    | _ => err ()
berghofe@13402
   283
  end;
berghofe@13402
   284
berghofe@13402
   285
(** realizers for axioms / theorems, together with correctness proofs **)
berghofe@13402
   286
berghofe@13402
   287
fun gen_add_realizers prep_rlz rs thy =
berghofe@13402
   288
  let val {realizes_eqns, typeof_eqns, types, realizers,
berghofe@13402
   289
    defs, expand, prep} = ExtractionData.get thy
berghofe@13402
   290
  in
berghofe@13402
   291
    ExtractionData.put
berghofe@13402
   292
      {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
wenzelm@25389
   293
       realizers = fold (Symtab.cons_list o prep_rlz thy) rs realizers,
berghofe@13402
   294
       defs = defs, expand = expand, prep = prep} thy
berghofe@13402
   295
  end
berghofe@13402
   296
berghofe@13402
   297
fun prep_realizer thy =
berghofe@13402
   298
  let
berghofe@13732
   299
    val {realizes_eqns, typeof_eqns, defs, types, ...} =
berghofe@13402
   300
      ExtractionData.get thy;
wenzelm@19482
   301
    val procs = maps (fst o snd) types;
berghofe@13732
   302
    val rtypes = map fst types;
wenzelm@16800
   303
    val eqns = Net.merge (K false) (#net realizes_eqns, #net typeof_eqns);
berghofe@13402
   304
    val thy' = add_syntax thy;
berghofe@13402
   305
    val rd = ProofSyntax.read_proof thy' false
berghofe@13402
   306
  in fn (thm, (vs, s1, s2)) =>
berghofe@13402
   307
    let
wenzelm@21646
   308
      val name = Thm.get_name thm;
wenzelm@21858
   309
      val _ = name <> "" orelse error "add_realizers: unnamed theorem";
wenzelm@17203
   310
      val prop = Pattern.rewrite_term thy'
berghofe@13402
   311
        (map (Logic.dest_equals o prop_of) defs) [] (prop_of thm);
berghofe@13402
   312
      val vars = vars_of prop;
berghofe@13732
   313
      val vars' = filter_out (fn v =>
wenzelm@20664
   314
        member (op =) rtypes (tname_of (body_type (fastype_of v)))) vars;
wenzelm@16458
   315
      val T = etype_of thy' vs [] prop;
berghofe@13402
   316
      val (T', thw) = Type.freeze_thaw_type
berghofe@13732
   317
        (if T = nullT then nullT else map fastype_of vars' ---> T);
wenzelm@27251
   318
      val t = map_types thw (OldGoals.simple_read_term thy' T' s1);
wenzelm@16458
   319
      val r' = freeze_thaw (condrew thy' eqns
wenzelm@16458
   320
        (procs @ [typeof_proc (Sign.defaultS thy') vs, rlz_proc]))
berghofe@13402
   321
          (Const ("realizes", T --> propT --> propT) $
berghofe@13732
   322
            (if T = nullT then t else list_comb (t, vars')) $ prop);
wenzelm@27330
   323
      val r = fold_rev Logic.all (map (get_var_type r') vars) r';
wenzelm@16458
   324
      val prf = Reconstruct.reconstruct_proof thy' r (rd s2);
berghofe@13402
   325
    in (name, (vs, (t, prf))) end
berghofe@13402
   326
  end;
berghofe@13402
   327
berghofe@13402
   328
val add_realizers_i = gen_add_realizers
berghofe@13402
   329
  (fn _ => fn (name, (vs, t, prf)) => (name, (vs, (t, prf))));
berghofe@13402
   330
val add_realizers = gen_add_realizers prep_realizer;
berghofe@13402
   331
berghofe@13714
   332
fun realizes_of thy vs t prop =
berghofe@13714
   333
  let
berghofe@13714
   334
    val thy' = add_syntax thy;
berghofe@13732
   335
    val {realizes_eqns, typeof_eqns, defs, types, ...} =
berghofe@13714
   336
      ExtractionData.get thy';
haftmann@22717
   337
    val procs = maps (rev o fst o snd) types;
wenzelm@16800
   338
    val eqns = Net.merge (K false) (#net realizes_eqns, #net typeof_eqns);
wenzelm@17203
   339
    val prop' = Pattern.rewrite_term thy'
berghofe@13714
   340
      (map (Logic.dest_equals o prop_of) defs) [] prop;
wenzelm@16458
   341
  in freeze_thaw (condrew thy' eqns
wenzelm@16458
   342
    (procs @ [typeof_proc (Sign.defaultS thy') vs, rlz_proc]))
berghofe@13714
   343
      (Const ("realizes", fastype_of t --> propT --> propT) $ t $ prop')
berghofe@13714
   344
  end;
berghofe@13714
   345
berghofe@13402
   346
(** expanding theorems / definitions **)
berghofe@13402
   347
wenzelm@18728
   348
fun add_expand_thm thm thy =
berghofe@13402
   349
  let
berghofe@13402
   350
    val {realizes_eqns, typeof_eqns, types, realizers,
berghofe@13402
   351
      defs, expand, prep} = ExtractionData.get thy;
berghofe@13402
   352
wenzelm@21646
   353
    val name = Thm.get_name thm;
wenzelm@21858
   354
    val _ = name <> "" orelse error "add_expand_thms: unnamed theorem";
berghofe@13402
   355
berghofe@13402
   356
    val is_def =
berghofe@13402
   357
      (case strip_comb (fst (Logic.dest_equals (prop_of thm))) of
haftmann@18928
   358
         (Const _, ts) => forall is_Var ts andalso not (has_duplicates (op =) ts)
wenzelm@28674
   359
           andalso (Thm.get_kind thm = Thm.definitionK orelse can (Thm.axiom thy) name)
berghofe@13402
   360
       | _ => false) handle TERM _ => false;
berghofe@13402
   361
  in
berghofe@13402
   362
    (ExtractionData.put (if is_def then
berghofe@13402
   363
        {realizes_eqns = realizes_eqns,
berghofe@13402
   364
         typeof_eqns = add_rule (([],
berghofe@13402
   365
           Logic.dest_equals (prop_of (Drule.abs_def thm))), typeof_eqns),
berghofe@13402
   366
         types = types,
wenzelm@22360
   367
         realizers = realizers, defs = insert Thm.eq_thm thm defs,
berghofe@13402
   368
         expand = expand, prep = prep}
berghofe@13402
   369
      else
berghofe@13402
   370
        {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
berghofe@13402
   371
         realizers = realizers, defs = defs,
haftmann@20854
   372
         expand = insert (op =) (name, prop_of thm) expand, prep = prep}) thy)
berghofe@13402
   373
  end;
berghofe@13402
   374
wenzelm@18728
   375
val add_expand_thms = fold add_expand_thm;
wenzelm@18728
   376
wenzelm@30528
   377
val extraction_expand = Thm.declaration_attribute (fn th => Context.mapping (add_expand_thm th) I);
berghofe@13402
   378
wenzelm@15801
   379
berghofe@13732
   380
(** types with computational content **)
berghofe@13732
   381
berghofe@13732
   382
fun add_types tys thy =
haftmann@22717
   383
  ExtractionData.map
haftmann@22717
   384
    (fn {realizes_eqns, typeof_eqns, types, realizers, defs, expand, prep} =>
berghofe@13732
   385
      {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns,
haftmann@22717
   386
       types = fold (AList.update (op =) o apfst (Sign.intern_type thy)) tys types,
haftmann@22717
   387
       realizers = realizers, defs = defs, expand = expand, prep = prep})
haftmann@22717
   388
    thy;
berghofe@13732
   389
berghofe@13402
   390
wenzelm@15801
   391
(** Pure setup **)
wenzelm@15801
   392
wenzelm@26463
   393
val _ = Context.>> (Context.map_theory
wenzelm@18708
   394
  (add_types [("prop", ([], NONE))] #>
wenzelm@15801
   395
wenzelm@15801
   396
   add_typeof_eqns
wenzelm@15801
   397
     ["(typeof (PROP P)) == (Type (TYPE(Null))) ==>  \
wenzelm@15801
   398
    \  (typeof (PROP Q)) == (Type (TYPE('Q))) ==>  \
wenzelm@15801
   399
    \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE('Q)))",
wenzelm@15801
   400
wenzelm@15801
   401
      "(typeof (PROP Q)) == (Type (TYPE(Null))) ==>  \
wenzelm@15801
   402
    \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE(Null)))",
wenzelm@15801
   403
wenzelm@15801
   404
      "(typeof (PROP P)) == (Type (TYPE('P))) ==>  \
wenzelm@15801
   405
    \  (typeof (PROP Q)) == (Type (TYPE('Q))) ==>  \
wenzelm@15801
   406
    \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE('P => 'Q)))",
wenzelm@15801
   407
wenzelm@15801
   408
      "(%x. typeof (PROP P (x))) == (%x. Type (TYPE(Null))) ==>  \
wenzelm@15801
   409
    \    (typeof (!!x. PROP P (x))) == (Type (TYPE(Null)))",
wenzelm@15801
   410
wenzelm@15801
   411
      "(%x. typeof (PROP P (x))) == (%x. Type (TYPE('P))) ==>  \
wenzelm@15801
   412
    \    (typeof (!!x::'a. PROP P (x))) == (Type (TYPE('a => 'P)))",
wenzelm@15801
   413
wenzelm@15801
   414
      "(%x. typeof (f (x))) == (%x. Type (TYPE('f))) ==>  \
wenzelm@18708
   415
    \    (typeof (f)) == (Type (TYPE('f)))"] #>
wenzelm@15801
   416
wenzelm@15801
   417
   add_realizes_eqns
wenzelm@15801
   418
     ["(typeof (PROP P)) == (Type (TYPE(Null))) ==>  \
wenzelm@15801
   419
    \    (realizes (r) (PROP P ==> PROP Q)) ==  \
wenzelm@15801
   420
    \    (PROP realizes (Null) (PROP P) ==> PROP realizes (r) (PROP Q))",
wenzelm@15801
   421
wenzelm@15801
   422
      "(typeof (PROP P)) == (Type (TYPE('P))) ==>  \
wenzelm@15801
   423
    \  (typeof (PROP Q)) == (Type (TYPE(Null))) ==>  \
wenzelm@15801
   424
    \    (realizes (r) (PROP P ==> PROP Q)) ==  \
wenzelm@15801
   425
    \    (!!x::'P. PROP realizes (x) (PROP P) ==> PROP realizes (Null) (PROP Q))",
wenzelm@15801
   426
wenzelm@15801
   427
      "(realizes (r) (PROP P ==> PROP Q)) ==  \
wenzelm@15801
   428
    \  (!!x. PROP realizes (x) (PROP P) ==> PROP realizes (r (x)) (PROP Q))",
wenzelm@15801
   429
wenzelm@15801
   430
      "(%x. typeof (PROP P (x))) == (%x. Type (TYPE(Null))) ==>  \
wenzelm@15801
   431
    \    (realizes (r) (!!x. PROP P (x))) ==  \
wenzelm@15801
   432
    \    (!!x. PROP realizes (Null) (PROP P (x)))",
wenzelm@15801
   433
wenzelm@15801
   434
      "(realizes (r) (!!x. PROP P (x))) ==  \
wenzelm@18708
   435
    \  (!!x. PROP realizes (r (x)) (PROP P (x)))"] #>
wenzelm@15801
   436
wenzelm@30528
   437
   Attrib.setup (Binding.name "extraction_expand") (Scan.succeed extraction_expand)
wenzelm@30528
   438
     "specify theorems / definitions to be expanded during extraction"));
wenzelm@15801
   439
wenzelm@15801
   440
berghofe@13402
   441
(**** extract program ****)
berghofe@13402
   442
berghofe@13402
   443
val dummyt = Const ("dummy", dummyT);
berghofe@13402
   444
berghofe@13402
   445
fun extract thms thy =
berghofe@13402
   446
  let
wenzelm@16458
   447
    val thy' = add_syntax thy;
berghofe@13402
   448
    val {realizes_eqns, typeof_eqns, types, realizers, defs, expand, prep} =
berghofe@13402
   449
      ExtractionData.get thy;
haftmann@22717
   450
    val procs = maps (rev o fst o snd) types;
berghofe@13732
   451
    val rtypes = map fst types;
wenzelm@16458
   452
    val typroc = typeof_proc (Sign.defaultS thy');
wenzelm@19466
   453
    val prep = the_default (K I) prep thy' o ProofRewriteRules.elim_defs thy' false defs o
wenzelm@16458
   454
      Reconstruct.expand_proof thy' (("", NONE) :: map (apsnd SOME) expand);
wenzelm@16800
   455
    val rrews = Net.merge (K false) (#net realizes_eqns, #net typeof_eqns);
berghofe@13402
   456
berghofe@13402
   457
    fun find_inst prop Ts ts vs =
berghofe@13402
   458
      let
berghofe@13732
   459
        val rvs = relevant_vars rtypes prop;
berghofe@13402
   460
        val vars = vars_of prop;
berghofe@13402
   461
        val n = Int.min (length vars, length ts);
berghofe@13402
   462
berghofe@13402
   463
        fun add_args ((Var ((a, i), _), t), (vs', tye)) =
wenzelm@20664
   464
          if member (op =) rvs a then
wenzelm@16458
   465
            let val T = etype_of thy' vs Ts t
berghofe@13402
   466
            in if T = nullT then (vs', tye)
berghofe@13402
   467
               else (a :: vs', (("'" ^ a, i), T) :: tye)
berghofe@13402
   468
            end
berghofe@13402
   469
          else (vs', tye)
berghofe@13402
   470
wenzelm@23178
   471
      in List.foldr add_args ([], []) (Library.take (n, vars) ~~ Library.take (n, ts)) end;
berghofe@13402
   472
wenzelm@20664
   473
    fun find (vs: string list) = Option.map snd o find_first (curry (gen_eq_set (op =)) vs o fst);
wenzelm@28375
   474
    fun find' (s: string) = map_filter (fn (s', x) => if s = s' then SOME x else NONE);
berghofe@13402
   475
berghofe@13732
   476
    fun app_rlz_rews Ts vs t = strip_abs (length Ts) (freeze_thaw
wenzelm@16458
   477
      (condrew thy' rrews (procs @ [typroc vs, rlz_proc])) (list_abs
berghofe@13732
   478
        (map (pair "x") (rev Ts), t)));
berghofe@13732
   479
berghofe@13732
   480
    fun realizes_null vs prop = app_rlz_rews [] vs
berghofe@13732
   481
      (Const ("realizes", nullT --> propT --> propT) $ nullt $ prop);
berghofe@13402
   482
berghofe@13402
   483
    fun corr d defs vs ts Ts hs (PBound i) _ _ = (defs, PBound i)
berghofe@13402
   484
skalberg@15531
   485
      | corr d defs vs ts Ts hs (Abst (s, SOME T, prf)) (Abst (_, _, prf')) t =
berghofe@13402
   486
          let val (defs', corr_prf) = corr d defs vs [] (T :: Ts)
berghofe@13402
   487
            (dummyt :: hs) prf (incr_pboundvars 1 0 prf')
skalberg@15531
   488
            (case t of SOME (Abs (_, _, u)) => SOME u | _ => NONE)
skalberg@15531
   489
          in (defs', Abst (s, SOME T, corr_prf)) end
berghofe@13402
   490
skalberg@15531
   491
      | corr d defs vs ts Ts hs (AbsP (s, SOME prop, prf)) (AbsP (_, _, prf')) t =
berghofe@13402
   492
          let
wenzelm@16458
   493
            val T = etype_of thy' vs Ts prop;
berghofe@13402
   494
            val u = if T = nullT then 
skalberg@15531
   495
                (case t of SOME u => SOME (incr_boundvars 1 u) | NONE => NONE)
skalberg@15531
   496
              else (case t of SOME (Abs (_, _, u)) => SOME u | _ => NONE);
berghofe@13402
   497
            val (defs', corr_prf) = corr d defs vs [] (T :: Ts) (prop :: hs)
berghofe@13402
   498
              (incr_pboundvars 0 1 prf) (incr_pboundvars 0 1 prf') u;
berghofe@13402
   499
            val rlz = Const ("realizes", T --> propT --> propT)
berghofe@13402
   500
          in (defs',
berghofe@13732
   501
            if T = nullT then AbsP ("R",
skalberg@15531
   502
              SOME (app_rlz_rews Ts vs (rlz $ nullt $ prop)),
berghofe@13732
   503
                prf_subst_bounds [nullt] corr_prf)
skalberg@15531
   504
            else Abst (s, SOME T, AbsP ("R",
skalberg@15531
   505
              SOME (app_rlz_rews (T :: Ts) vs
berghofe@13732
   506
                (rlz $ Bound 0 $ incr_boundvars 1 prop)), corr_prf)))
berghofe@13402
   507
          end
berghofe@13402
   508
skalberg@15531
   509
      | corr d defs vs ts Ts hs (prf % SOME t) (prf' % _) t' =
berghofe@13732
   510
          let
berghofe@13732
   511
            val (Us, T) = strip_type (fastype_of1 (Ts, t));
berghofe@13732
   512
            val (defs', corr_prf) = corr d defs vs (t :: ts) Ts hs prf prf'
wenzelm@20664
   513
              (if member (op =) rtypes (tname_of T) then t'
skalberg@15531
   514
               else (case t' of SOME (u $ _) => SOME u | _ => NONE));
wenzelm@20664
   515
            val u = if not (member (op =) rtypes (tname_of T)) then t else
berghofe@13732
   516
              let
wenzelm@16458
   517
                val eT = etype_of thy' vs Ts t;
berghofe@13732
   518
                val (r, Us') = if eT = nullT then (nullt, Us) else
berghofe@13732
   519
                  (Bound (length Us), eT :: Us);
berghofe@13732
   520
                val u = list_comb (incr_boundvars (length Us') t,
berghofe@13732
   521
                  map Bound (length Us - 1 downto 0));
haftmann@17271
   522
                val u' = (case AList.lookup (op =) types (tname_of T) of
skalberg@15531
   523
                    SOME ((_, SOME f)) => f r eT u T
berghofe@13732
   524
                  | _ => Const ("realizes", eT --> T --> T) $ r $ u)
berghofe@13732
   525
              in app_rlz_rews Ts vs (list_abs (map (pair "x") Us', u')) end
skalberg@15531
   526
          in (defs', corr_prf % SOME u) end
berghofe@13402
   527
berghofe@13402
   528
      | corr d defs vs ts Ts hs (prf1 %% prf2) (prf1' %% prf2') t =
berghofe@13402
   529
          let
berghofe@13402
   530
            val prop = Reconstruct.prop_of' hs prf2';
wenzelm@16458
   531
            val T = etype_of thy' vs Ts prop;
skalberg@15531
   532
            val (defs1, f, u) = if T = nullT then (defs, t, NONE) else
berghofe@13402
   533
              (case t of
skalberg@15531
   534
                 SOME (f $ u) => (defs, SOME f, SOME u)
berghofe@13402
   535
               | _ =>
berghofe@13402
   536
                 let val (defs1, u) = extr d defs vs [] Ts hs prf2'
skalberg@15531
   537
                 in (defs1, NONE, SOME u) end)
berghofe@13402
   538
            val (defs2, corr_prf1) = corr d defs1 vs [] Ts hs prf1 prf1' f;
berghofe@13402
   539
            val (defs3, corr_prf2) = corr d defs2 vs [] Ts hs prf2 prf2' u;
berghofe@13402
   540
          in
berghofe@13402
   541
            if T = nullT then (defs3, corr_prf1 %% corr_prf2) else
berghofe@13402
   542
              (defs3, corr_prf1 % u %% corr_prf2)
berghofe@13402
   543
          end
berghofe@13402
   544
wenzelm@28805
   545
      | corr d defs vs ts Ts hs (prf0 as PThm (_, ((name, prop, SOME Ts'), body))) _ _ =
berghofe@13402
   546
          let
wenzelm@29635
   547
            val prf = join_proof body;
berghofe@13402
   548
            val (vs', tye) = find_inst prop Ts ts vs;
wenzelm@29270
   549
            val tye' = (map fst (OldTerm.term_tvars prop) ~~ Ts') @ tye;
wenzelm@16458
   550
            val T = etype_of thy' vs' [] prop;
berghofe@13402
   551
            val defs' = if T = nullT then defs
berghofe@13402
   552
              else fst (extr d defs vs ts Ts hs prf0)
berghofe@13402
   553
          in
berghofe@13609
   554
            if T = nullT andalso realizes_null vs' prop aconv prop then (defs, prf0)
wenzelm@17412
   555
            else case Symtab.lookup realizers name of
skalberg@15531
   556
              NONE => (case find vs' (find' name defs') of
skalberg@15531
   557
                NONE =>
berghofe@13402
   558
                  let
wenzelm@21858
   559
                    val _ = T = nullT orelse error "corr: internal error";
berghofe@13402
   560
                    val _ = msg d ("Building correctness proof for " ^ quote name ^
berghofe@13402
   561
                      (if null vs' then ""
berghofe@13402
   562
                       else " (relevant variables: " ^ commas_quote vs' ^ ")"));
wenzelm@16458
   563
                    val prf' = prep (Reconstruct.reconstruct_proof thy' prop prf);
berghofe@13402
   564
                    val (defs'', corr_prf) =
skalberg@15531
   565
                      corr (d + 1) defs' vs' [] [] [] prf' prf' NONE;
berghofe@13732
   566
                    val corr_prop = Reconstruct.prop_of corr_prf;
wenzelm@23178
   567
                    val corr_prf' = List.foldr forall_intr_prf
skalberg@15574
   568
                      (proof_combt
wenzelm@28805
   569
                         (PThm (serial (),
wenzelm@29270
   570
                          ((corr_name name vs', corr_prop, SOME (map TVar (OldTerm.term_tvars corr_prop))),
wenzelm@30718
   571
                            Future.value (approximate_proof_body corr_prf))), vfs_of corr_prop))
haftmann@22750
   572
                      (map (get_var_type corr_prop) (vfs_of prop))
berghofe@13402
   573
                  in
berghofe@13732
   574
                    ((name, (vs', ((nullt, nullt), (corr_prf, corr_prf')))) :: defs'',
berghofe@13402
   575
                     prf_subst_TVars tye' corr_prf')
berghofe@13402
   576
                  end
skalberg@15531
   577
              | SOME (_, (_, prf')) => (defs', prf_subst_TVars tye' prf'))
skalberg@15531
   578
            | SOME rs => (case find vs' rs of
skalberg@15531
   579
                SOME (_, prf') => (defs', prf_subst_TVars tye' prf')
skalberg@15531
   580
              | NONE => error ("corr: no realizer for instance of theorem " ^
wenzelm@26939
   581
                  quote name ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
berghofe@13402
   582
                    (Reconstruct.prop_of (proof_combt (prf0, ts))))))
berghofe@13402
   583
          end
berghofe@13402
   584
skalberg@15531
   585
      | corr d defs vs ts Ts hs (prf0 as PAxm (s, prop, SOME Ts')) _ _ =
berghofe@13402
   586
          let
berghofe@13402
   587
            val (vs', tye) = find_inst prop Ts ts vs;
wenzelm@29270
   588
            val tye' = (map fst (OldTerm.term_tvars prop) ~~ Ts') @ tye
berghofe@13402
   589
          in
wenzelm@16458
   590
            if etype_of thy' vs' [] prop = nullT andalso
berghofe@13609
   591
              realizes_null vs' prop aconv prop then (defs, prf0)
wenzelm@18956
   592
            else case find vs' (Symtab.lookup_list realizers s) of
skalberg@15531
   593
              SOME (_, prf) => (defs, prf_subst_TVars tye' prf)
skalberg@15531
   594
            | NONE => error ("corr: no realizer for instance of axiom " ^
wenzelm@26939
   595
                quote s ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
berghofe@13402
   596
                  (Reconstruct.prop_of (proof_combt (prf0, ts)))))
berghofe@13402
   597
          end
berghofe@13402
   598
berghofe@13402
   599
      | corr d defs vs ts Ts hs _ _ _ = error "corr: bad proof"
berghofe@13402
   600
berghofe@13402
   601
    and extr d defs vs ts Ts hs (PBound i) = (defs, Bound i)
berghofe@13402
   602
skalberg@15531
   603
      | extr d defs vs ts Ts hs (Abst (s, SOME T, prf)) =
berghofe@13402
   604
          let val (defs', t) = extr d defs vs []
berghofe@13402
   605
            (T :: Ts) (dummyt :: hs) (incr_pboundvars 1 0 prf)
berghofe@13402
   606
          in (defs', Abs (s, T, t)) end
berghofe@13402
   607
skalberg@15531
   608
      | extr d defs vs ts Ts hs (AbsP (s, SOME t, prf)) =
berghofe@13402
   609
          let
wenzelm@16458
   610
            val T = etype_of thy' vs Ts t;
berghofe@13402
   611
            val (defs', t) = extr d defs vs [] (T :: Ts) (t :: hs)
berghofe@13402
   612
              (incr_pboundvars 0 1 prf)
berghofe@13402
   613
          in (defs',
berghofe@13402
   614
            if T = nullT then subst_bound (nullt, t) else Abs (s, T, t))
berghofe@13402
   615
          end
berghofe@13402
   616
skalberg@15531
   617
      | extr d defs vs ts Ts hs (prf % SOME t) =
berghofe@13402
   618
          let val (defs', u) = extr d defs vs (t :: ts) Ts hs prf
berghofe@13732
   619
          in (defs',
wenzelm@20664
   620
            if member (op =) rtypes (tname_of (body_type (fastype_of1 (Ts, t)))) then u
berghofe@13732
   621
            else u $ t)
berghofe@13732
   622
          end
berghofe@13402
   623
berghofe@13402
   624
      | extr d defs vs ts Ts hs (prf1 %% prf2) =
berghofe@13402
   625
          let
berghofe@13402
   626
            val (defs', f) = extr d defs vs [] Ts hs prf1;
berghofe@13402
   627
            val prop = Reconstruct.prop_of' hs prf2;
wenzelm@16458
   628
            val T = etype_of thy' vs Ts prop
berghofe@13402
   629
          in
berghofe@13402
   630
            if T = nullT then (defs', f) else
berghofe@13402
   631
              let val (defs'', t) = extr d defs' vs [] Ts hs prf2
berghofe@13402
   632
              in (defs'', f $ t) end
berghofe@13402
   633
          end
berghofe@13402
   634
wenzelm@28805
   635
      | extr d defs vs ts Ts hs (prf0 as PThm (_, ((s, prop, SOME Ts'), body))) =
berghofe@13402
   636
          let
wenzelm@29635
   637
            val prf = join_proof body;
berghofe@13402
   638
            val (vs', tye) = find_inst prop Ts ts vs;
wenzelm@29270
   639
            val tye' = (map fst (OldTerm.term_tvars prop) ~~ Ts') @ tye
berghofe@13402
   640
          in
wenzelm@17412
   641
            case Symtab.lookup realizers s of
skalberg@15531
   642
              NONE => (case find vs' (find' s defs) of
skalberg@15531
   643
                NONE =>
berghofe@13402
   644
                  let
berghofe@13402
   645
                    val _ = msg d ("Extracting " ^ quote s ^
berghofe@13402
   646
                      (if null vs' then ""
berghofe@13402
   647
                       else " (relevant variables: " ^ commas_quote vs' ^ ")"));
wenzelm@16458
   648
                    val prf' = prep (Reconstruct.reconstruct_proof thy' prop prf);
berghofe@13402
   649
                    val (defs', t) = extr (d + 1) defs vs' [] [] [] prf';
berghofe@13402
   650
                    val (defs'', corr_prf) =
skalberg@15531
   651
                      corr (d + 1) defs' vs' [] [] [] prf' prf' (SOME t);
berghofe@13402
   652
berghofe@13402
   653
                    val nt = Envir.beta_norm t;
wenzelm@20664
   654
                    val args = filter_out (fn v => member (op =) rtypes
wenzelm@20664
   655
                      (tname_of (body_type (fastype_of v)))) (vfs_of prop);
skalberg@15570
   656
                    val args' = List.filter (fn v => Logic.occs (v, nt)) args;
skalberg@15574
   657
                    val t' = mkabs nt args';
berghofe@13402
   658
                    val T = fastype_of t';
berghofe@13732
   659
                    val cname = extr_name s vs';
berghofe@13402
   660
                    val c = Const (cname, T);
skalberg@15574
   661
                    val u = mkabs (list_comb (c, args')) args;
berghofe@13402
   662
                    val eqn = Logic.mk_equals (c, t');
berghofe@13402
   663
                    val rlz =
berghofe@13402
   664
                      Const ("realizes", fastype_of nt --> propT --> propT);
berghofe@13732
   665
                    val lhs = app_rlz_rews [] vs' (rlz $ nt $ prop);
berghofe@13732
   666
                    val rhs = app_rlz_rews [] vs' (rlz $ list_comb (c, args') $ prop);
berghofe@13732
   667
                    val f = app_rlz_rews [] vs'
berghofe@13732
   668
                      (Abs ("x", T, rlz $ list_comb (Bound 0, args') $ prop));
berghofe@13402
   669
berghofe@13732
   670
                    val corr_prf' =
berghofe@13732
   671
                      chtype [] equal_elim_axm %> lhs %> rhs %%
berghofe@13732
   672
                       (chtype [propT] symmetric_axm %> rhs %> lhs %%
berghofe@13732
   673
                         (chtype [propT, T] combination_axm %> f %> f %> c %> t' %%
berghofe@13732
   674
                           (chtype [T --> propT] reflexive_axm %> f) %%
berghofe@13732
   675
                           PAxm (cname ^ "_def", eqn,
wenzelm@29270
   676
                             SOME (map TVar (OldTerm.term_tvars eqn))))) %% corr_prf;
berghofe@13732
   677
                    val corr_prop = Reconstruct.prop_of corr_prf';
wenzelm@23178
   678
                    val corr_prf'' = List.foldr forall_intr_prf
skalberg@15574
   679
                      (proof_combt
wenzelm@28805
   680
                        (PThm (serial (),
wenzelm@29270
   681
                         ((corr_name s vs', corr_prop, SOME (map TVar (OldTerm.term_tvars corr_prop))),
wenzelm@30718
   682
                           Future.value (approximate_proof_body corr_prf'))), vfs_of corr_prop))
haftmann@22750
   683
                      (map (get_var_type corr_prop) (vfs_of prop));
berghofe@13402
   684
                  in
berghofe@13732
   685
                    ((s, (vs', ((t', u), (corr_prf', corr_prf'')))) :: defs'',
berghofe@13402
   686
                     subst_TVars tye' u)
berghofe@13402
   687
                  end
skalberg@15531
   688
              | SOME ((_, u), _) => (defs, subst_TVars tye' u))
skalberg@15531
   689
            | SOME rs => (case find vs' rs of
skalberg@15531
   690
                SOME (t, _) => (defs, subst_TVars tye' t)
skalberg@15531
   691
              | NONE => error ("extr: no realizer for instance of theorem " ^
wenzelm@26939
   692
                  quote s ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
berghofe@13402
   693
                    (Reconstruct.prop_of (proof_combt (prf0, ts))))))
berghofe@13402
   694
          end
berghofe@13402
   695
skalberg@15531
   696
      | extr d defs vs ts Ts hs (prf0 as PAxm (s, prop, SOME Ts')) =
berghofe@13402
   697
          let
berghofe@13402
   698
            val (vs', tye) = find_inst prop Ts ts vs;
wenzelm@29270
   699
            val tye' = (map fst (OldTerm.term_tvars prop) ~~ Ts') @ tye
berghofe@13402
   700
          in
wenzelm@18956
   701
            case find vs' (Symtab.lookup_list realizers s) of
skalberg@15531
   702
              SOME (t, _) => (defs, subst_TVars tye' t)
skalberg@15531
   703
            | NONE => error ("extr: no realizer for instance of axiom " ^
wenzelm@26939
   704
                quote s ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
berghofe@13402
   705
                  (Reconstruct.prop_of (proof_combt (prf0, ts)))))
berghofe@13402
   706
          end
berghofe@13402
   707
berghofe@13402
   708
      | extr d defs vs ts Ts hs _ = error "extr: bad proof";
berghofe@13402
   709
berghofe@13732
   710
    fun prep_thm (thm, vs) =
berghofe@13402
   711
      let
wenzelm@26626
   712
        val thy = Thm.theory_of_thm thm;
wenzelm@26626
   713
        val prop = Thm.prop_of thm;
wenzelm@28814
   714
        val prf = Thm.proof_of thm;
wenzelm@21646
   715
        val name = Thm.get_name thm;
wenzelm@21858
   716
        val _ = name <> "" orelse error "extraction: unnamed theorem";
wenzelm@21858
   717
        val _ = etype_of thy' vs [] prop <> nullT orelse error ("theorem " ^
berghofe@13402
   718
          quote name ^ " has no computational content")
wenzelm@22596
   719
      in (Reconstruct.reconstruct_proof thy prop prf, vs) end;
berghofe@13402
   720
skalberg@15570
   721
    val defs = Library.foldl (fn (defs, (prf, vs)) =>
berghofe@13732
   722
      fst (extr 0 defs vs [] [] [] prf)) ([], map prep_thm thms);
berghofe@13402
   723
wenzelm@16149
   724
    fun add_def (s, (vs, ((t, u), (prf, _)))) thy =
wenzelm@16458
   725
      (case Sign.const_type thy (extr_name s vs) of
skalberg@15531
   726
         NONE =>
berghofe@13732
   727
           let
berghofe@13732
   728
             val corr_prop = Reconstruct.prop_of prf;
wenzelm@16287
   729
             val ft = Type.freeze t;
wenzelm@16287
   730
             val fu = Type.freeze u;
haftmann@22750
   731
             val (def_thms, thy') = if t = nullt then ([], thy) else
haftmann@22750
   732
               thy
wenzelm@30435
   733
               |> Sign.add_consts_i [(Binding.qualified_name (extr_name s vs), fastype_of ft, NoSyn)]
wenzelm@30435
   734
               |> PureThy.add_defs false [((Binding.qualified_name (extr_name s vs ^ "_def"),
haftmann@22750
   735
                    Logic.mk_equals (head_of (strip_abs_body fu), ft)), [])]
berghofe@13732
   736
           in
haftmann@22750
   737
             thy'
wenzelm@30435
   738
             |> PureThy.store_thm (Binding.qualified_name (corr_name s vs),
wenzelm@29265
   739
                  Thm.varifyT (funpow (length (OldTerm.term_vars corr_prop))
wenzelm@26653
   740
                    (Thm.forall_elim_var 0) (forall_intr_frees
haftmann@22750
   741
                      (ProofChecker.thm_of_proof thy'
wenzelm@26481
   742
                       (fst (Proofterm.freeze_thaw_prf prf))))))
haftmann@22750
   743
             |> snd
haftmann@28370
   744
             |> fold Code.add_default_eqn def_thms
berghofe@13732
   745
           end
skalberg@15531
   746
       | SOME _ => thy);
berghofe@13402
   747
wenzelm@16149
   748
  in
wenzelm@16149
   749
    thy
wenzelm@30435
   750
    |> Sign.root_path
wenzelm@16149
   751
    |> fold_rev add_def defs
wenzelm@22796
   752
    |> Sign.restore_naming thy
berghofe@13402
   753
  end;
berghofe@13402
   754
berghofe@13402
   755
berghofe@13402
   756
(**** interface ****)
berghofe@13402
   757
wenzelm@17057
   758
structure P = OuterParse and K = OuterKeyword;
berghofe@13402
   759
berghofe@13732
   760
val parse_vars = Scan.optional (P.$$$ "(" |-- P.list1 P.name --| P.$$$ ")") [];
berghofe@13732
   761
wenzelm@24867
   762
val _ =
berghofe@13402
   763
  OuterSyntax.command "realizers"
berghofe@13402
   764
  "specify realizers for primitive axioms / theorems, together with correctness proof"
berghofe@13402
   765
  K.thy_decl
berghofe@13732
   766
    (Scan.repeat1 (P.xname -- parse_vars --| P.$$$ ":" -- P.string -- P.string) >>
berghofe@13402
   767
     (fn xs => Toplevel.theory (fn thy => add_realizers
wenzelm@26343
   768
       (map (fn (((a, vs), s1), s2) => (PureThy.get_thm thy a, (vs, s1, s2))) xs) thy)));
berghofe@13402
   769
wenzelm@24867
   770
val _ =
berghofe@13402
   771
  OuterSyntax.command "realizability"
berghofe@13402
   772
  "add equations characterizing realizability" K.thy_decl
berghofe@13402
   773
  (Scan.repeat1 P.string >> (Toplevel.theory o add_realizes_eqns));
berghofe@13402
   774
wenzelm@24867
   775
val _ =
berghofe@13402
   776
  OuterSyntax.command "extract_type"
berghofe@13402
   777
  "add equations characterizing type of extracted program" K.thy_decl
berghofe@13402
   778
  (Scan.repeat1 P.string >> (Toplevel.theory o add_typeof_eqns));
berghofe@13402
   779
wenzelm@24867
   780
val _ =
berghofe@13402
   781
  OuterSyntax.command "extract" "extract terms from proofs" K.thy_decl
wenzelm@26336
   782
    (Scan.repeat1 (P.xname -- parse_vars) >> (fn xs => Toplevel.theory (fn thy =>
wenzelm@26343
   783
      extract (map (apfst (PureThy.get_thm thy)) xs) thy)));
berghofe@13402
   784
wenzelm@16458
   785
val etype_of = etype_of o add_syntax;
berghofe@13714
   786
berghofe@13402
   787
end;