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