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