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