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