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