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