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