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