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