src/Pure/Proof/extraction.ML
changeset 13402 e6e826bb8c3c
child 13417 12cc77f90811
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/Pure/Proof/extraction.ML	Sun Jul 21 15:37:04 2002 +0200
     1.3 @@ -0,0 +1,714 @@
     1.4 +(*  Title:      Pure/Proof/extraction.ML
     1.5 +    ID:         $Id$
     1.6 +    Author:     Stefan Berghofer, TU Muenchen
     1.7 +    License:    GPL (GNU GENERAL PUBLIC LICENSE)
     1.8 +
     1.9 +Extraction of programs from proofs.
    1.10 +*)
    1.11 +
    1.12 +signature EXTRACTION =
    1.13 +sig
    1.14 +  val set_preprocessor : (Sign.sg -> Proofterm.proof -> Proofterm.proof) -> theory -> theory
    1.15 +  val add_realizes_eqns_i : ((term * term) list * (term * term)) list -> theory -> theory
    1.16 +  val add_realizes_eqns : string list -> theory -> theory
    1.17 +  val add_typeof_eqns_i : ((term * term) list * (term * term)) list -> theory -> theory
    1.18 +  val add_typeof_eqns : string list -> theory -> theory
    1.19 +  val add_realizers_i : (string * (string list * term * Proofterm.proof)) list
    1.20 +    -> theory -> theory
    1.21 +  val add_realizers : (thm * (string list * string * string)) list
    1.22 +    -> theory -> theory
    1.23 +  val add_expand_thms : thm list -> theory -> theory
    1.24 +  val extract : thm list -> theory -> theory
    1.25 +  val nullT : typ
    1.26 +  val nullt : term
    1.27 +  val parsers: OuterSyntax.parser list
    1.28 +  val setup: (theory -> theory) list
    1.29 +end;
    1.30 +
    1.31 +structure Extraction : EXTRACTION =
    1.32 +struct
    1.33 +
    1.34 +open Proofterm;
    1.35 +
    1.36 +(**** tools ****)
    1.37 +
    1.38 +fun add_syntax thy =
    1.39 +  thy
    1.40 +  |> Theory.copy
    1.41 +  |> Theory.root_path
    1.42 +  |> Theory.add_types [("Type", 0, NoSyn), ("Null", 0, NoSyn)]
    1.43 +  |> Theory.add_arities [("Type", [], "logic"), ("Null", [], "logic")]
    1.44 +  |> Theory.add_consts
    1.45 +      [("typeof", "'b::logic => Type", NoSyn),
    1.46 +       ("Type", "'a::logic itself => Type", NoSyn),
    1.47 +       ("Null", "Null", NoSyn),
    1.48 +       ("realizes", "'a::logic => 'b::logic => 'b", NoSyn)];
    1.49 +
    1.50 +val nullT = Type ("Null", []);
    1.51 +val nullt = Const ("Null", nullT);
    1.52 +
    1.53 +fun mk_typ T =
    1.54 +  Const ("Type", itselfT T --> Type ("Type", [])) $ Logic.mk_type T;
    1.55 +
    1.56 +fun typeof_proc defaultS vs (Const ("typeof", _) $ u) =
    1.57 +      Some (mk_typ (case strip_comb u of
    1.58 +          (Var ((a, i), _), _) =>
    1.59 +            if a mem vs then TFree ("'" ^ a ^ ":" ^ string_of_int i, defaultS)
    1.60 +            else nullT
    1.61 +        | (Free (a, _), _) =>
    1.62 +            if a mem vs then TFree ("'" ^ a, defaultS) else nullT
    1.63 +        | _ => nullT))
    1.64 +  | typeof_proc _ _ _ = None;
    1.65 +
    1.66 +fun rlz_proc (Const ("realizes", Type (_, [Type ("Null", []), _])) $ _ $ t) =
    1.67 +  (case strip_comb t of (Const _, _) => Some t | _ => None)
    1.68 +  | rlz_proc _ = None;
    1.69 +
    1.70 +fun rlz_proc' (Const ("realizes", _) $ _ $ t) = Some t
    1.71 +  | rlz_proc' _ = None;
    1.72 +
    1.73 +val unpack_ixn = apfst implode o apsnd (fst o read_int o tl) o
    1.74 +  take_prefix (not o equal ":") o explode;
    1.75 +
    1.76 +type rules =
    1.77 +  {next: int, rs: ((term * term) list * (term * term)) list,
    1.78 +   net: (int * ((term * term) list * (term * term))) Net.net};
    1.79 +
    1.80 +val empty_rules : rules = {next = 0, rs = [], net = Net.empty};
    1.81 +
    1.82 +fun add_rule (r as (_, (lhs, _)), {next, rs, net} : rules) =
    1.83 +  {next = next - 1, rs = r :: rs, net = Net.insert_term
    1.84 +     ((Pattern.eta_contract lhs, (next, r)), net, K false)};
    1.85 +
    1.86 +fun (merge_rules : rules -> rules -> rules)
    1.87 +  {next, rs = rs1, net} {next = next2, rs = rs2, ...} =
    1.88 +  foldr add_rule (rs2 \\ rs1, {next = next, rs = rs1, net = net});
    1.89 +
    1.90 +fun condrew sign rules procs =
    1.91 +  let
    1.92 +    val tsig = Sign.tsig_of sign;
    1.93 +
    1.94 +    fun rew tm =
    1.95 +      Pattern.rewrite_term tsig [] (condrew' :: procs) tm
    1.96 +    and condrew' tm = get_first (fn (_, (prems, (tm1, tm2))) =>
    1.97 +      let
    1.98 +        fun ren t = if_none (Term.rename_abs tm1 tm t) t;
    1.99 +        val inc = Logic.incr_indexes ([], maxidx_of_term tm + 1);
   1.100 +        val env as (Tenv, tenv) = Pattern.match tsig (inc tm1, tm);
   1.101 +        val prems' = map (pairself (rew o subst_vars env o inc o ren)) prems;
   1.102 +        val env' = Envir.Envir
   1.103 +          {maxidx = foldl Int.max
   1.104 +            (~1, map (Int.max o pairself maxidx_of_term) prems'),
   1.105 +           iTs = Vartab.make Tenv, asol = Vartab.make tenv}
   1.106 +      in Some (Envir.norm_term
   1.107 +        (Pattern.unify (sign, env', prems')) (inc (ren tm2)))
   1.108 +      end handle Pattern.MATCH => None | Pattern.Unif => None)
   1.109 +        (sort (int_ord o pairself fst)
   1.110 +          (Net.match_term rules (Pattern.eta_contract tm)));
   1.111 +
   1.112 +  in rew end;
   1.113 +
   1.114 +val chtype = change_type o Some;
   1.115 +
   1.116 +fun add_prefix a b = NameSpace.pack (a :: NameSpace.unpack b);
   1.117 +
   1.118 +fun msg d s = priority (implode (replicate d " ") ^ s);
   1.119 +
   1.120 +fun vars_of t = rev (foldl_aterms
   1.121 +  (fn (vs, v as Var _) => v ins vs | (vs, _) => vs) ([], t));
   1.122 +
   1.123 +fun vfs_of t = vars_of t @ sort (make_ord atless) (term_frees t);
   1.124 +
   1.125 +fun forall_intr (t, prop) =
   1.126 +  let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
   1.127 +  in all T $ Abs (a, T, abstract_over (t, prop)) end;
   1.128 +
   1.129 +fun forall_intr_prf (t, prf) =
   1.130 +  let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
   1.131 +  in Abst (a, Some T, prf_abstract_over t prf) end;
   1.132 +
   1.133 +val mkabs = foldr (fn (v, t) => Abs ("x", fastype_of v, abstract_over (v, t)));
   1.134 +
   1.135 +fun prf_subst_TVars tye =
   1.136 +  map_proof_terms (subst_TVars tye) (typ_subst_TVars tye);
   1.137 +
   1.138 +fun add_types (Const ("typeof", Type (_, [T, _])), xs) =
   1.139 +      (case strip_type T of (_, Type (s, _)) => s ins xs | _ => xs)
   1.140 +  | add_types (t $ u, xs) = add_types (t, add_types (u, xs))
   1.141 +  | add_types (Abs (_, _, t), xs) = add_types (t, xs)
   1.142 +  | add_types (_, xs) = xs;
   1.143 +
   1.144 +fun relevant_vars types prop = foldr (fn
   1.145 +      (Var ((a, i), T), vs) => (case strip_type T of
   1.146 +        (_, Type (s, _)) => if s mem types then a :: vs else vs
   1.147 +      | _ => vs)
   1.148 +    | (_, vs) => vs) (vars_of prop, []);
   1.149 +
   1.150 +
   1.151 +(**** theory data ****)
   1.152 +
   1.153 +(* data kind 'Pure/extraction' *)
   1.154 +
   1.155 +structure ExtractionArgs =
   1.156 +struct
   1.157 +  val name = "Pure/extraction";
   1.158 +  type T =
   1.159 +    {realizes_eqns : rules,
   1.160 +     typeof_eqns : rules,
   1.161 +     types : string list,
   1.162 +     realizers : (string list * (term * proof)) list Symtab.table,
   1.163 +     defs : thm list,
   1.164 +     expand : (string * term) list,
   1.165 +     prep : (Sign.sg -> proof -> proof) option}
   1.166 +
   1.167 +  val empty =
   1.168 +    {realizes_eqns = empty_rules,
   1.169 +     typeof_eqns = empty_rules,
   1.170 +     types = [],
   1.171 +     realizers = Symtab.empty,
   1.172 +     defs = [],
   1.173 +     expand = [],
   1.174 +     prep = None};
   1.175 +  val copy = I;
   1.176 +  val prep_ext = I;
   1.177 +
   1.178 +  fun merge
   1.179 +    (({realizes_eqns = realizes_eqns1, typeof_eqns = typeof_eqns1, types = types1,
   1.180 +       realizers = realizers1, defs = defs1, expand = expand1, prep = prep1},
   1.181 +      {realizes_eqns = realizes_eqns2, typeof_eqns = typeof_eqns2, types = types2,
   1.182 +       realizers = realizers2, defs = defs2, expand = expand2, prep = prep2}) : T * T) =
   1.183 +    {realizes_eqns = merge_rules realizes_eqns1 realizes_eqns2,
   1.184 +     typeof_eqns = merge_rules typeof_eqns1 typeof_eqns2,
   1.185 +     types = types1 union types2,
   1.186 +     realizers = Symtab.merge_multi' (eq_set o pairself #1)
   1.187 +       (realizers1, realizers2),
   1.188 +     defs = gen_merge_lists eq_thm defs1 defs2,
   1.189 +     expand = merge_lists expand1 expand2,
   1.190 +     prep = (case prep1 of None => prep2 | _ => prep1)};
   1.191 +
   1.192 +  fun print sg (x : T) = ();
   1.193 +end;
   1.194 +
   1.195 +structure ExtractionData = TheoryDataFun(ExtractionArgs);
   1.196 +
   1.197 +fun read_condeq thy =
   1.198 +  let val sg = sign_of (add_syntax thy)
   1.199 +  in fn s =>
   1.200 +    let val t = Logic.varify (term_of (read_cterm sg (s, propT)))
   1.201 +    in (map Logic.dest_equals (Logic.strip_imp_prems t),
   1.202 +      Logic.dest_equals (Logic.strip_imp_concl t))
   1.203 +    end handle TERM _ => error ("Not a (conditional) meta equality:\n" ^ s)
   1.204 +  end;
   1.205 +
   1.206 +(** preprocessor **)
   1.207 +
   1.208 +fun set_preprocessor prep thy =
   1.209 +  let val {realizes_eqns, typeof_eqns, types, realizers,
   1.210 +    defs, expand, ...} = ExtractionData.get thy
   1.211 +  in
   1.212 +    ExtractionData.put
   1.213 +      {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
   1.214 +       realizers = realizers, defs = defs, expand = expand, prep = Some prep} thy
   1.215 +  end;
   1.216 +
   1.217 +(** equations characterizing realizability **)
   1.218 +
   1.219 +fun gen_add_realizes_eqns prep_eq eqns thy =
   1.220 +  let val {realizes_eqns, typeof_eqns, types, realizers,
   1.221 +    defs, expand, prep} = ExtractionData.get thy;
   1.222 +  in
   1.223 +    ExtractionData.put
   1.224 +      {realizes_eqns = foldr add_rule (map (prep_eq thy) eqns, realizes_eqns),
   1.225 +       typeof_eqns = typeof_eqns, types = types, realizers = realizers,
   1.226 +       defs = defs, expand = expand, prep = prep} thy
   1.227 +  end
   1.228 +
   1.229 +val add_realizes_eqns_i = gen_add_realizes_eqns (K I);
   1.230 +val add_realizes_eqns = gen_add_realizes_eqns read_condeq;
   1.231 +
   1.232 +(** equations characterizing type of extracted program **)
   1.233 +
   1.234 +fun gen_add_typeof_eqns prep_eq eqns thy =
   1.235 +  let
   1.236 +    val {realizes_eqns, typeof_eqns, types, realizers,
   1.237 +      defs, expand, prep} = ExtractionData.get thy;
   1.238 +    val eqns' = map (prep_eq thy) eqns;
   1.239 +    val ts = flat (flat
   1.240 +      (map (fn (ps, p) => map (fn (x, y) => [x, y]) (p :: ps)) eqns'))
   1.241 +  in
   1.242 +    ExtractionData.put
   1.243 +      {realizes_eqns = realizes_eqns, realizers = realizers,
   1.244 +       typeof_eqns = foldr add_rule (eqns', typeof_eqns),
   1.245 +       types = foldr add_types (ts, types),
   1.246 +       defs = defs, expand = expand, prep = prep} thy
   1.247 +  end
   1.248 +
   1.249 +val add_typeof_eqns_i = gen_add_typeof_eqns (K I);
   1.250 +val add_typeof_eqns = gen_add_typeof_eqns read_condeq;
   1.251 +
   1.252 +fun thaw (T as TFree (a, S)) =
   1.253 +      if ":" mem explode a then TVar (unpack_ixn a, S) else T
   1.254 +  | thaw (Type (a, Ts)) = Type (a, map thaw Ts)
   1.255 +  | thaw T = T;
   1.256 +
   1.257 +fun freeze (TVar ((a, i), S)) = TFree (a ^ ":" ^ string_of_int i, S)
   1.258 +  | freeze (Type (a, Ts)) = Type (a, map freeze Ts)
   1.259 +  | freeze T = T;
   1.260 +
   1.261 +fun freeze_thaw f x =
   1.262 +  map_term_types thaw (f (map_term_types freeze x));
   1.263 +
   1.264 +fun etype_of sg vs Ts t =
   1.265 +  let
   1.266 +    val {typeof_eqns, ...} = ExtractionData.get_sg sg;
   1.267 +    fun err () = error ("Unable to determine type of extracted program for\n" ^
   1.268 +      Sign.string_of_term sg t);
   1.269 +    val abs = foldr (fn (T, u) => Abs ("x", T, u))
   1.270 +  in case strip_abs_body (freeze_thaw (condrew sg (#net typeof_eqns)
   1.271 +    [typeof_proc (Sign.defaultS sg) vs]) (abs (Ts,
   1.272 +      Const ("typeof", fastype_of1 (Ts, t) --> Type ("Type", [])) $ t))) of
   1.273 +      Const ("Type", _) $ u => (Logic.dest_type u handle TERM _ => err ())
   1.274 +    | _ => err ()
   1.275 +  end;
   1.276 +
   1.277 +(** realizers for axioms / theorems, together with correctness proofs **)
   1.278 +
   1.279 +fun gen_add_realizers prep_rlz rs thy =
   1.280 +  let val {realizes_eqns, typeof_eqns, types, realizers,
   1.281 +    defs, expand, prep} = ExtractionData.get thy
   1.282 +  in
   1.283 +    ExtractionData.put
   1.284 +      {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
   1.285 +       realizers = foldr Symtab.update_multi
   1.286 +         (map (prep_rlz thy) (rev rs), realizers),
   1.287 +       defs = defs, expand = expand, prep = prep} thy
   1.288 +  end
   1.289 +
   1.290 +fun prep_realizer thy =
   1.291 +  let
   1.292 +    val {realizes_eqns, typeof_eqns, defs, ...} =
   1.293 +      ExtractionData.get thy;
   1.294 +    val eqns = Net.merge (#net realizes_eqns, #net typeof_eqns, K false);
   1.295 +    val thy' = add_syntax thy;
   1.296 +    val sign = sign_of thy';
   1.297 +    val tsg = Sign.tsig_of sign;
   1.298 +    val rd = ProofSyntax.read_proof thy' false
   1.299 +  in fn (thm, (vs, s1, s2)) =>
   1.300 +    let
   1.301 +      val name = Thm.name_of_thm thm;
   1.302 +      val _ = assert (name <> "") "add_realizers: unnamed theorem";
   1.303 +      val prop = Pattern.rewrite_term tsg
   1.304 +        (map (Logic.dest_equals o prop_of) defs) [] (prop_of thm);
   1.305 +      val vars = vars_of prop;
   1.306 +      val T = etype_of sign vs [] prop;
   1.307 +      val (T', thw) = Type.freeze_thaw_type
   1.308 +        (if T = nullT then nullT else map fastype_of vars ---> T);
   1.309 +      val t = map_term_types thw (term_of (read_cterm sign (s1, T')));
   1.310 +      val r = foldr forall_intr (vars, freeze_thaw
   1.311 +        (condrew sign eqns [typeof_proc (Sign.defaultS sign) vs, rlz_proc])
   1.312 +          (Const ("realizes", T --> propT --> propT) $
   1.313 +            (if T = nullT then t else list_comb (t, vars)) $ prop));
   1.314 +      val prf = Reconstruct.reconstruct_proof sign r (rd s2);
   1.315 +    in (name, (vs, (t, prf))) end
   1.316 +  end;
   1.317 +
   1.318 +val add_realizers_i = gen_add_realizers
   1.319 +  (fn _ => fn (name, (vs, t, prf)) => (name, (vs, (t, prf))));
   1.320 +val add_realizers = gen_add_realizers prep_realizer;
   1.321 +
   1.322 +(** expanding theorems / definitions **)
   1.323 +
   1.324 +fun add_expand_thm (thy, thm) =
   1.325 +  let
   1.326 +    val {realizes_eqns, typeof_eqns, types, realizers,
   1.327 +      defs, expand, prep} = ExtractionData.get thy;
   1.328 +
   1.329 +    val name = Thm.name_of_thm thm;
   1.330 +    val _ = assert (name <> "") "add_expand_thms: unnamed theorem";
   1.331 +
   1.332 +    val is_def =
   1.333 +      (case strip_comb (fst (Logic.dest_equals (prop_of thm))) of
   1.334 +         (Const _, ts) => forall is_Var ts andalso null (duplicates ts)
   1.335 +           andalso exists (fn thy =>
   1.336 +               is_some (Symtab.lookup (#axioms (rep_theory thy), name)))
   1.337 +             (thy :: ancestors_of thy)
   1.338 +       | _ => false) handle TERM _ => false;
   1.339 +
   1.340 +    val name = Thm.name_of_thm thm;
   1.341 +    val _ = assert (name <> "") "add_expand_thms: unnamed theorem";
   1.342 +  in
   1.343 +    (ExtractionData.put (if is_def then
   1.344 +        {realizes_eqns = realizes_eqns,
   1.345 +         typeof_eqns = add_rule (([],
   1.346 +           Logic.dest_equals (prop_of (Drule.abs_def thm))), typeof_eqns),
   1.347 +         types = types,
   1.348 +         realizers = realizers, defs = gen_ins eq_thm (thm, defs),
   1.349 +         expand = expand, prep = prep}
   1.350 +      else
   1.351 +        {realizes_eqns = realizes_eqns, typeof_eqns = typeof_eqns, types = types,
   1.352 +         realizers = realizers, defs = defs,
   1.353 +         expand = (name, prop_of thm) ins expand, prep = prep}) thy, thm)
   1.354 +  end;
   1.355 +
   1.356 +fun add_expand_thms thms thy = foldl (fst o add_expand_thm) (thy, thms);
   1.357 +
   1.358 +
   1.359 +(**** extract program ****)
   1.360 +
   1.361 +val dummyt = Const ("dummy", dummyT);
   1.362 +
   1.363 +fun extract thms thy =
   1.364 +  let
   1.365 +    val sg = sign_of (add_syntax thy);
   1.366 +    val tsg = Sign.tsig_of sg;
   1.367 +    val {realizes_eqns, typeof_eqns, types, realizers, defs, expand, prep} =
   1.368 +      ExtractionData.get thy;
   1.369 +    val typroc = typeof_proc (Sign.defaultS sg);
   1.370 +    val prep = if_none prep (K I) sg o ProofRewriteRules.elim_defs sg false defs o
   1.371 +      Reconstruct.expand_proof sg (("", None) :: map (apsnd Some) expand);
   1.372 +    val rrews = Net.merge (#net realizes_eqns, #net typeof_eqns, K false);
   1.373 +
   1.374 +    fun find_inst prop Ts ts vs =
   1.375 +      let
   1.376 +        val rvs = relevant_vars types prop;
   1.377 +        val vars = vars_of prop;
   1.378 +        val n = Int.min (length vars, length ts);
   1.379 +
   1.380 +        fun add_args ((Var ((a, i), _), t), (vs', tye)) =
   1.381 +          if a mem rvs then
   1.382 +            let val T = etype_of sg vs Ts t
   1.383 +            in if T = nullT then (vs', tye)
   1.384 +               else (a :: vs', (("'" ^ a, i), T) :: tye)
   1.385 +            end
   1.386 +          else (vs', tye)
   1.387 +
   1.388 +      in foldr add_args (take (n, vars) ~~ take (n, ts), ([], [])) end;
   1.389 +
   1.390 +    fun find vs = apsome snd o find_first (curry eq_set vs o fst);
   1.391 +    fun find' s = map snd o filter (equal s o fst)
   1.392 +
   1.393 +    fun realizes_null vs prop =
   1.394 +      freeze_thaw (condrew sg rrews [typroc vs, rlz_proc])
   1.395 +        (Const ("realizes", nullT --> propT --> propT) $ nullt $ prop);
   1.396 +
   1.397 +    fun corr d defs vs ts Ts hs (PBound i) _ _ = (defs, PBound i)
   1.398 +
   1.399 +      | corr d defs vs ts Ts hs (Abst (s, Some T, prf)) (Abst (_, _, prf')) t =
   1.400 +          let val (defs', corr_prf) = corr d defs vs [] (T :: Ts)
   1.401 +            (dummyt :: hs) prf (incr_pboundvars 1 0 prf')
   1.402 +            (case t of Some (Abs (_, _, u)) => Some u | _ => None)
   1.403 +          in (defs', Abst (s, Some T, corr_prf)) end
   1.404 +
   1.405 +      | corr d defs vs ts Ts hs (AbsP (s, Some prop, prf)) (AbsP (_, _, prf')) t =
   1.406 +          let
   1.407 +            val T = etype_of sg vs Ts prop;
   1.408 +            val u = if T = nullT then 
   1.409 +                (case t of Some u => Some (incr_boundvars 1 u) | None => None)
   1.410 +              else (case t of Some (Abs (_, _, u)) => Some u | _ => None);
   1.411 +            val (defs', corr_prf) = corr d defs vs [] (T :: Ts) (prop :: hs)
   1.412 +              (incr_pboundvars 0 1 prf) (incr_pboundvars 0 1 prf') u;
   1.413 +            val rlz = Const ("realizes", T --> propT --> propT)
   1.414 +          in (defs',
   1.415 +            if T = nullT then AbsP ("R", Some (rlz $ nullt $ prop),
   1.416 +              prf_subst_bounds [nullt] corr_prf)
   1.417 +            else Abst (s, Some T, AbsP ("R",
   1.418 +              Some (rlz $ Bound 0 $ incr_boundvars 1 prop), corr_prf)))
   1.419 +          end
   1.420 +
   1.421 +      | corr d defs vs ts Ts hs (prf % Some t) (prf' % _) t' =
   1.422 +          let val (defs', corr_prf) = corr d defs vs (t :: ts) Ts hs prf prf'
   1.423 +            (case t' of Some (u $ _) => Some u | _ => None)
   1.424 +          in (defs', corr_prf % Some t) end
   1.425 +
   1.426 +      | corr d defs vs ts Ts hs (prf1 %% prf2) (prf1' %% prf2') t =
   1.427 +          let
   1.428 +            val prop = Reconstruct.prop_of' hs prf2';
   1.429 +            val T = etype_of sg vs Ts prop;
   1.430 +            val (defs1, f, u) = if T = nullT then (defs, t, None) else
   1.431 +              (case t of
   1.432 +                 Some (f $ u) => (defs, Some f, Some u)
   1.433 +               | _ =>
   1.434 +                 let val (defs1, u) = extr d defs vs [] Ts hs prf2'
   1.435 +                 in (defs1, None, Some u) end)
   1.436 +            val (defs2, corr_prf1) = corr d defs1 vs [] Ts hs prf1 prf1' f;
   1.437 +            val (defs3, corr_prf2) = corr d defs2 vs [] Ts hs prf2 prf2' u;
   1.438 +          in
   1.439 +            if T = nullT then (defs3, corr_prf1 %% corr_prf2) else
   1.440 +              (defs3, corr_prf1 % u %% corr_prf2)
   1.441 +          end
   1.442 +
   1.443 +      | corr d defs vs ts Ts hs (prf0 as PThm ((name, _), prf, prop, Some Ts')) _ _ =
   1.444 +          let
   1.445 +            val (vs', tye) = find_inst prop Ts ts vs;
   1.446 +            val tye' = (map fst (term_tvars prop) ~~ Ts') @ tye;
   1.447 +            val T = etype_of sg vs' [] prop;
   1.448 +            val defs' = if T = nullT then defs
   1.449 +              else fst (extr d defs vs ts Ts hs prf0)
   1.450 +          in
   1.451 +            if T = nullT andalso realizes_null vs' prop = prop then (defs, prf0)
   1.452 +            else case Symtab.lookup (realizers, name) of
   1.453 +              None => (case find vs' (find' name defs') of
   1.454 +                None =>
   1.455 +                  let
   1.456 +                    val _ = assert (T = nullT) "corr: internal error";
   1.457 +                    val _ = msg d ("Building correctness proof for " ^ quote name ^
   1.458 +                      (if null vs' then ""
   1.459 +                       else " (relevant variables: " ^ commas_quote vs' ^ ")"));
   1.460 +                    val prf' = prep (Reconstruct.reconstruct_proof sg prop prf);
   1.461 +                    val (defs'', corr_prf) =
   1.462 +                      corr (d + 1) defs' vs' [] [] [] prf' prf' None;
   1.463 +                    val args = vfs_of prop;
   1.464 +                    val corr_prf' = foldr forall_intr_prf (args, corr_prf);
   1.465 +                  in
   1.466 +                    ((name, (vs', ((nullt, nullt), corr_prf'))) :: defs',
   1.467 +                     prf_subst_TVars tye' corr_prf')
   1.468 +                  end
   1.469 +              | Some (_, prf') => (defs', prf_subst_TVars tye' prf'))
   1.470 +            | Some rs => (case find vs' rs of
   1.471 +                Some (_, prf') => (defs', prf_subst_TVars tye' prf')
   1.472 +              | None => error ("corr: no realizer for instance of theorem " ^
   1.473 +                  quote name ^ ":\n" ^ Sign.string_of_term sg (Envir.beta_norm
   1.474 +                    (Reconstruct.prop_of (proof_combt (prf0, ts))))))
   1.475 +          end
   1.476 +
   1.477 +      | corr d defs vs ts Ts hs (prf0 as PAxm (s, prop, Some Ts')) _ _ =
   1.478 +          let
   1.479 +            val (vs', tye) = find_inst prop Ts ts vs;
   1.480 +            val tye' = (map fst (term_tvars prop) ~~ Ts') @ tye
   1.481 +          in
   1.482 +            case find vs' (Symtab.lookup_multi (realizers, s)) of
   1.483 +              Some (_, prf) => (defs, prf_subst_TVars tye' prf)
   1.484 +            | None => error ("corr: no realizer for instance of axiom " ^
   1.485 +                quote s ^ ":\n" ^ Sign.string_of_term sg (Envir.beta_norm
   1.486 +                  (Reconstruct.prop_of (proof_combt (prf0, ts)))))
   1.487 +          end
   1.488 +
   1.489 +      | corr d defs vs ts Ts hs _ _ _ = error "corr: bad proof"
   1.490 +
   1.491 +    and extr d defs vs ts Ts hs (PBound i) = (defs, Bound i)
   1.492 +
   1.493 +      | extr d defs vs ts Ts hs (Abst (s, Some T, prf)) =
   1.494 +          let val (defs', t) = extr d defs vs []
   1.495 +            (T :: Ts) (dummyt :: hs) (incr_pboundvars 1 0 prf)
   1.496 +          in (defs', Abs (s, T, t)) end
   1.497 +
   1.498 +      | extr d defs vs ts Ts hs (AbsP (s, Some t, prf)) =
   1.499 +          let
   1.500 +            val T = etype_of sg vs Ts t;
   1.501 +            val (defs', t) = extr d defs vs [] (T :: Ts) (t :: hs)
   1.502 +              (incr_pboundvars 0 1 prf)
   1.503 +          in (defs',
   1.504 +            if T = nullT then subst_bound (nullt, t) else Abs (s, T, t))
   1.505 +          end
   1.506 +
   1.507 +      | extr d defs vs ts Ts hs (prf % Some t) =
   1.508 +          let val (defs', u) = extr d defs vs (t :: ts) Ts hs prf
   1.509 +          in (defs', u $ t) end
   1.510 +
   1.511 +      | extr d defs vs ts Ts hs (prf1 %% prf2) =
   1.512 +          let
   1.513 +            val (defs', f) = extr d defs vs [] Ts hs prf1;
   1.514 +            val prop = Reconstruct.prop_of' hs prf2;
   1.515 +            val T = etype_of sg vs Ts prop
   1.516 +          in
   1.517 +            if T = nullT then (defs', f) else
   1.518 +              let val (defs'', t) = extr d defs' vs [] Ts hs prf2
   1.519 +              in (defs'', f $ t) end
   1.520 +          end
   1.521 +
   1.522 +      | extr d defs vs ts Ts hs (prf0 as PThm ((s, _), prf, prop, Some Ts')) =
   1.523 +          let
   1.524 +            val (vs', tye) = find_inst prop Ts ts vs;
   1.525 +            val tye' = (map fst (term_tvars prop) ~~ Ts') @ tye
   1.526 +          in
   1.527 +            case Symtab.lookup (realizers, s) of
   1.528 +              None => (case find vs' (find' s defs) of
   1.529 +                None =>
   1.530 +                  let
   1.531 +                    val _ = msg d ("Extracting " ^ quote s ^
   1.532 +                      (if null vs' then ""
   1.533 +                       else " (relevant variables: " ^ commas_quote vs' ^ ")"));
   1.534 +                    val prf' = prep (Reconstruct.reconstruct_proof sg prop prf);
   1.535 +                    val (defs', t) = extr (d + 1) defs vs' [] [] [] prf';
   1.536 +                    val (defs'', corr_prf) =
   1.537 +                      corr (d + 1) defs' vs' [] [] [] prf' prf' (Some t);
   1.538 +
   1.539 +                    val nt = Envir.beta_norm t;
   1.540 +                    val args = vfs_of prop;
   1.541 +                    val args' = filter (fn v => Logic.occs (v, nt)) args;
   1.542 +                    val t' = mkabs (args', nt);
   1.543 +                    val T = fastype_of t';
   1.544 +                    val cname = add_prefix "extr" (space_implode "_" (s :: vs'));
   1.545 +                    val c = Const (cname, T);
   1.546 +                    val u = mkabs (args, list_comb (c, args'));
   1.547 +                    val eqn = Logic.mk_equals (c, t');
   1.548 +                    val rlz =
   1.549 +                      Const ("realizes", fastype_of nt --> propT --> propT);
   1.550 +                    val lhs = rlz $ nt $ prop;
   1.551 +                    val rhs = rlz $ list_comb (c, args') $ prop;
   1.552 +                    val f = Abs ("x", T, rlz $ list_comb (Bound 0, args') $ prop);
   1.553 +
   1.554 +                    val corr_prf' = foldr forall_intr_prf (args,
   1.555 +                      ProofRewriteRules.rewrite_terms
   1.556 +                        (freeze_thaw (condrew sg rrews [typroc vs', rlz_proc]))
   1.557 +                        (Proofterm.rewrite_proof_notypes ([], [])
   1.558 +                          (chtype [] equal_elim_axm %> lhs %> rhs %%
   1.559 +                            (chtype [propT] symmetric_axm %> rhs %> lhs %%
   1.560 +                              (chtype [propT, T] combination_axm %> f %> f %> c %> t' %%
   1.561 +                                (chtype [T --> propT] reflexive_axm %> f) %%
   1.562 +                                PAxm (cname ^ "_def", eqn,
   1.563 +                                  Some (map TVar (term_tvars eqn))))) %%
   1.564 +                            corr_prf)))
   1.565 +                  in
   1.566 +                    ((s, (vs', ((t', u), corr_prf'))) :: defs',
   1.567 +                     subst_TVars tye' u)
   1.568 +                  end
   1.569 +              | Some ((_, u), _) => (defs, subst_TVars tye' u))
   1.570 +            | Some rs => (case find vs' rs of
   1.571 +                Some (t, _) => (defs, subst_TVars tye' t)
   1.572 +              | None => error ("extr: no realizer for instance of theorem " ^
   1.573 +                  quote s ^ ":\n" ^ Sign.string_of_term sg (Envir.beta_norm
   1.574 +                    (Reconstruct.prop_of (proof_combt (prf0, ts))))))
   1.575 +          end
   1.576 +
   1.577 +      | extr d defs vs ts Ts hs (prf0 as PAxm (s, prop, Some Ts')) =
   1.578 +          let
   1.579 +            val (vs', tye) = find_inst prop Ts ts vs;
   1.580 +            val tye' = (map fst (term_tvars prop) ~~ Ts') @ tye
   1.581 +          in
   1.582 +            case find vs' (Symtab.lookup_multi (realizers, s)) of
   1.583 +              Some (t, _) => (defs, subst_TVars tye' t)
   1.584 +            | None => error ("no realizer for instance of axiom " ^
   1.585 +                quote s ^ ":\n" ^ Sign.string_of_term sg (Envir.beta_norm
   1.586 +                  (Reconstruct.prop_of (proof_combt (prf0, ts)))))
   1.587 +          end
   1.588 +
   1.589 +      | extr d defs vs ts Ts hs _ = error "extr: bad proof";
   1.590 +
   1.591 +    fun prep_thm thm =
   1.592 +      let
   1.593 +        val {prop, der = (_, prf), sign, ...} = rep_thm thm;
   1.594 +        val name = Thm.name_of_thm thm;
   1.595 +        val _ = assert (name <> "") "extraction: unnamed theorem";
   1.596 +        val _ = assert (etype_of sg [] [] prop <> nullT) ("theorem " ^
   1.597 +          quote name ^ " has no computational content")
   1.598 +      in (name, Reconstruct.reconstruct_proof sign prop prf) end;
   1.599 +
   1.600 +    val (names, prfs) = ListPair.unzip (map prep_thm thms);
   1.601 +    val defs = foldl (fn (defs, prf) =>
   1.602 +      fst (extr 0 defs [] [] [] [] prf)) ([], prfs);
   1.603 +    val {path, ...} = Sign.rep_sg sg;
   1.604 +
   1.605 +    fun add_def ((s, (vs, ((t, u), _))), thy) = 
   1.606 +      let
   1.607 +        val ft = fst (Type.freeze_thaw t);
   1.608 +        val fu = fst (Type.freeze_thaw u);
   1.609 +        val name = add_prefix "extr" (space_implode "_" (s :: vs))
   1.610 +      in case Sign.const_type (sign_of thy) name of
   1.611 +          None => if t = nullt then thy else thy |>
   1.612 +            Theory.add_consts_i [(name, fastype_of ft, NoSyn)] |>
   1.613 +            fst o PureThy.add_defs_i false [((name ^ "_def",
   1.614 +              Logic.mk_equals (head_of (strip_abs_body fu), ft)), [])]
   1.615 +        | Some _ => thy
   1.616 +      end;
   1.617 +
   1.618 +    fun add_thm ((s, (vs, (_, prf))), thy) = fst (PureThy.store_thm
   1.619 +          ((add_prefix "extr" (space_implode "_" (s :: vs)) ^
   1.620 +            "_correctness", standard (gen_all (ProofChecker.thm_of_proof thy
   1.621 +              (fst (Proofterm.freeze_thaw_prf (ProofRewriteRules.rewrite_terms
   1.622 +                (Pattern.rewrite_term (Sign.tsig_of (sign_of thy)) []
   1.623 +                  [rlz_proc']) prf)))))), []) thy)
   1.624 +      | add_thm (_, thy) = thy
   1.625 +
   1.626 +  in thy |>
   1.627 +    Theory.absolute_path |>
   1.628 +    curry (foldr add_def) defs |>
   1.629 +    curry (foldr add_thm) (filter (fn (s, _) => s mem names) defs) |>
   1.630 +    Theory.add_path (NameSpace.pack (if_none path []))
   1.631 +  end;
   1.632 +
   1.633 +
   1.634 +(**** interface ****)
   1.635 +
   1.636 +structure P = OuterParse and K = OuterSyntax.Keyword;
   1.637 +
   1.638 +val realizersP =
   1.639 +  OuterSyntax.command "realizers"
   1.640 +  "specify realizers for primitive axioms / theorems, together with correctness proof"
   1.641 +  K.thy_decl
   1.642 +    (Scan.repeat1 (P.xname --
   1.643 +       Scan.optional (P.$$$ "(" |-- P.list1 P.name --| P.$$$ ")") [] --|
   1.644 +       P.$$$ ":" -- P.string -- P.string) >>
   1.645 +     (fn xs => Toplevel.theory (fn thy => add_realizers
   1.646 +       (map (fn (((a, vs), s1), s2) =>
   1.647 +         (PureThy.get_thm thy a, (vs, s1, s2))) xs) thy)));
   1.648 +
   1.649 +val realizabilityP =
   1.650 +  OuterSyntax.command "realizability"
   1.651 +  "add equations characterizing realizability" K.thy_decl
   1.652 +  (Scan.repeat1 P.string >> (Toplevel.theory o add_realizes_eqns));
   1.653 +
   1.654 +val typeofP =
   1.655 +  OuterSyntax.command "extract_type"
   1.656 +  "add equations characterizing type of extracted program" K.thy_decl
   1.657 +  (Scan.repeat1 P.string >> (Toplevel.theory o add_typeof_eqns));
   1.658 +
   1.659 +val extractP =
   1.660 +  OuterSyntax.command "extract" "extract terms from proofs" K.thy_decl
   1.661 +    (Scan.repeat1 P.xname >> (fn xs => Toplevel.theory
   1.662 +      (fn thy => extract (map (PureThy.get_thm thy) xs) thy)));
   1.663 +
   1.664 +val parsers = [realizersP, realizabilityP, typeofP, extractP];
   1.665 +
   1.666 +val setup =
   1.667 +  [ExtractionData.init,
   1.668 +
   1.669 +   add_typeof_eqns
   1.670 +     ["(typeof (PROP P)) == (Type (TYPE(Null))) ==>  \
   1.671 +    \  (typeof (PROP Q)) == (Type (TYPE('Q))) ==>  \
   1.672 +    \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE('Q)))",
   1.673 +
   1.674 +      "(typeof (PROP Q)) == (Type (TYPE(Null))) ==>  \
   1.675 +    \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE(Null)))",
   1.676 +
   1.677 +      "(typeof (PROP P)) == (Type (TYPE('P))) ==>  \
   1.678 +    \  (typeof (PROP Q)) == (Type (TYPE('Q))) ==>  \
   1.679 +    \    (typeof (PROP P ==> PROP Q)) == (Type (TYPE('P => 'Q)))",
   1.680 +
   1.681 +      "(%x. typeof (PROP P (x))) == (%x. Type (TYPE(Null))) ==>  \
   1.682 +    \    (typeof (!!x. PROP P (x))) == (Type (TYPE(Null)))",
   1.683 +
   1.684 +      "(%x. typeof (PROP P (x))) == (%x. Type (TYPE('P))) ==>  \
   1.685 +    \    (typeof (!!x::'a. PROP P (x))) == (Type (TYPE('a => 'P)))",
   1.686 +
   1.687 +      "(%x. typeof (f (x))) == (%x. Type (TYPE('f))) ==>  \
   1.688 +    \    (typeof (f)) == (Type (TYPE('f)))"],
   1.689 +
   1.690 +   add_realizes_eqns
   1.691 +     ["(typeof (PROP P)) == (Type (TYPE(Null))) ==>  \
   1.692 +    \    (realizes (r) (PROP P ==> PROP Q)) ==  \
   1.693 +    \    (PROP realizes (Null) (PROP P) ==> PROP realizes (r) (PROP Q))",
   1.694 +
   1.695 +      "(typeof (PROP P)) == (Type (TYPE('P))) ==>  \
   1.696 +    \  (typeof (PROP Q)) == (Type (TYPE(Null))) ==>  \
   1.697 +    \    (realizes (r) (PROP P ==> PROP Q)) ==  \
   1.698 +    \    (!!x::'P. PROP realizes (x) (PROP P) ==> PROP realizes (Null) (PROP Q))",
   1.699 +
   1.700 +      "(realizes (r) (PROP P ==> PROP Q)) ==  \
   1.701 +    \  (!!x. PROP realizes (x) (PROP P) ==> PROP realizes (r (x)) (PROP Q))",
   1.702 +
   1.703 +      "(%x. typeof (PROP P (x))) == (%x. Type (TYPE(Null))) ==>  \
   1.704 +    \    (realizes (r) (!!x. PROP P (x))) ==  \
   1.705 +    \    (!!x. PROP realizes (Null) (PROP P (x)))",
   1.706 +
   1.707 +      "(realizes (r) (!!x. PROP P (x))) ==  \
   1.708 +    \  (!!x. PROP realizes (r (x)) (PROP P (x)))"],
   1.709 +
   1.710 +   Attrib.add_attributes
   1.711 +     [("extraction_expand",
   1.712 +       (Attrib.no_args add_expand_thm, K Attrib.undef_local_attribute),
   1.713 +       "specify theorems / definitions to be expanded during extraction")]];
   1.714 +
   1.715 +end;
   1.716 +
   1.717 +OuterSyntax.add_parsers Extraction.parsers;