src/Pure/Isar/code_unit.ML
author haftmann
Tue Jul 15 16:02:10 2008 +0200 (2008-07-15)
changeset 27610 8882d47e075f
parent 27582 367aff8d7ffd
child 28015 11635f41abc1
permissions -rw-r--r--
tuned
     1 (*  Title:      Pure/Isar/code_unit.ML
     2     ID:         $Id$
     3     Author:     Florian Haftmann, TU Muenchen
     4 
     5 Basic notions of code generation.  Auxiliary.
     6 *)
     7 
     8 signature CODE_UNIT =
     9 sig
    10   (*generic non-sense*)
    11   val bad_thm: string -> 'a
    12   val error_thm: (thm -> thm) -> thm -> thm
    13   val warning_thm: (thm -> thm) -> thm -> thm option
    14   val try_thm: (thm -> thm) -> thm -> thm option
    15 
    16   (*typ instantiations*)
    17   val typscheme: theory -> string * typ -> (string * sort) list * typ
    18   val inst_thm: sort Vartab.table -> thm -> thm
    19   val constrain_thm: sort -> thm -> thm
    20 
    21   (*constant aliasses*)
    22   val add_const_alias: thm -> theory -> theory
    23   val subst_alias: theory -> string -> string
    24   val resubst_alias: theory -> string -> string
    25   val triv_classes: theory -> class list
    26 
    27   (*constants*)
    28   val string_of_typ: theory -> typ -> string
    29   val string_of_const: theory -> string -> string
    30   val no_args: theory -> string -> int
    31   val check_const: theory -> term -> string
    32   val read_bare_const: theory -> string -> string * typ
    33   val read_const: theory -> string -> string
    34 
    35   (*constructor sets*)
    36   val constrset_of_consts: theory -> (string * typ) list
    37     -> string * ((string * sort) list * (string * typ list) list)
    38 
    39   (*defining equations*)
    40   val assert_rew: thm -> thm
    41   val mk_rew: thm -> thm
    42   val mk_func: thm -> thm
    43   val head_func: thm -> string * ((string * sort) list * typ)
    44   val expand_eta: int -> thm -> thm
    45   val rewrite_func: simpset -> thm -> thm
    46   val rewrite_head: thm list -> thm -> thm
    47   val norm_args: thm list -> thm list 
    48   val norm_varnames: (string -> string) -> (string -> string) -> thm list -> thm list
    49 
    50   (*case certificates*)
    51   val case_cert: thm -> string * (int * string list)
    52 end;
    53 
    54 structure CodeUnit: CODE_UNIT =
    55 struct
    56 
    57 
    58 (* auxiliary *)
    59 
    60 exception BAD_THM of string;
    61 fun bad_thm msg = raise BAD_THM msg;
    62 fun error_thm f thm = f thm handle BAD_THM msg => error msg;
    63 fun warning_thm f thm = SOME (f thm) handle BAD_THM msg
    64   => (warning ("code generator: " ^ msg); NONE);
    65 fun try_thm f thm = SOME (f thm) handle BAD_THM _ => NONE;
    66 
    67 fun string_of_typ thy = setmp show_sorts true (Syntax.string_of_typ_global thy);
    68 fun string_of_const thy c = case AxClass.inst_of_param thy c
    69  of SOME (c, tyco) => Sign.extern_const thy c ^ " " ^ enclose "[" "]" (Sign.extern_type thy tyco)
    70   | NONE => Sign.extern_const thy c;
    71 
    72 fun no_args thy = length o fst o strip_type o Sign.the_const_type thy;
    73 
    74 
    75 (* utilities *)
    76 
    77 fun typscheme thy (c, ty) =
    78   let
    79     fun dest (TVar ((v, 0), sort)) = (v, sort)
    80       | dest ty = error ("Illegal type parameter in type scheme: " ^ Syntax.string_of_typ_global thy ty);
    81     val vs = map dest (Sign.const_typargs thy (c, ty));
    82   in (vs, ty) end;
    83 
    84 fun inst_thm tvars' thm =
    85   let
    86     val thy = Thm.theory_of_thm thm;
    87     val tvars = (Term.add_tvars o Thm.prop_of) thm [];
    88     fun mk_inst (tvar as (v, _)) = case Vartab.lookup tvars' v
    89      of SOME sort => SOME (pairself (Thm.ctyp_of thy o TVar) (tvar, (v, sort)))
    90       | NONE => NONE;
    91     val insts = map_filter mk_inst tvars;
    92   in Thm.instantiate (insts, []) thm end;
    93 
    94 fun constrain_thm sort thm =
    95   let
    96     val thy = Thm.theory_of_thm thm;
    97     val constrain = curry (Sorts.inter_sort (Sign.classes_of thy)) sort
    98     val tvars = (Term.add_tvars o Thm.prop_of) thm [];
    99     fun mk_inst (tvar as (v, sort)) = pairself (Thm.ctyp_of thy o TVar o pair v)
   100       (sort, constrain sort)
   101     val insts = map mk_inst tvars;
   102   in Thm.instantiate (insts, []) thm end;
   103 
   104 fun expand_eta k thm =
   105   let
   106     val thy = Thm.theory_of_thm thm;
   107     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm;
   108     val (head, args) = strip_comb lhs;
   109     val l = if k = ~1
   110       then (length o fst o strip_abs) rhs
   111       else Int.max (0, k - length args);
   112     val used = Name.make_context (map (fst o fst) (Term.add_vars lhs []));
   113     fun get_name _ 0 = pair []
   114       | get_name (Abs (v, ty, t)) k =
   115           Name.variants [v]
   116           ##>> get_name t (k - 1)
   117           #>> (fn ([v'], vs') => (v', ty) :: vs')
   118       | get_name t k = 
   119           let
   120             val (tys, _) = (strip_type o fastype_of) t
   121           in case tys
   122            of [] => raise TERM ("expand_eta", [t])
   123             | ty :: _ =>
   124                 Name.variants [""]
   125                 #-> (fn [v] => get_name (t $ Var ((v, 0), ty)) (k - 1)
   126                 #>> (fn vs' => (v, ty) :: vs'))
   127           end;
   128     val (vs, _) = get_name rhs l used;
   129     fun expand (v, ty) thm = Drule.fun_cong_rule thm
   130       (Thm.cterm_of thy (Var ((v, 0), ty)));
   131   in
   132     thm
   133     |> fold expand vs
   134     |> Conv.fconv_rule Drule.beta_eta_conversion
   135   end;
   136 
   137 fun func_conv conv =
   138   let
   139     fun lhs_conv ct = if can Thm.dest_comb ct
   140       then (Conv.combination_conv lhs_conv conv) ct
   141       else Conv.all_conv ct;
   142   in Conv.combination_conv (Conv.arg_conv lhs_conv) conv end;
   143 
   144 fun head_conv conv =
   145   let
   146     fun lhs_conv ct = if can Thm.dest_comb ct
   147       then (Conv.fun_conv lhs_conv) ct
   148       else conv ct;
   149   in Conv.fun_conv (Conv.arg_conv lhs_conv) end;
   150 
   151 val rewrite_func = Conv.fconv_rule o func_conv o Simplifier.rewrite;
   152 val rewrite_head = Conv.fconv_rule o head_conv o MetaSimplifier.rewrite false;
   153 
   154 fun norm_args thms =
   155   let
   156     val num_args_of = length o snd o strip_comb o fst o Logic.dest_equals;
   157     val k = fold (curry Int.max o num_args_of o Thm.plain_prop_of) thms 0;
   158   in
   159     thms
   160     |> map (expand_eta k)
   161     |> map (Conv.fconv_rule Drule.beta_eta_conversion)
   162   end;
   163 
   164 fun canonical_tvars purify_tvar thm =
   165   let
   166     val ctyp = Thm.ctyp_of (Thm.theory_of_thm thm);
   167     fun tvars_subst_for thm = (fold_types o fold_atyps)
   168       (fn TVar (v_i as (v, _), sort) => let
   169             val v' = purify_tvar v
   170           in if v = v' then I
   171           else insert (op =) (v_i, (v', sort)) end
   172         | _ => I) (prop_of thm) [];
   173     fun mk_inst (v_i, (v', sort)) (maxidx, acc) =
   174       let
   175         val ty = TVar (v_i, sort)
   176       in
   177         (maxidx + 1, (ctyp ty, ctyp (TVar ((v', maxidx), sort))) :: acc)
   178       end;
   179     val maxidx = Thm.maxidx_of thm + 1;
   180     val (_, inst) = fold mk_inst (tvars_subst_for thm) (maxidx + 1, []);
   181   in Thm.instantiate (inst, []) thm end;
   182 
   183 fun canonical_vars purify_var thm =
   184   let
   185     val cterm = Thm.cterm_of (Thm.theory_of_thm thm);
   186     fun vars_subst_for thm = fold_aterms
   187       (fn Var (v_i as (v, _), ty) => let
   188             val v' = purify_var v
   189           in if v = v' then I
   190           else insert (op =) (v_i, (v', ty)) end
   191         | _ => I) (prop_of thm) [];
   192     fun mk_inst (v_i as (v, i), (v', ty)) (maxidx, acc) =
   193       let
   194         val t = Var (v_i, ty)
   195       in
   196         (maxidx + 1, (cterm t, cterm (Var ((v', maxidx), ty))) :: acc)
   197       end;
   198     val maxidx = Thm.maxidx_of thm + 1;
   199     val (_, inst) = fold mk_inst (vars_subst_for thm) (maxidx + 1, []);
   200   in Thm.instantiate ([], inst) thm end;
   201 
   202 fun canonical_absvars purify_var thm =
   203   let
   204     val t = Thm.plain_prop_of thm;
   205     val t' = Term.map_abs_vars purify_var t;
   206   in Thm.rename_boundvars t t' thm end;
   207 
   208 fun norm_varnames purify_tvar purify_var thms =
   209   let
   210     fun burrow_thms f [] = []
   211       | burrow_thms f thms =
   212           thms
   213           |> Conjunction.intr_balanced
   214           |> f
   215           |> Conjunction.elim_balanced (length thms)
   216   in
   217     thms
   218     |> burrow_thms (canonical_tvars purify_tvar)
   219     |> map (canonical_vars purify_var)
   220     |> map (canonical_absvars purify_var)
   221     |> map Drule.zero_var_indexes
   222   end;
   223 
   224 (* const aliasses *)
   225 
   226 structure ConstAlias = TheoryDataFun
   227 (
   228   type T = ((string * string) * thm) list * class list;
   229   val empty = ([], []);
   230   val copy = I;
   231   val extend = I;
   232   fun merge _ ((alias1, classes1), (alias2, classes2)) =
   233     (Library.merge (eq_snd Thm.eq_thm_prop) (alias1, alias2),
   234       Library.merge (op =) (classes1, classes2));
   235 );
   236 
   237 fun add_const_alias thm =
   238   let
   239     val t = Thm.prop_of thm;
   240     val thy = Thm.theory_of_thm thm;
   241     val lhs_rhs = case try Logic.dest_equals t
   242      of SOME lhs_rhs => lhs_rhs
   243       | _ => error ("Not an equation: " ^ Display.string_of_thm thm);
   244     val c_c' = case try (pairself (AxClass.unoverload_const thy o dest_Const)) lhs_rhs
   245      of SOME c_c' => c_c'
   246       | _ => error ("Not an equation with two constants: " ^ Display.string_of_thm thm);
   247     val some_class = the_list (AxClass.class_of_param thy (snd c_c'));
   248   in
   249     ConstAlias.map (fn (alias, classes) =>
   250       ((c_c', thm) :: alias, fold (insert (op =)) some_class classes))
   251   end;
   252 
   253 fun rew_alias thm =
   254   let
   255     val thy = Thm.theory_of_thm thm;
   256   in rewrite_head ((map snd o fst o ConstAlias.get) thy) thm end;
   257 
   258 fun subst_alias thy c = ConstAlias.get thy
   259   |> fst
   260   |> get_first (fn ((c', c''), _) => if c = c' then SOME c'' else NONE)
   261   |> the_default c;
   262 
   263 fun resubst_alias thy =
   264   let
   265     val alias = fst (ConstAlias.get thy);
   266     val subst_inst_param = Option.map fst o AxClass.inst_of_param thy;
   267     fun subst_alias c =
   268       get_first (fn ((c', c''), _) => if c = c'' then SOME c' else NONE) alias;
   269   in
   270     perhaps subst_inst_param
   271     #> perhaps subst_alias
   272   end;
   273 
   274 val triv_classes = snd o ConstAlias.get;
   275 
   276 (* reading constants as terms *)
   277 
   278 fun check_bare_const thy t = case try dest_Const t
   279  of SOME c_ty => c_ty
   280   | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   281 
   282 fun check_const thy = subst_alias thy o AxClass.unoverload_const thy o apfst (subst_alias thy)
   283   o check_bare_const thy;
   284 
   285 fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
   286 
   287 fun read_const thy = subst_alias thy o AxClass.unoverload_const thy o apfst (subst_alias thy)
   288   o read_bare_const thy;
   289 
   290 
   291 (* constructor sets *)
   292 
   293 fun constrset_of_consts thy cs =
   294   let
   295     fun no_constr (c, ty) = error ("Not a datatype constructor: " ^ string_of_const thy c
   296       ^ " :: " ^ string_of_typ thy ty);
   297     fun last_typ c_ty ty =
   298       let
   299         val frees = typ_tfrees ty;
   300         val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) ty
   301           handle TYPE _ => no_constr c_ty
   302         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr c_ty else ();
   303         val _ = if length frees <> length vs then no_constr c_ty else ();
   304       in (tyco, vs) end;
   305     fun ty_sorts (c, ty) =
   306       let
   307         val ty_decl = (Logic.unvarifyT o Sign.the_const_type thy) c;
   308         val (tyco, _) = last_typ (c, ty) ty_decl;
   309         val (_, vs) = last_typ (c, ty) ty;
   310       in ((tyco, map snd vs), (c, (map fst vs, ty_decl))) end;
   311     fun add ((tyco', sorts'), c) ((tyco, sorts), cs) =
   312       let
   313         val _ = if tyco' <> tyco
   314           then error "Different type constructors in constructor set"
   315           else ();
   316         val sorts'' = map2 (curry (Sorts.inter_sort (Sign.classes_of thy))) sorts' sorts
   317       in ((tyco, sorts), c :: cs) end;
   318     fun inst vs' (c, (vs, ty)) =
   319       let
   320         val the_v = the o AList.lookup (op =) (vs ~~ vs');
   321         val ty' = map_atyps (fn TFree (v, _) => TFree (the_v v)) ty;
   322       in (c, (fst o strip_type) ty') end;
   323     val c' :: cs' = map ty_sorts cs;
   324     val ((tyco, sorts), cs'') = fold add cs' (apsnd single c');
   325     val vs = Name.names Name.context Name.aT sorts;
   326     val cs''' = map (inst vs) cs'';
   327   in (tyco, (vs, cs''')) end;
   328 
   329 
   330 (* rewrite theorems *)
   331 
   332 fun assert_rew thm =
   333   let
   334     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   335       handle TERM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm)
   336           | THM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm);
   337     fun vars_of t = fold_aterms
   338      (fn Var (v, _) => insert (op =) v
   339        | Free _ => bad_thm ("Illegal free variable in rewrite theorem\n"
   340            ^ Display.string_of_thm thm)
   341        | _ => I) t [];
   342     fun tvars_of t = fold_term_types
   343      (fn _ => fold_atyps (fn TVar (v, _) => insert (op =) v
   344                           | TFree _ => bad_thm 
   345       ("Illegal free type variable in rewrite theorem\n" ^ Display.string_of_thm thm))) t [];
   346     val lhs_vs = vars_of lhs;
   347     val rhs_vs = vars_of rhs;
   348     val lhs_tvs = tvars_of lhs;
   349     val rhs_tvs = tvars_of lhs;
   350     val _ = if null (subtract (op =) lhs_vs rhs_vs)
   351       then ()
   352       else bad_thm ("Free variables on right hand side of rewrite theorem\n"
   353         ^ Display.string_of_thm thm);
   354     val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
   355       then ()
   356       else bad_thm ("Free type variables on right hand side of rewrite theorem\n"
   357         ^ Display.string_of_thm thm)
   358   in thm end;
   359 
   360 fun mk_rew thm =
   361   let
   362     val thy = Thm.theory_of_thm thm;
   363     val ctxt = ProofContext.init thy;
   364   in
   365     thm
   366     |> LocalDefs.meta_rewrite_rule ctxt
   367     |> assert_rew
   368   end;
   369 
   370 
   371 (* defining equations *)
   372 
   373 fun assert_func thm =
   374   let
   375     val thy = Thm.theory_of_thm thm;
   376     val (head, args) = (strip_comb o fst o Logic.dest_equals
   377       o ObjectLogic.drop_judgment thy o Thm.plain_prop_of) thm;
   378     val _ = case head of Const _ => () | _ =>
   379       bad_thm ("Equation not headed by constant\n" ^ Display.string_of_thm thm);
   380     val _ =
   381       if has_duplicates (op =)
   382         ((fold o fold_aterms) (fn Var (v, _) => cons v
   383           | _ => I
   384         ) args [])
   385       then bad_thm ("Duplicated variables on left hand side of equation\n"
   386         ^ Display.string_of_thm thm)
   387       else ()
   388     fun check _ (Abs _) = bad_thm
   389           ("Abstraction on left hand side of equation\n"
   390             ^ Display.string_of_thm thm)
   391       | check 0 (Var _) = ()
   392       | check _ (Var _) = bad_thm
   393           ("Variable with application on left hand side of defining equation\n"
   394             ^ Display.string_of_thm thm)
   395       | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
   396       | check n (Const (_, ty)) = if n <> (length o fst o strip_type) ty
   397           then bad_thm
   398             ("Partially applied constant on left hand side of equation\n"
   399                ^ Display.string_of_thm thm)
   400           else ();
   401     val _ = map (check 0) args;
   402   in thm end;
   403 
   404 val mk_func = rew_alias o assert_func o mk_rew;
   405 
   406 fun head_func thm =
   407   let
   408     val thy = Thm.theory_of_thm thm;
   409     val Const (c, ty) = (fst o strip_comb o fst o Logic.dest_equals
   410       o Thm.plain_prop_of) thm;
   411   in (c, typscheme thy (c, ty)) end;
   412 
   413 
   414 (* case cerificates *)
   415 
   416 fun case_certificate thm =
   417   let
   418     val thy = Thm.theory_of_thm thm;
   419     val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
   420       o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.prop_of) thm;
   421     val _ = case head of Free _ => true
   422       | Var _ => true
   423       | _ => raise TERM ("case_cert", []);
   424     val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
   425     val (Const (case_const, _), raw_params) = strip_comb case_expr;
   426     val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
   427     val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
   428     val params = map (fst o dest_Var) (nth_drop n raw_params);
   429     fun dest_case t =
   430       let
   431         val (head' $ t_co, rhs) = Logic.dest_equals t;
   432         val _ = if head' = head then () else raise TERM ("case_cert", []);
   433         val (Const (co, _), args) = strip_comb t_co;
   434         val (Var (param, _), args') = strip_comb rhs;
   435         val _ = if args' = args then () else raise TERM ("case_cert", []);
   436       in (param, co) end;
   437     fun analyze_cases cases =
   438       let
   439         val co_list = fold (AList.update (op =) o dest_case) cases [];
   440       in map (the o AList.lookup (op =) co_list) params end;
   441     fun analyze_let t =
   442       let
   443         val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
   444         val _ = if head' = head then () else raise TERM ("case_cert", []);
   445         val _ = if arg' = arg then () else raise TERM ("case_cert", []);
   446         val _ = if [param'] = params then () else raise TERM ("case_cert", []);
   447       in [] end;
   448     fun analyze (cases as [let_case]) =
   449           (analyze_cases cases handle Bind => analyze_let let_case)
   450       | analyze cases = analyze_cases cases;
   451   in (case_const, (n, analyze cases)) end;
   452 
   453 fun case_cert thm = case_certificate thm
   454   handle Bind => error "bad case certificate"
   455       | TERM _ => error "bad case certificate";
   456 
   457 end;