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