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