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