src/Pure/Isar/code_unit.ML
author wenzelm
Sun Mar 01 23:36:12 2009 +0100 (2009-03-01)
changeset 30190 479806475f3c
parent 30022 1d8b8fa19074
child 30688 2d1d426e00e4
permissions -rw-r--r--
use long names for old-style fold combinators;
     1 (*  Title:      Pure/Isar/code_unit.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Basic notions of code generation.  Auxiliary.
     5 *)
     6 
     7 signature CODE_UNIT =
     8 sig
     9   (*generic non-sense*)
    10   val bad_thm: string -> 'a
    11   val error_thm: ('a -> 'b) -> 'a -> 'b
    12   val warning_thm: ('a -> 'b) -> 'a -> 'b option
    13   val try_thm: ('a -> 'b) -> 'a -> 'b option
    14 
    15   (*typ instantiations*)
    16   val typscheme: theory -> string * typ -> (string * sort) list * typ
    17   val inst_thm: theory -> sort Vartab.table -> thm -> thm
    18   val constrain_thm: theory -> sort -> thm -> thm
    19 
    20   (*constant aliasses*)
    21   val add_const_alias: thm -> theory -> theory
    22   val triv_classes: theory -> class list
    23   val resubst_alias: theory -> string -> string
    24 
    25   (*constants*)
    26   val string_of_typ: theory -> typ -> string
    27   val string_of_const: theory -> string -> string
    28   val no_args: theory -> string -> int
    29   val check_const: theory -> term -> string
    30   val read_bare_const: theory -> string -> string * typ
    31   val read_const: theory -> string -> string
    32 
    33   (*constructor sets*)
    34   val constrset_of_consts: theory -> (string * typ) list
    35     -> string * ((string * sort) list * (string * typ list) list)
    36 
    37   (*code equations*)
    38   val assert_eqn: theory -> thm -> thm
    39   val mk_eqn: theory -> thm -> thm * bool
    40   val assert_linear: (string -> bool) -> thm * bool -> thm * bool
    41   val const_eqn: thm -> string
    42   val const_typ_eqn: thm -> string * typ
    43   val head_eqn: theory -> thm -> string * ((string * sort) list * typ)
    44   val expand_eta: theory -> int -> thm -> thm
    45   val rewrite_eqn: simpset -> thm -> thm
    46   val rewrite_head: thm list -> thm -> thm
    47   val norm_args: theory -> thm list -> thm list 
    48   val norm_varnames: theory -> (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 Code_Unit: 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     val ty' = Logic.unvarifyT ty;
    80     fun dest (TFree (v, sort)) = (v, sort)
    81       | dest ty = error ("Illegal type parameter in type scheme: " ^ Syntax.string_of_typ_global thy ty);
    82     val vs = map dest (Sign.const_typargs thy (c, ty'));
    83   in (vs, Type.strip_sorts ty') end;
    84 
    85 fun inst_thm thy tvars' thm =
    86   let
    87     val tvars = (Term.add_tvars o Thm.prop_of) thm [];
    88     val inter_sort = Sorts.inter_sort (Sign.classes_of thy);
    89     fun mk_inst (tvar as (v, sort)) = case Vartab.lookup tvars' v
    90      of SOME sort' => SOME (pairself (Thm.ctyp_of thy o TVar)
    91           (tvar, (v, inter_sort (sort, sort'))))
    92       | NONE => NONE;
    93     val insts = map_filter mk_inst tvars;
    94   in Thm.instantiate (insts, []) thm end;
    95 
    96 fun constrain_thm thy sort thm =
    97   let
    98     val constrain = curry (Sorts.inter_sort (Sign.classes_of thy)) sort
    99     val tvars = (Term.add_tvars o Thm.prop_of) thm [];
   100     fun mk_inst (tvar as (v, sort)) = pairself (Thm.ctyp_of thy o TVar o pair v)
   101       (sort, constrain sort)
   102     val insts = map mk_inst tvars;
   103   in Thm.instantiate (insts, []) thm end;
   104 
   105 fun expand_eta thy k thm =
   106   let
   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 eqn_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_eqn = Conv.fconv_rule o eqn_conv o Simplifier.rewrite;
   152 val rewrite_head = Conv.fconv_rule o head_conv o MetaSimplifier.rewrite false;
   153 
   154 fun norm_args thy 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.prop_of) thms 0;
   158   in
   159     thms
   160     |> map (expand_eta thy k)
   161     |> map (Conv.fconv_rule Drule.beta_eta_conversion)
   162   end;
   163 
   164 fun canonical_tvars thy purify_tvar thm =
   165   let
   166     val ctyp = Thm.ctyp_of thy;
   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 thy purify_var thm =
   184   let
   185     val cterm = Thm.cterm_of thy;
   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 thy 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 thy purify_tvar)
   219     |> map (canonical_vars thy purify_var)
   220     |> map (canonical_absvars purify_var)
   221     |> map Drule.zero_var_indexes
   222   end;
   223 
   224 
   225 (* const aliasses *)
   226 
   227 structure ConstAlias = TheoryDataFun
   228 (
   229   type T = ((string * string) * thm) list * class list;
   230   val empty = ([], []);
   231   val copy = I;
   232   val extend = I;
   233   fun merge _ ((alias1, classes1), (alias2, classes2)) : T =
   234     (Library.merge (eq_snd Thm.eq_thm_prop) (alias1, alias2),
   235       Library.merge (op =) (classes1, classes2));
   236 );
   237 
   238 fun add_const_alias thm thy =
   239   let
   240     val lhs_rhs = case try Logic.dest_equals (Thm.prop_of thm)
   241      of SOME lhs_rhs => lhs_rhs
   242       | _ => error ("Not an equation: " ^ Display.string_of_thm thm);
   243     val c_c' = case try (pairself (AxClass.unoverload_const thy o dest_Const)) lhs_rhs
   244      of SOME c_c' => c_c'
   245       | _ => error ("Not an equation with two constants: " ^ Display.string_of_thm thm);
   246     val some_class = the_list (AxClass.class_of_param thy (snd c_c'));
   247   in thy |>
   248     ConstAlias.map (fn (alias, classes) =>
   249       ((c_c', thm) :: alias, fold (insert (op =)) some_class classes))
   250   end;
   251 
   252 fun resubst_alias thy =
   253   let
   254     val alias = fst (ConstAlias.get thy);
   255     val subst_inst_param = Option.map fst o AxClass.inst_of_param thy;
   256     fun subst_alias c =
   257       get_first (fn ((c', c''), _) => if c = c'' then SOME c' else NONE) alias;
   258   in
   259     perhaps subst_inst_param
   260     #> perhaps subst_alias
   261   end;
   262 
   263 val triv_classes = snd o ConstAlias.get;
   264 
   265 
   266 (* reading constants as terms *)
   267 
   268 fun check_bare_const thy t = case try dest_Const t
   269  of SOME c_ty => c_ty
   270   | NONE => error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   271 
   272 fun check_const thy = AxClass.unoverload_const thy o check_bare_const thy;
   273 
   274 fun read_bare_const thy = check_bare_const thy o Syntax.read_term_global thy;
   275 
   276 fun read_const thy = AxClass.unoverload_const thy o read_bare_const thy;
   277 
   278 
   279 (* constructor sets *)
   280 
   281 fun constrset_of_consts thy cs =
   282   let
   283     val _ = map (fn (c, _) => if (is_some o AxClass.class_of_param thy) c
   284       then error ("Is a class parameter: " ^ string_of_const thy c) else ()) cs;
   285     fun no_constr (c, ty) = error ("Not a datatype constructor: " ^ string_of_const thy c
   286       ^ " :: " ^ string_of_typ thy ty);
   287     fun last_typ c_ty ty =
   288       let
   289         val frees = OldTerm.typ_tfrees ty;
   290         val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) ty
   291           handle TYPE _ => no_constr c_ty
   292         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr c_ty else ();
   293         val _ = if length frees <> length vs then no_constr c_ty else ();
   294       in (tyco, vs) end;
   295     fun ty_sorts (c, ty) =
   296       let
   297         val ty_decl = (Logic.unvarifyT o Sign.the_const_type thy) c;
   298         val (tyco, _) = last_typ (c, ty) ty_decl;
   299         val (_, vs) = last_typ (c, ty) ty;
   300       in ((tyco, map snd vs), (c, (map fst vs, ty))) end;
   301     fun add ((tyco', sorts'), c) ((tyco, sorts), cs) =
   302       let
   303         val _ = if tyco' <> tyco
   304           then error "Different type constructors in constructor set"
   305           else ();
   306         val sorts'' = map2 (curry (Sorts.inter_sort (Sign.classes_of thy))) sorts' sorts
   307       in ((tyco, sorts), c :: cs) end;
   308     fun inst vs' (c, (vs, ty)) =
   309       let
   310         val the_v = the o AList.lookup (op =) (vs ~~ vs');
   311         val ty' = map_atyps (fn TFree (v, _) => TFree (the_v v)) ty;
   312       in (c, (fst o strip_type) ty') end;
   313     val c' :: cs' = map ty_sorts cs;
   314     val ((tyco, sorts), cs'') = fold add cs' (apsnd single c');
   315     val vs = Name.names Name.context Name.aT sorts;
   316     val cs''' = map (inst vs) cs'';
   317   in (tyco, (vs, rev cs''')) end;
   318 
   319 
   320 (* code equations *)
   321 
   322 fun assert_eqn thy thm =
   323   let
   324     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm
   325       handle TERM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm)
   326           | THM _ => bad_thm ("Not an equation: " ^ Display.string_of_thm thm);
   327     fun vars_of t = fold_aterms
   328      (fn Var (v, _) => insert (op =) v
   329        | Free _ => bad_thm ("Illegal free variable in rewrite theorem\n"
   330            ^ Display.string_of_thm thm)
   331        | _ => I) t [];
   332     fun tvars_of t = fold_term_types
   333      (fn _ => fold_atyps (fn TVar (v, _) => insert (op =) v
   334                           | TFree _ => bad_thm 
   335       ("Illegal free type variable in rewrite theorem\n" ^ Display.string_of_thm thm))) t [];
   336     val lhs_vs = vars_of lhs;
   337     val rhs_vs = vars_of rhs;
   338     val lhs_tvs = tvars_of lhs;
   339     val rhs_tvs = tvars_of lhs;
   340     val _ = if null (subtract (op =) lhs_vs rhs_vs)
   341       then ()
   342       else bad_thm ("Free variables on right hand side of rewrite theorem\n"
   343         ^ Display.string_of_thm thm);
   344     val _ = if null (subtract (op =) lhs_tvs rhs_tvs)
   345       then ()
   346       else bad_thm ("Free type variables on right hand side of rewrite theorem\n"
   347         ^ Display.string_of_thm thm)    val (head, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
   348     val (c, ty) = case head of Const c_ty => c_ty | _ =>
   349       bad_thm ("Equation not headed by constant\n" ^ Display.string_of_thm thm);
   350     fun check _ (Abs _) = bad_thm
   351           ("Abstraction on left hand side of equation\n"
   352             ^ Display.string_of_thm thm)
   353       | check 0 (Var _) = ()
   354       | check _ (Var _) = bad_thm
   355           ("Variable with application on left hand side of code equation\n"
   356             ^ Display.string_of_thm thm)
   357       | check n (t1 $ t2) = (check (n+1) t1; check 0 t2)
   358       | check n (Const (_, ty)) = if n <> (length o fst o strip_type) ty
   359           then bad_thm
   360             ("Partially applied constant on left hand side of equation\n"
   361                ^ Display.string_of_thm thm)
   362           else ();
   363     val _ = map (check 0) args;
   364     val ty_decl = Sign.the_const_type thy c;
   365     val _ = if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
   366       then () else bad_thm ("Type\n" ^ string_of_typ thy ty
   367            ^ "\nof code equation\n"
   368            ^ Display.string_of_thm thm
   369            ^ "\nis incompatible with declared function type\n"
   370            ^ string_of_typ thy ty_decl)
   371   in thm end;
   372 
   373 fun add_linear thm =
   374   let
   375     val (_, args) = (strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
   376     val linear = not (has_duplicates (op =)
   377       ((fold o fold_aterms) (fn Var (v, _) => cons v | _ => I) args []))
   378   in (thm, linear) end;
   379 
   380 fun assert_pat is_cons thm =
   381   let
   382     val args = (snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of) thm;
   383     val _ = (map o map_aterms) (fn t as Const (c, _) => if is_cons c then t
   384           else bad_thm ("Not a constructor on left hand side of equation: "
   385             ^ quote c ^ ",\n in equation\n" ^ Display.string_of_thm thm)
   386       | t => t) args;
   387   in thm end;
   388 
   389 fun assert_linear is_cons (thm, false) = (thm, false)
   390   | assert_linear is_cons (thm, true) = if snd (add_linear (assert_pat is_cons thm)) then (thm, true)
   391       else bad_thm
   392         ("Duplicate variables on left hand side of code equation:\n"
   393           ^ Display.string_of_thm thm);
   394 
   395 
   396 fun mk_eqn thy = add_linear o assert_eqn thy o AxClass.unoverload thy
   397   o LocalDefs.meta_rewrite_rule (ProofContext.init thy);
   398 
   399 val const_typ_eqn = dest_Const o fst o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   400 val const_eqn = fst o const_typ_eqn;
   401 fun head_eqn thy thm = let val (c, ty) = const_typ_eqn thm in (c, typscheme thy (c, ty)) end;
   402 
   403 
   404 (* case cerificates *)
   405 
   406 fun case_certificate thm =
   407   let
   408     val ((head, raw_case_expr), cases) = (apfst Logic.dest_equals
   409       o apsnd Logic.dest_conjunctions o Logic.dest_implies o Thm.prop_of) thm;
   410     val _ = case head of Free _ => true
   411       | Var _ => true
   412       | _ => raise TERM ("case_cert", []);
   413     val ([(case_var, _)], case_expr) = Term.strip_abs_eta 1 raw_case_expr;
   414     val (Const (case_const, _), raw_params) = strip_comb case_expr;
   415     val n = find_index (fn Free (v, _) => v = case_var | _ => false) raw_params;
   416     val _ = if n = ~1 then raise TERM ("case_cert", []) else ();
   417     val params = map (fst o dest_Var) (nth_drop n raw_params);
   418     fun dest_case t =
   419       let
   420         val (head' $ t_co, rhs) = Logic.dest_equals t;
   421         val _ = if head' = head then () else raise TERM ("case_cert", []);
   422         val (Const (co, _), args) = strip_comb t_co;
   423         val (Var (param, _), args') = strip_comb rhs;
   424         val _ = if args' = args then () else raise TERM ("case_cert", []);
   425       in (param, co) end;
   426     fun analyze_cases cases =
   427       let
   428         val co_list = fold (AList.update (op =) o dest_case) cases [];
   429       in map (the o AList.lookup (op =) co_list) params end;
   430     fun analyze_let t =
   431       let
   432         val (head' $ arg, Var (param', _) $ arg') = Logic.dest_equals t;
   433         val _ = if head' = head then () else raise TERM ("case_cert", []);
   434         val _ = if arg' = arg then () else raise TERM ("case_cert", []);
   435         val _ = if [param'] = params then () else raise TERM ("case_cert", []);
   436       in [] end;
   437     fun analyze (cases as [let_case]) =
   438           (analyze_cases cases handle Bind => analyze_let let_case)
   439       | analyze cases = analyze_cases cases;
   440   in (case_const, (n, analyze cases)) end;
   441 
   442 fun case_cert thm = case_certificate thm
   443   handle Bind => error "bad case certificate"
   444        | TERM _ => error "bad case certificate";
   445 
   446 end;