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