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