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