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