src/Pure/Proof/extraction.ML
author wenzelm
Sat Nov 08 21:31:51 2014 +0100 (2014-11-08)
changeset 58950 d07464875dd4
parent 58843 521cea5fa777
child 59058 a78612c67ec0
permissions -rw-r--r--
optional proof context for unify operations, for the sake of proper local options;
     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 (pairself (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 pairself (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 pairself 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 (Pretty.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 thy T s =
   168   let
   169     val ctxt = Proof_Context.init_global thy
   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 pairself #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 thy' = add_syntax thy
   218   in fn s =>
   219     let val t = Logic.varify_global (read_term thy' 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 rd = Proof_Syntax.read_proof thy' true false;
   318   in fn (thm, (vs, s1, s2)) =>
   319     let
   320       val name = Thm.derivation_name thm;
   321       val _ = name <> "" orelse error "add_realizers: unnamed theorem";
   322       val prop = Thm.unconstrainT thm |> prop_of |>
   323         Pattern.rewrite_term thy' (map (Logic.dest_equals o prop_of) defs) [];
   324       val vars = vars_of prop;
   325       val vars' = filter_out (fn v =>
   326         member (op =) rtypes (tname_of (body_type (fastype_of v)))) vars;
   327       val shyps = maps (fn Var ((x, i), _) =>
   328         if member (op =) vs x then Logic.mk_of_sort
   329           (TVar (("'" ^ x, i), []), Sign.defaultS thy')
   330         else []) vars;
   331       val T = etype_of thy' vs [] prop;
   332       val (T', thw) = Type.legacy_freeze_thaw_type
   333         (if T = nullT then nullT else map fastype_of vars' ---> T);
   334       val t = map_types thw (read_term thy' T' s1);
   335       val r' = freeze_thaw (condrew thy' eqns
   336         (procs @ [typeof_proc [] vs, rlz_proc]))
   337           (Const ("realizes", T --> propT --> propT) $
   338             (if T = nullT then t else list_comb (t, vars')) $ prop);
   339       val r = Logic.list_implies (shyps,
   340         fold_rev Logic.all (map (get_var_type r') vars) r');
   341       val prf = Reconstruct.reconstruct_proof thy' r (rd s2);
   342     in (name, (vs, (t, prf))) end
   343   end;
   344 
   345 val add_realizers_i = gen_add_realizers
   346   (fn _ => fn (name, (vs, t, prf)) => (name, (vs, (t, prf))));
   347 val add_realizers = gen_add_realizers prep_realizer;
   348 
   349 fun realizes_of thy vs t prop =
   350   let
   351     val thy' = add_syntax thy;
   352     val {realizes_eqns, typeof_eqns, defs, types, ...} =
   353       ExtractionData.get thy';
   354     val procs = maps (rev o fst o snd) types;
   355     val eqns = Net.merge (K false) (#net realizes_eqns, #net typeof_eqns);
   356     val prop' = Pattern.rewrite_term thy'
   357       (map (Logic.dest_equals o prop_of) defs) [] prop;
   358   in freeze_thaw (condrew thy' eqns
   359     (procs @ [typeof_proc [] vs, rlz_proc]))
   360       (Const ("realizes", fastype_of t --> propT --> propT) $ t $ prop')
   361   end;
   362 
   363 fun abs_corr_shyps thy thm vs xs prf =
   364   let
   365     val S = Sign.defaultS thy;
   366     val ((atyp_map, constraints, _), prop') =
   367       Logic.unconstrainT (#shyps (rep_thm thm)) (prop_of thm);
   368     val atyps = fold_types (fold_atyps (insert (op =))) (prop_of thm) [];
   369     val Ts = map_filter (fn ((v, i), _) => if member (op =) vs v then
   370         SOME (TVar (("'" ^ v, i), [])) else NONE)
   371       (rev (Term.add_vars prop' []));
   372     val cs = maps (fn T => map (pair T) S) Ts;
   373     val constraints' = map Logic.mk_of_class cs;
   374     fun typ_map T = Type.strip_sorts
   375       (map_atyps (fn U => if member (op =) atyps U then atyp_map U else U) T);
   376     fun mk_hyp (T, c) = Hyp (Logic.mk_of_class (typ_map T, c));
   377     val xs' = map (map_types typ_map) xs
   378   in
   379     prf |>
   380     Same.commit (Proofterm.map_proof_same (map_types typ_map) typ_map mk_hyp) |>
   381     fold_rev Proofterm.implies_intr_proof' (map snd constraints) |>
   382     fold_rev Proofterm.forall_intr_proof' xs' |>
   383     fold_rev Proofterm.implies_intr_proof' constraints'
   384   end;
   385 
   386 (** expanding theorems / definitions **)
   387 
   388 fun add_expand_thm is_def thm thy =
   389   let
   390     val {realizes_eqns, typeof_eqns, types, realizers,
   391       defs, expand, prep} = ExtractionData.get thy;
   392 
   393     val name = Thm.derivation_name thm;
   394     val _ = name <> "" orelse error "add_expand_thm: unnamed theorem";
   395   in
   396     thy |> ExtractionData.put
   397       (if is_def then
   398         {realizes_eqns = realizes_eqns,
   399          typeof_eqns = add_rule ([], Logic.dest_equals (map_types
   400            Type.strip_sorts (prop_of (Drule.abs_def thm)))) typeof_eqns,
   401          types = types,
   402          realizers = realizers, defs = insert Thm.eq_thm thm defs,
   403          expand = expand, prep = prep}
   404       else
   405         {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
   406          realizers = realizers, defs = defs,
   407          expand = insert (op =) name expand, prep = prep})
   408   end;
   409 
   410 fun extraction_expand is_def =
   411   Thm.declaration_attribute (fn th => Context.mapping (add_expand_thm is_def th) I);
   412 
   413 
   414 (** types with computational content **)
   415 
   416 fun add_types tys thy =
   417   ExtractionData.map
   418     (fn {realizes_eqns, typeof_eqns, types, realizers, defs, expand, prep} =>
   419       {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns,
   420        types = fold (AList.update (op =) o apfst (Sign.intern_type thy)) tys types,
   421        realizers = realizers, defs = defs, expand = expand, prep = prep})
   422     thy;
   423 
   424 
   425 (** Pure setup **)
   426 
   427 val _ = Theory.setup
   428   (add_types [("prop", ([], NONE))] #>
   429 
   430    add_typeof_eqns
   431      ["(typeof (PROP P)) == (Type (TYPE(Null))) ==>  \
   432     \  (typeof (PROP Q)) == (Type (TYPE('Q))) ==>  \
   433     \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE('Q)))",
   434 
   435       "(typeof (PROP Q)) == (Type (TYPE(Null))) ==>  \
   436     \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE(Null)))",
   437 
   438       "(typeof (PROP P)) == (Type (TYPE('P))) ==>  \
   439     \  (typeof (PROP Q)) == (Type (TYPE('Q))) ==>  \
   440     \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE('P => 'Q)))",
   441 
   442       "(%x. typeof (PROP P (x))) == (%x. Type (TYPE(Null))) ==>  \
   443     \    (typeof (!!x. PROP P (x))) == (Type (TYPE(Null)))",
   444 
   445       "(%x. typeof (PROP P (x))) == (%x. Type (TYPE('P))) ==>  \
   446     \    (typeof (!!x::'a. PROP P (x))) == (Type (TYPE('a => 'P)))",
   447 
   448       "(%x. typeof (f (x))) == (%x. Type (TYPE('f))) ==>  \
   449     \    (typeof (f)) == (Type (TYPE('f)))"] #>
   450 
   451    add_realizes_eqns
   452      ["(typeof (PROP P)) == (Type (TYPE(Null))) ==>  \
   453     \    (realizes (r) (PROP P ==> PROP Q)) ==  \
   454     \    (PROP realizes (Null) (PROP P) ==> PROP realizes (r) (PROP Q))",
   455 
   456       "(typeof (PROP P)) == (Type (TYPE('P))) ==>  \
   457     \  (typeof (PROP Q)) == (Type (TYPE(Null))) ==>  \
   458     \    (realizes (r) (PROP P ==> PROP Q)) ==  \
   459     \    (!!x::'P. PROP realizes (x) (PROP P) ==> PROP realizes (Null) (PROP Q))",
   460 
   461       "(realizes (r) (PROP P ==> PROP Q)) ==  \
   462     \  (!!x. PROP realizes (x) (PROP P) ==> PROP realizes (r (x)) (PROP Q))",
   463 
   464       "(%x. typeof (PROP P (x))) == (%x. Type (TYPE(Null))) ==>  \
   465     \    (realizes (r) (!!x. PROP P (x))) ==  \
   466     \    (!!x. PROP realizes (Null) (PROP P (x)))",
   467 
   468       "(realizes (r) (!!x. PROP P (x))) ==  \
   469     \  (!!x. PROP realizes (r (x)) (PROP P (x)))"] #>
   470 
   471    Attrib.setup @{binding extraction_expand} (Scan.succeed (extraction_expand false))
   472      "specify theorems to be expanded during extraction" #>
   473    Attrib.setup @{binding extraction_expand_def} (Scan.succeed (extraction_expand true))
   474      "specify definitions to be expanded during extraction");
   475 
   476 
   477 (**** extract program ****)
   478 
   479 val dummyt = Const ("dummy", dummyT);
   480 
   481 fun extract thm_vss thy =
   482   let
   483     val thy' = add_syntax thy;
   484     val {realizes_eqns, typeof_eqns, types, realizers, defs, expand, prep} =
   485       ExtractionData.get thy;
   486     val procs = maps (rev o fst o snd) types;
   487     val rtypes = map fst types;
   488     val typroc = typeof_proc [];
   489     val prep = the_default (K I) prep thy' o ProofRewriteRules.elim_defs thy' false defs o
   490       Reconstruct.expand_proof thy' (map (rpair NONE) ("" :: expand));
   491     val rrews = Net.merge (K false) (#net realizes_eqns, #net typeof_eqns);
   492 
   493     fun find_inst prop Ts ts vs =
   494       let
   495         val rvs = relevant_vars rtypes prop;
   496         val vars = vars_of prop;
   497         val n = Int.min (length vars, length ts);
   498 
   499         fun add_args (Var ((a, i), _), t) (vs', tye) =
   500           if member (op =) rvs a then
   501             let val T = etype_of thy' vs Ts t
   502             in if T = nullT then (vs', tye)
   503                else (a :: vs', (("'" ^ a, i), T) :: tye)
   504             end
   505           else (vs', tye)
   506 
   507       in fold_rev add_args (take n vars ~~ take n ts) ([], []) end;
   508 
   509     fun mk_shyps tye = maps (fn (ixn, _) =>
   510       Logic.mk_of_sort (TVar (ixn, []), Sign.defaultS thy)) tye;
   511 
   512     fun mk_sprfs cs tye = maps (fn (_, T) =>
   513       ProofRewriteRules.mk_of_sort_proof thy (map SOME cs)
   514         (T, Sign.defaultS thy)) tye;
   515 
   516     fun find (vs: string list) = Option.map snd o find_first (curry (eq_set (op =)) vs o fst);
   517     fun find' (s: string) = map_filter (fn (s', x) => if s = s' then SOME x else NONE);
   518 
   519     fun app_rlz_rews Ts vs t =
   520       strip_abs (length Ts)
   521         (freeze_thaw (condrew thy' rrews (procs @ [typroc vs, rlz_proc]))
   522           (fold (Term.abs o pair "x") Ts t));
   523 
   524     fun realizes_null vs prop = app_rlz_rews [] vs
   525       (Const ("realizes", nullT --> propT --> propT) $ nullt $ prop);
   526 
   527     fun corr d vs ts Ts hs cs _ (PBound i) _ defs = (PBound i, defs)
   528 
   529       | corr d vs ts Ts hs cs t (Abst (s, SOME T, prf)) (Abst (_, _, prf')) defs =
   530           let val (corr_prf, defs') = corr d vs [] (T :: Ts)
   531             (dummyt :: hs) cs (case t of SOME (Abs (_, _, u)) => SOME u | _ => NONE)
   532             prf (Proofterm.incr_pboundvars 1 0 prf') defs
   533           in (Abst (s, SOME T, corr_prf), defs') end
   534 
   535       | corr d vs ts Ts hs cs t (AbsP (s, SOME prop, prf)) (AbsP (_, _, prf')) defs =
   536           let
   537             val T = etype_of thy' vs Ts prop;
   538             val u = if T = nullT then
   539                 (case t of SOME u => SOME (incr_boundvars 1 u) | NONE => NONE)
   540               else (case t of SOME (Abs (_, _, u)) => SOME u | _ => NONE);
   541             val (corr_prf, defs') =
   542               corr d vs [] (T :: Ts) (prop :: hs)
   543                 (prop :: cs) u (Proofterm.incr_pboundvars 0 1 prf)
   544                 (Proofterm.incr_pboundvars 0 1 prf') defs;
   545             val rlz = Const ("realizes", T --> propT --> propT)
   546           in (
   547             if T = nullT then AbsP ("R",
   548               SOME (app_rlz_rews Ts vs (rlz $ nullt $ prop)),
   549                 Proofterm.prf_subst_bounds [nullt] corr_prf)
   550             else Abst (s, SOME T, AbsP ("R",
   551               SOME (app_rlz_rews (T :: Ts) vs
   552                 (rlz $ Bound 0 $ incr_boundvars 1 prop)), corr_prf)), defs')
   553           end
   554 
   555       | corr d vs ts Ts hs cs t' (prf % SOME t) (prf' % _) defs =
   556           let
   557             val (Us, T) = strip_type (fastype_of1 (Ts, t));
   558             val (corr_prf, defs') = corr d vs (t :: ts) Ts hs cs
   559               (if member (op =) rtypes (tname_of T) then t'
   560                else (case t' of SOME (u $ _) => SOME u | _ => NONE))
   561                prf prf' defs;
   562             val u = if not (member (op =) rtypes (tname_of T)) then t else
   563               let
   564                 val eT = etype_of thy' vs Ts t;
   565                 val (r, Us') = if eT = nullT then (nullt, Us) else
   566                   (Bound (length Us), eT :: Us);
   567                 val u = list_comb (incr_boundvars (length Us') t,
   568                   map Bound (length Us - 1 downto 0));
   569                 val u' = (case AList.lookup (op =) types (tname_of T) of
   570                     SOME ((_, SOME f)) => f r eT u T
   571                   | _ => Const ("realizes", eT --> T --> T) $ r $ u)
   572               in app_rlz_rews Ts vs (fold_rev (Term.abs o pair "x") Us' u') end
   573           in (corr_prf % SOME u, defs') end
   574 
   575       | corr d vs ts Ts hs cs t (prf1 %% prf2) (prf1' %% prf2') defs =
   576           let
   577             val prop = Reconstruct.prop_of' hs prf2';
   578             val T = etype_of thy' vs Ts prop;
   579             val (f, u, defs1) = if T = nullT then (t, NONE, defs) else
   580               (case t of
   581                  SOME (f $ u) => (SOME f, SOME u, defs)
   582                | _ =>
   583                  let val (u, defs1) = extr d vs [] Ts hs prf2' defs
   584                  in (NONE, SOME u, defs1) end)
   585             val ((corr_prf1, corr_prf2), defs2) =
   586               defs1
   587               |> corr d vs [] Ts hs cs f prf1 prf1'
   588               ||>> corr d vs [] Ts hs cs u prf2 prf2';
   589           in
   590             if T = nullT then (corr_prf1 %% corr_prf2, defs2) else
   591               (corr_prf1 % u %% corr_prf2, defs2)
   592           end
   593 
   594       | corr d vs ts Ts hs cs _ (prf0 as PThm (_, ((name, prop, SOME Ts'), body))) _ defs =
   595           let
   596             val prf = Proofterm.join_proof body;
   597             val (vs', tye) = find_inst prop Ts ts vs;
   598             val shyps = mk_shyps tye;
   599             val sprfs = mk_sprfs cs tye;
   600             val tye' = (map fst (Term.add_tvars prop [] |> rev) ~~ Ts') @ tye;
   601             val T = etype_of thy' vs' [] prop;
   602             val defs' = if T = nullT then defs
   603               else snd (extr d vs ts Ts hs prf0 defs)
   604           in
   605             if T = nullT andalso realizes_null vs' prop aconv prop then (prf0, defs)
   606             else (case Symtab.lookup realizers name of
   607               NONE => (case find vs' (find' name defs') of
   608                 NONE =>
   609                   let
   610                     val _ = T = nullT orelse error "corr: internal error";
   611                     val _ = msg d ("Building correctness proof for " ^ quote name ^
   612                       (if null vs' then ""
   613                        else " (relevant variables: " ^ commas_quote vs' ^ ")"));
   614                     val prf' = prep (Reconstruct.reconstruct_proof thy' prop prf);
   615                     val (corr_prf0, defs'') = corr (d + 1) vs' [] [] []
   616                       (rev shyps) NONE prf' prf' defs';
   617                     val corr_prf = mkabsp shyps corr_prf0;
   618                     val corr_prop = Reconstruct.prop_of corr_prf;
   619                     val corr_prf' =
   620                       Proofterm.proof_combP (Proofterm.proof_combt
   621                          (PThm (serial (),
   622                           ((corr_name name vs', corr_prop, SOME (map TVar (Term.add_tvars corr_prop [] |> rev))),
   623                             Future.value (Proofterm.approximate_proof_body corr_prf))),
   624                               vfs_of corr_prop),
   625                               map PBound (length shyps - 1 downto 0)) |>
   626                       fold_rev Proofterm.forall_intr_proof'
   627                         (map (get_var_type corr_prop) (vfs_of prop)) |>
   628                       mkabsp shyps
   629                   in
   630                     (Proofterm.proof_combP (prf_subst_TVars tye' corr_prf', sprfs),
   631                       (name, (vs', ((nullt, nullt), (corr_prf, corr_prf')))) :: defs'')
   632                   end
   633               | SOME (_, (_, prf')) =>
   634                   (Proofterm.proof_combP (prf_subst_TVars tye' prf', sprfs), defs'))
   635             | SOME rs => (case find vs' rs of
   636                 SOME (_, prf') => (Proofterm.proof_combP (prf_subst_TVars tye' prf', sprfs), defs')
   637               | NONE => error ("corr: no realizer for instance of theorem " ^
   638                   quote name ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
   639                     (Reconstruct.prop_of (Proofterm.proof_combt (prf0, ts)))))))
   640           end
   641 
   642       | corr d vs ts Ts hs cs _ (prf0 as PAxm (s, prop, SOME Ts')) _ defs =
   643           let
   644             val (vs', tye) = find_inst prop Ts ts vs;
   645             val tye' = (map fst (Term.add_tvars prop [] |> rev) ~~ Ts') @ tye
   646           in
   647             if etype_of thy' vs' [] prop = nullT andalso
   648               realizes_null vs' prop aconv prop then (prf0, defs)
   649             else case find vs' (Symtab.lookup_list realizers s) of
   650               SOME (_, prf) => (Proofterm.proof_combP (prf_subst_TVars tye' prf, mk_sprfs cs tye),
   651                 defs)
   652             | NONE => error ("corr: no realizer for instance of axiom " ^
   653                 quote s ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
   654                   (Reconstruct.prop_of (Proofterm.proof_combt (prf0, ts)))))
   655           end
   656 
   657       | corr d vs ts Ts hs _ _ _ _ defs = error "corr: bad proof"
   658 
   659     and extr d vs ts Ts hs (PBound i) defs = (Bound i, defs)
   660 
   661       | extr d vs ts Ts hs (Abst (s, SOME T, prf)) defs =
   662           let val (t, defs') = extr d vs []
   663             (T :: Ts) (dummyt :: hs) (Proofterm.incr_pboundvars 1 0 prf) defs
   664           in (Abs (s, T, t), defs') end
   665 
   666       | extr d vs ts Ts hs (AbsP (s, SOME t, prf)) defs =
   667           let
   668             val T = etype_of thy' vs Ts t;
   669             val (t, defs') =
   670               extr d vs [] (T :: Ts) (t :: hs) (Proofterm.incr_pboundvars 0 1 prf) defs
   671           in
   672             (if T = nullT then subst_bound (nullt, t) else Abs (s, T, t), defs')
   673           end
   674 
   675       | extr d vs ts Ts hs (prf % SOME t) defs =
   676           let val (u, defs') = extr d vs (t :: ts) Ts hs prf defs
   677           in (if member (op =) rtypes (tname_of (body_type (fastype_of1 (Ts, t)))) then u
   678             else u $ t, defs')
   679           end
   680 
   681       | extr d vs ts Ts hs (prf1 %% prf2) defs =
   682           let
   683             val (f, defs') = extr d vs [] Ts hs prf1 defs;
   684             val prop = Reconstruct.prop_of' hs prf2;
   685             val T = etype_of thy' vs Ts prop
   686           in
   687             if T = nullT then (f, defs') else
   688               let val (t, defs'') = extr d vs [] Ts hs prf2 defs'
   689               in (f $ t, defs'') end
   690           end
   691 
   692       | extr d vs ts Ts hs (prf0 as PThm (_, ((s, prop, SOME Ts'), body))) defs =
   693           let
   694             val prf = Proofterm.join_proof body;
   695             val (vs', tye) = find_inst prop Ts ts vs;
   696             val shyps = mk_shyps tye;
   697             val tye' = (map fst (Term.add_tvars prop [] |> rev) ~~ Ts') @ tye
   698           in
   699             case Symtab.lookup realizers s of
   700               NONE => (case find vs' (find' s defs) of
   701                 NONE =>
   702                   let
   703                     val _ = msg d ("Extracting " ^ quote s ^
   704                       (if null vs' then ""
   705                        else " (relevant variables: " ^ commas_quote vs' ^ ")"));
   706                     val prf' = prep (Reconstruct.reconstruct_proof thy' prop prf);
   707                     val (t, defs') = extr (d + 1) vs' [] [] [] prf' defs;
   708                     val (corr_prf, defs'') = corr (d + 1) vs' [] [] []
   709                       (rev shyps) (SOME t) prf' prf' defs';
   710 
   711                     val nt = Envir.beta_norm t;
   712                     val args = filter_out (fn v => member (op =) rtypes
   713                       (tname_of (body_type (fastype_of v)))) (vfs_of prop);
   714                     val args' = filter (fn v => Logic.occs (v, nt)) args;
   715                     val t' = mkabs args' nt;
   716                     val T = fastype_of t';
   717                     val cname = extr_name s vs';
   718                     val c = Const (cname, T);
   719                     val u = mkabs args (list_comb (c, args'));
   720                     val eqn = Logic.mk_equals (c, t');
   721                     val rlz =
   722                       Const ("realizes", fastype_of nt --> propT --> propT);
   723                     val lhs = app_rlz_rews [] vs' (rlz $ nt $ prop);
   724                     val rhs = app_rlz_rews [] vs' (rlz $ list_comb (c, args') $ prop);
   725                     val f = app_rlz_rews [] vs'
   726                       (Abs ("x", T, rlz $ list_comb (Bound 0, args') $ prop));
   727 
   728                     val corr_prf' = mkabsp shyps
   729                       (chtype [] Proofterm.equal_elim_axm %> lhs %> rhs %%
   730                        (chtype [propT] Proofterm.symmetric_axm %> rhs %> lhs %%
   731                          (chtype [T, propT] Proofterm.combination_axm %> f %> f %> c %> t' %%
   732                            (chtype [T --> propT] Proofterm.reflexive_axm %> f) %%
   733                            PAxm (Thm.def_name cname, eqn,
   734                              SOME (map TVar (Term.add_tvars eqn [] |> rev))))) %% corr_prf);
   735                     val corr_prop = Reconstruct.prop_of corr_prf';
   736                     val corr_prf'' =
   737                       Proofterm.proof_combP (Proofterm.proof_combt
   738                         (PThm (serial (),
   739                          ((corr_name s vs', corr_prop, SOME (map TVar (Term.add_tvars corr_prop [] |> rev))),
   740                            Future.value (Proofterm.approximate_proof_body corr_prf'))),
   741                             vfs_of corr_prop),
   742                              map PBound (length shyps - 1 downto 0)) |>
   743                       fold_rev Proofterm.forall_intr_proof'
   744                         (map (get_var_type corr_prop) (vfs_of prop)) |>
   745                       mkabsp shyps
   746                   in
   747                     (subst_TVars tye' u,
   748                       (s, (vs', ((t', u), (corr_prf', corr_prf'')))) :: defs'')
   749                   end
   750               | SOME ((_, u), _) => (subst_TVars tye' u, defs))
   751             | SOME rs => (case find vs' rs of
   752                 SOME (t, _) => (subst_TVars tye' t, defs)
   753               | NONE => error ("extr: no realizer for instance of theorem " ^
   754                   quote s ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
   755                     (Reconstruct.prop_of (Proofterm.proof_combt (prf0, ts))))))
   756           end
   757 
   758       | extr d vs ts Ts hs (prf0 as PAxm (s, prop, SOME Ts')) defs =
   759           let
   760             val (vs', tye) = find_inst prop Ts ts vs;
   761             val tye' = (map fst (Term.add_tvars prop [] |> rev) ~~ Ts') @ tye
   762           in
   763             case find vs' (Symtab.lookup_list realizers s) of
   764               SOME (t, _) => (subst_TVars tye' t, defs)
   765             | NONE => error ("extr: no realizer for instance of axiom " ^
   766                 quote s ^ ":\n" ^ Syntax.string_of_term_global thy' (Envir.beta_norm
   767                   (Reconstruct.prop_of (Proofterm.proof_combt (prf0, ts)))))
   768           end
   769 
   770       | extr d vs ts Ts hs _ defs = error "extr: bad proof";
   771 
   772     fun prep_thm vs thm =
   773       let
   774         val thy = Thm.theory_of_thm thm;
   775         val prop = Thm.prop_of thm;
   776         val prf = Thm.proof_of thm;
   777         val name = Thm.derivation_name thm;
   778         val _ = name <> "" orelse error "extraction: unnamed theorem";
   779         val _ = etype_of thy' vs [] prop <> nullT orelse error ("theorem " ^
   780           quote name ^ " has no computational content")
   781       in Reconstruct.reconstruct_proof thy prop prf end;
   782 
   783     val defs =
   784       fold (fn (thm, vs) => snd o (extr 0 vs [] [] [] o prep_thm vs) thm)
   785         thm_vss [];
   786 
   787     fun add_def (s, (vs, ((t, u), (prf, _)))) thy =
   788       (case Sign.const_type thy (extr_name s vs) of
   789          NONE =>
   790            let
   791              val corr_prop = Reconstruct.prop_of prf;
   792              val ft = Type.legacy_freeze t;
   793              val fu = Type.legacy_freeze u;
   794              val (def_thms, thy') = if t = nullt then ([], thy) else
   795                thy
   796                |> Sign.add_consts [(Binding.qualified_name (extr_name s vs), fastype_of ft, NoSyn)]
   797                |> Global_Theory.add_defs false
   798                   [((Binding.qualified_name (Thm.def_name (extr_name s vs)),
   799                     Logic.mk_equals (head_of (strip_abs_body fu), ft)), [])]
   800            in
   801              thy'
   802              |> Global_Theory.store_thm (Binding.qualified_name (corr_name s vs),
   803                   Thm.varifyT_global (funpow (length (vars_of corr_prop))
   804                     (Thm.forall_elim_var 0) (Thm.forall_intr_frees
   805                       (Proof_Checker.thm_of_proof thy'
   806                        (fst (Proofterm.freeze_thaw_prf prf))))))
   807              |> snd
   808              |> fold Code.add_default_eqn def_thms
   809            end
   810        | SOME _ => thy);
   811 
   812   in
   813     thy
   814     |> Sign.root_path
   815     |> fold_rev add_def defs
   816     |> Sign.restore_naming thy
   817   end;
   818 
   819 val etype_of = etype_of o add_syntax;
   820 
   821 end;