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