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