src/Tools/Code/code_thingol.ML
author haftmann
Thu, 08 Oct 2009 15:59:17 +0200
changeset 32895 6f3cdb4a9e11
parent 32873 333945c9ac6a
child 32909 bd72e72c3ee3
permissions -rw-r--r--
added group_stmts
     1 (*  Title:      Tools/code/code_thingol.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Intermediate language ("Thin-gol") representing executable code.
     5 Representation and translation.
     6 *)
     7 
     8 infix 8 `%%;
     9 infix 4 `$;
    10 infix 4 `$$;
    11 infixr 3 `|=>;
    12 infixr 3 `|==>;
    13 
    14 signature BASIC_CODE_THINGOL =
    15 sig
    16   type vname = string;
    17   datatype dict =
    18       DictConst of string * dict list list
    19     | DictVar of string list * (vname * (int * int));
    20   datatype itype =
    21       `%% of string * itype list
    22     | ITyVar of vname;
    23   type const = string * ((itype list * dict list list) * itype list (*types of arguments*))
    24   datatype iterm =
    25       IConst of const
    26     | IVar of vname option
    27     | `$ of iterm * iterm
    28     | `|=> of (vname option * itype) * iterm
    29     | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
    30         (*((term, type), [(selector pattern, body term )]), primitive term)*)
    31   val `$$ : iterm * iterm list -> iterm;
    32   val `|==> : (vname option * itype) list * iterm -> iterm;
    33   type typscheme = (vname * sort) list * itype;
    34 end;
    35 
    36 signature CODE_THINGOL =
    37 sig
    38   include BASIC_CODE_THINGOL
    39   val unfoldl: ('a -> ('a * 'b) option) -> 'a -> 'a * 'b list
    40   val unfoldr: ('a -> ('b * 'a) option) -> 'a -> 'b list * 'a
    41   val unfold_fun: itype -> itype list * itype
    42   val unfold_app: iterm -> iterm * iterm list
    43   val unfold_abs: iterm -> (vname option * itype) list * iterm
    44   val split_let: iterm -> (((iterm * itype) * iterm) * iterm) option
    45   val unfold_let: iterm -> ((iterm * itype) * iterm) list * iterm
    46   val split_pat_abs: iterm -> ((iterm * itype) * iterm) option
    47   val unfold_pat_abs: iterm -> (iterm * itype) list * iterm
    48   val unfold_const_app: iterm -> (const * iterm list) option
    49   val eta_expand: int -> const * iterm list -> iterm
    50   val contains_dictvar: iterm -> bool
    51   val locally_monomorphic: iterm -> bool
    52   val add_constnames: iterm -> string list -> string list
    53   val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
    54 
    55   type naming
    56   val empty_naming: naming
    57   val lookup_class: naming -> class -> string option
    58   val lookup_classrel: naming -> class * class -> string option
    59   val lookup_tyco: naming -> string -> string option
    60   val lookup_instance: naming -> class * string -> string option
    61   val lookup_const: naming -> string -> string option
    62   val ensure_declared_const: theory -> string -> naming -> string * naming
    63 
    64   datatype stmt =
    65       NoStmt
    66     | Fun of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
    67     | Datatype of string * ((vname * sort) list * (string * itype list) list)
    68     | Datatypecons of string * string
    69     | Class of class * (vname * ((class * string) list * (string * itype) list))
    70     | Classrel of class * class
    71     | Classparam of string * class
    72     | Classinst of (class * (string * (vname * sort) list))
    73           * ((class * (string * (string * dict list list))) list
    74         * ((string * const) * (thm * bool)) list)
    75   type program = stmt Graph.T
    76   val empty_funs: program -> string list
    77   val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
    78   val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
    79   val is_cons: program -> string -> bool
    80   val contr_classparam_typs: program -> string -> itype option list
    81   val labelled_name: theory -> program -> string -> string
    82   val group_stmts: theory -> program
    83     -> ((string * stmt) list * (string * stmt) list
    84       * ((string * stmt) list * (string * stmt) list)) list
    85 
    86   val expand_eta: theory -> int -> thm -> thm
    87   val clean_thms: theory -> thm list -> thm list
    88   val read_const_exprs: theory -> string list -> string list * string list
    89   val consts_program: theory -> string list -> string list * (naming * program)
    90   val cached_program: theory -> naming * program
    91   val eval_conv: theory
    92     -> (naming -> program -> ((string * sort) list * typscheme) * iterm -> string list -> cterm -> thm)
    93     -> cterm -> thm
    94   val eval: theory -> ((term -> term) -> 'a -> 'a)
    95     -> (naming -> program -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
    96     -> term -> 'a
    97 end;
    98 
    99 structure Code_Thingol: CODE_THINGOL =
   100 struct
   101 
   102 (** auxiliary **)
   103 
   104 fun unfoldl dest x =
   105   case dest x
   106    of NONE => (x, [])
   107     | SOME (x1, x2) =>
   108         let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
   109 
   110 fun unfoldr dest x =
   111   case dest x
   112    of NONE => ([], x)
   113     | SOME (x1, x2) =>
   114         let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
   115 
   116 
   117 (** language core - types, terms **)
   118 
   119 type vname = string;
   120 
   121 datatype dict =
   122     DictConst of string * dict list list
   123   | DictVar of string list * (vname * (int * int));
   124 
   125 datatype itype =
   126     `%% of string * itype list
   127   | ITyVar of vname;
   128 
   129 type const = string * ((itype list * dict list list) * itype list (*types of arguments*))
   130 
   131 datatype iterm =
   132     IConst of const
   133   | IVar of vname option
   134   | `$ of iterm * iterm
   135   | `|=> of (vname option * itype) * iterm
   136   | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
   137     (*see also signature*)
   138 
   139 val op `$$ = Library.foldl (op `$);
   140 val op `|==> = Library.foldr (op `|=>);
   141 
   142 val unfold_app = unfoldl
   143   (fn op `$ t => SOME t
   144     | _ => NONE);
   145 
   146 val unfold_abs = unfoldr
   147   (fn op `|=> t => SOME t
   148     | _ => NONE);
   149 
   150 val split_let = 
   151   (fn ICase (((td, ty), [(p, t)]), _) => SOME (((p, ty), td), t)
   152     | _ => NONE);
   153 
   154 val unfold_let = unfoldr split_let;
   155 
   156 fun unfold_const_app t =
   157  case unfold_app t
   158   of (IConst c, ts) => SOME (c, ts)
   159    | _ => NONE;
   160 
   161 fun add_constnames (IConst (c, _)) = insert (op =) c
   162   | add_constnames (IVar _) = I
   163   | add_constnames (t1 `$ t2) = add_constnames t1 #> add_constnames t2
   164   | add_constnames (_ `|=> t) = add_constnames t
   165   | add_constnames (ICase (((t, _), ds), _)) = add_constnames t
   166       #> fold (fn (pat, body) => add_constnames pat #> add_constnames body) ds;
   167 
   168 fun fold_varnames f =
   169   let
   170     fun fold_aux add f =
   171       let
   172         fun fold_term _ (IConst _) = I
   173           | fold_term vs (IVar (SOME v)) = if member (op =) vs v then I else f v
   174           | fold_term _ (IVar NONE) = I
   175           | fold_term vs (t1 `$ t2) = fold_term vs t1 #> fold_term vs t2
   176           | fold_term vs ((SOME v, _) `|=> t) = fold_term (insert (op =) v vs) t
   177           | fold_term vs ((NONE, _) `|=> t) = fold_term vs t
   178           | fold_term vs (ICase (((t, _), ds), _)) = fold_term vs t #> fold (fold_case vs) ds
   179         and fold_case vs (p, t) = fold_term (add p vs) t;
   180       in fold_term [] end;
   181     fun add t = fold_aux add (insert (op =)) t;
   182   in fold_aux add f end;
   183 
   184 fun exists_var t v = fold_varnames (fn w => fn b => v = w orelse b) t false;
   185 
   186 fun split_pat_abs ((NONE, ty) `|=> t) = SOME ((IVar NONE, ty), t)
   187   | split_pat_abs ((SOME v, ty) `|=> t) = SOME (case t
   188      of ICase (((IVar (SOME w), _), [(p, t')]), _) =>
   189           if v = w andalso (exists_var p v orelse not (exists_var t' v))
   190           then ((p, ty), t')
   191           else ((IVar (SOME v), ty), t)
   192       | _ => ((IVar (SOME v), ty), t))
   193   | split_pat_abs _ = NONE;
   194 
   195 val unfold_pat_abs = unfoldr split_pat_abs;
   196 
   197 fun unfold_abs_eta [] t = ([], t)
   198   | unfold_abs_eta (_ :: tys) (v_ty `|=> t) =
   199       let
   200         val (vs_tys, t') = unfold_abs_eta tys t;
   201       in (v_ty :: vs_tys, t') end
   202   | unfold_abs_eta tys t =
   203       let
   204         val ctxt = fold_varnames Name.declare t Name.context;
   205         val vs_tys = (map o apfst) SOME (Name.names ctxt "a" tys);
   206       in (vs_tys, t `$$ map (IVar o fst) vs_tys) end;
   207 
   208 fun eta_expand k (c as (_, (_, tys)), ts) =
   209   let
   210     val j = length ts;
   211     val l = k - j;
   212     val ctxt = (fold o fold_varnames) Name.declare ts Name.context;
   213     val vs_tys = (map o apfst) SOME
   214       (Name.names ctxt "a" ((curry Library.take l o curry Library.drop j) tys));
   215   in vs_tys `|==> IConst c `$$ ts @ map (IVar o fst) vs_tys end;
   216 
   217 fun contains_dictvar t =
   218   let
   219     fun cont_dict (DictConst (_, dss)) = (exists o exists) cont_dict dss
   220       | cont_dict (DictVar _) = true;
   221     fun cont_term (IConst (_, ((_, dss), _))) = (exists o exists) cont_dict dss
   222       | cont_term (IVar _) = false
   223       | cont_term (t1 `$ t2) = cont_term t1 orelse cont_term t2
   224       | cont_term (_ `|=> t) = cont_term t
   225       | cont_term (ICase (_, t)) = cont_term t;
   226   in cont_term t end;
   227   
   228 fun locally_monomorphic (IConst _) = false
   229   | locally_monomorphic (IVar _) = true
   230   | locally_monomorphic (t `$ _) = locally_monomorphic t
   231   | locally_monomorphic (_ `|=> t) = locally_monomorphic t
   232   | locally_monomorphic (ICase ((_, ds), _)) = exists (locally_monomorphic o snd) ds;
   233 
   234 
   235 (** namings **)
   236 
   237 (* policies *)
   238 
   239 local
   240   fun thyname_of thy f x = the (AList.lookup (op =) (f x) Markup.theory_nameN);
   241   fun thyname_of_class thy =
   242     thyname_of thy (ProofContext.query_class (ProofContext.init thy));
   243   fun thyname_of_tyco thy =
   244     thyname_of thy (Type.the_tags (Sign.tsig_of thy));
   245   fun thyname_of_instance thy inst = case AxClass.arity_property thy inst Markup.theory_nameN
   246    of [] => error ("no such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
   247     | thyname :: _ => thyname;
   248   fun thyname_of_const thy c = case AxClass.class_of_param thy c
   249    of SOME class => thyname_of_class thy class
   250     | NONE => (case Code.get_datatype_of_constr thy c
   251        of SOME dtco => thyname_of_tyco thy dtco
   252         | NONE => thyname_of thy (Consts.the_tags (Sign.consts_of thy)) c);
   253   fun purify_base "op &" = "and"
   254     | purify_base "op |" = "or"
   255     | purify_base "op -->" = "implies"
   256     | purify_base "op :" = "member"
   257     | purify_base "op =" = "eq"
   258     | purify_base "*" = "product"
   259     | purify_base "+" = "sum"
   260     | purify_base s = Name.desymbolize false s;
   261   fun namify thy get_basename get_thyname name =
   262     let
   263       val prefix = get_thyname thy name;
   264       val base = (purify_base o get_basename) name;
   265     in Long_Name.append prefix base end;
   266 in
   267 
   268 fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
   269 fun namify_classrel thy = namify thy (fn (class1, class2) => 
   270   Long_Name.base_name class2 ^ "_" ^ Long_Name.base_name class1) (fn thy => thyname_of_class thy o fst);
   271   (*order fits nicely with composed projections*)
   272 fun namify_tyco thy "fun" = "Pure.fun"
   273   | namify_tyco thy tyco = namify thy Long_Name.base_name thyname_of_tyco tyco;
   274 fun namify_instance thy = namify thy (fn (class, tyco) => 
   275   Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
   276 fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
   277 
   278 end; (* local *)
   279 
   280 
   281 (* data *)
   282 
   283 datatype naming = Naming of {
   284   class: class Symtab.table * Name.context,
   285   classrel: string Symreltab.table * Name.context,
   286   tyco: string Symtab.table * Name.context,
   287   instance: string Symreltab.table * Name.context,
   288   const: string Symtab.table * Name.context
   289 }
   290 
   291 fun dest_Naming (Naming naming) = naming;
   292 
   293 val empty_naming = Naming {
   294   class = (Symtab.empty, Name.context),
   295   classrel = (Symreltab.empty, Name.context),
   296   tyco = (Symtab.empty, Name.context),
   297   instance = (Symreltab.empty, Name.context),
   298   const = (Symtab.empty, Name.context)
   299 };
   300 
   301 local
   302   fun mk_naming (class, classrel, tyco, instance, const) =
   303     Naming { class = class, classrel = classrel,
   304       tyco = tyco, instance = instance, const = const };
   305   fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
   306     mk_naming (f (class, classrel, tyco, instance, const));
   307 in
   308   fun map_class f = map_naming
   309     (fn (class, classrel, tyco, inst, const) =>
   310       (f class, classrel, tyco, inst, const));
   311   fun map_classrel f = map_naming
   312     (fn (class, classrel, tyco, inst, const) =>
   313       (class, f classrel, tyco, inst, const));
   314   fun map_tyco f = map_naming
   315     (fn (class, classrel, tyco, inst, const) =>
   316       (class, classrel, f tyco, inst, const));
   317   fun map_instance f = map_naming
   318     (fn (class, classrel, tyco, inst, const) =>
   319       (class, classrel, tyco, f inst, const));
   320   fun map_const f = map_naming
   321     (fn (class, classrel, tyco, inst, const) =>
   322       (class, classrel, tyco, inst, f const));
   323 end; (*local*)
   324 
   325 fun add_variant update (thing, name) (tab, used) =
   326   let
   327     val (name', used') = yield_singleton Name.variants name used;
   328     val tab' = update (thing, name') tab;
   329   in (tab', used') end;
   330 
   331 fun declare thy mapp lookup update namify thing =
   332   mapp (add_variant update (thing, namify thy thing))
   333   #> `(fn naming => the (lookup naming thing));
   334 
   335 
   336 (* lookup and declare *)
   337 
   338 local
   339 
   340 val suffix_class = "class";
   341 val suffix_classrel = "classrel"
   342 val suffix_tyco = "tyco";
   343 val suffix_instance = "inst";
   344 val suffix_const = "const";
   345 
   346 fun add_suffix nsp NONE = NONE
   347   | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
   348 
   349 in
   350 
   351 val lookup_class = add_suffix suffix_class
   352   oo Symtab.lookup o fst o #class o dest_Naming;
   353 val lookup_classrel = add_suffix suffix_classrel
   354   oo Symreltab.lookup o fst o #classrel o dest_Naming;
   355 val lookup_tyco = add_suffix suffix_tyco
   356   oo Symtab.lookup o fst o #tyco o dest_Naming;
   357 val lookup_instance = add_suffix suffix_instance
   358   oo Symreltab.lookup o fst o #instance o dest_Naming;
   359 val lookup_const = add_suffix suffix_const
   360   oo Symtab.lookup o fst o #const o dest_Naming;
   361 
   362 fun declare_class thy = declare thy map_class
   363   lookup_class Symtab.update_new namify_class;
   364 fun declare_classrel thy = declare thy map_classrel
   365   lookup_classrel Symreltab.update_new namify_classrel;
   366 fun declare_tyco thy = declare thy map_tyco
   367   lookup_tyco Symtab.update_new namify_tyco;
   368 fun declare_instance thy = declare thy map_instance
   369   lookup_instance Symreltab.update_new namify_instance;
   370 fun declare_const thy = declare thy map_const
   371   lookup_const Symtab.update_new namify_const;
   372 
   373 fun ensure_declared_const thy const naming =
   374   case lookup_const naming const
   375    of SOME const' => (const', naming)
   376     | NONE => declare_const thy const naming;
   377 
   378 val unfold_fun = unfoldr
   379   (fn "Pure.fun.tyco" `%% [ty1, ty2] => SOME (ty1, ty2)
   380     | _ => NONE); (*depends on suffix_tyco and namify_tyco!*)
   381 
   382 end; (* local *)
   383 
   384 
   385 (** technical transformations of code equations **)
   386 
   387 fun expand_eta thy k thm =
   388   let
   389     val (lhs, rhs) = (Logic.dest_equals o Thm.plain_prop_of) thm;
   390     val (head, args) = strip_comb lhs;
   391     val l = if k = ~1
   392       then (length o fst o strip_abs) rhs
   393       else Int.max (0, k - length args);
   394     val (raw_vars, _) = Term.strip_abs_eta l rhs;
   395     val vars = burrow_fst (Name.variant_list (map (fst o fst) (Term.add_vars lhs [])))
   396       raw_vars;
   397     fun expand (v, ty) thm = Drule.fun_cong_rule thm
   398       (Thm.cterm_of thy (Var ((v, 0), ty)));
   399   in
   400     thm
   401     |> fold expand vars
   402     |> Conv.fconv_rule Drule.beta_eta_conversion
   403   end;
   404 
   405 fun same_arity thy thms =
   406   let
   407     val num_args_of = length o snd o strip_comb o fst o Logic.dest_equals;
   408     val k = fold (curry Int.max o num_args_of o Thm.prop_of) thms 0;
   409   in map (expand_eta thy k) thms end;
   410 
   411 fun mk_desymbolization pre post mk vs =
   412   let
   413     val names = map (pre o fst o fst) vs
   414       |> map (Name.desymbolize false)
   415       |> Name.variant_list []
   416       |> map post;
   417   in map_filter (fn (((v, i), x), v') =>
   418     if v = v' andalso i = 0 then NONE
   419     else SOME (((v, i), x), mk ((v', 0), x))) (vs ~~ names)
   420   end;
   421 
   422 fun desymbolize_tvars thy thms =
   423   let
   424     val tvs = fold (Term.add_tvars o Thm.prop_of) thms [];
   425     val tvar_subst = mk_desymbolization (unprefix "'") (prefix "'") TVar tvs;
   426   in map (Thm.certify_instantiate (tvar_subst, [])) thms end;
   427 
   428 fun desymbolize_vars thy thm =
   429   let
   430     val vs = Term.add_vars (Thm.prop_of thm) [];
   431     val var_subst = mk_desymbolization I I Var vs;
   432   in Thm.certify_instantiate ([], var_subst) thm end;
   433 
   434 fun desymbolize_all_vars thy = desymbolize_tvars thy #> map (desymbolize_vars thy);
   435 
   436 fun clean_thms thy = map (Thm.transfer thy) #> same_arity thy #> desymbolize_all_vars thy;
   437 
   438 
   439 (** statements, abstract programs **)
   440 
   441 type typscheme = (vname * sort) list * itype;
   442 datatype stmt =
   443     NoStmt
   444   | Fun of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
   445   | Datatype of string * ((vname * sort) list * (string * itype list) list)
   446   | Datatypecons of string * string
   447   | Class of class * (vname * ((class * string) list * (string * itype) list))
   448   | Classrel of class * class
   449   | Classparam of string * class
   450   | Classinst of (class * (string * (vname * sort) list))
   451         * ((class * (string * (string * dict list list))) list
   452       * ((string * const) * (thm * bool)) list);
   453 
   454 type program = stmt Graph.T;
   455 
   456 fun empty_funs program =
   457   Graph.fold (fn (name, (Fun (c, (_, [])), _)) => cons c
   458                | _ => I) program [];
   459 
   460 fun map_terms_bottom_up f (t as IConst _) = f t
   461   | map_terms_bottom_up f (t as IVar _) = f t
   462   | map_terms_bottom_up f (t1 `$ t2) = f
   463       (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
   464   | map_terms_bottom_up f ((v, ty) `|=> t) = f
   465       ((v, ty) `|=> map_terms_bottom_up f t)
   466   | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
   467       (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
   468         (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
   469 
   470 fun map_terms_stmt f NoStmt = NoStmt
   471   | map_terms_stmt f (Fun (c, (tysm, eqs))) = Fun (c, (tysm, (map o apfst)
   472       (fn (ts, t) => (map f ts, f t)) eqs))
   473   | map_terms_stmt f (stmt as Datatype _) = stmt
   474   | map_terms_stmt f (stmt as Datatypecons _) = stmt
   475   | map_terms_stmt f (stmt as Class _) = stmt
   476   | map_terms_stmt f (stmt as Classrel _) = stmt
   477   | map_terms_stmt f (stmt as Classparam _) = stmt
   478   | map_terms_stmt f (Classinst (arity, (superarities, classparms))) =
   479       Classinst (arity, (superarities, (map o apfst o apsnd) (fn const =>
   480         case f (IConst const) of IConst const' => const') classparms));
   481 
   482 fun is_cons program name = case Graph.get_node program name
   483  of Datatypecons _ => true
   484   | _ => false;
   485 
   486 fun contr_classparam_typs program name = case Graph.get_node program name
   487  of Classparam (_, class) => let
   488         val Class (_, (_, (_, params))) = Graph.get_node program class;
   489         val SOME ty = AList.lookup (op =) params name;
   490         val (tys, res_ty) = unfold_fun ty;
   491         fun no_tyvar (_ `%% tys) = forall no_tyvar tys
   492           | no_tyvar (ITyVar _) = false;
   493       in if no_tyvar res_ty
   494         then map (fn ty => if no_tyvar ty then NONE else SOME ty) tys
   495         else []
   496       end
   497   | _ => [];
   498 
   499 fun labelled_name thy program name = case Graph.get_node program name
   500  of Fun (c, _) => quote (Code.string_of_const thy c)
   501   | Datatype (tyco, _) => "type " ^ quote (Sign.extern_type thy tyco)
   502   | Datatypecons (c, _) => quote (Code.string_of_const thy c)
   503   | Class (class, _) => "class " ^ quote (Sign.extern_class thy class)
   504   | Classrel (sub, super) => let
   505         val Class (sub, _) = Graph.get_node program sub
   506         val Class (super, _) = Graph.get_node program super
   507       in quote (Sign.extern_class thy sub ^ " < " ^ Sign.extern_class thy super) end
   508   | Classparam (c, _) => quote (Code.string_of_const thy c)
   509   | Classinst ((class, (tyco, _)), _) => let
   510         val Class (class, _) = Graph.get_node program class
   511         val Datatype (tyco, _) = Graph.get_node program tyco
   512       in quote (Sign.extern_type thy tyco ^ " :: " ^ Sign.extern_class thy class) end
   513 
   514 fun group_stmts thy program =
   515   let
   516     fun is_fun (_, Fun _) = true | is_fun _ = false;
   517     fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
   518     fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
   519     fun is_class (_, Class _) = true | is_class _ = false;
   520     fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
   521     fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
   522     fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
   523     fun group stmts =
   524       if forall (is_datatypecons orf is_datatype) stmts
   525       then (filter is_datatype stmts, [], ([], []))
   526       else if forall (is_class orf is_classrel orf is_classparam) stmts
   527       then ([], filter is_class stmts, ([], []))
   528       else if forall (is_fun orf is_classinst) stmts
   529       then ([], [], List.partition is_fun stmts)
   530       else error ("Illegal mutual dependencies: " ^
   531         (commas o map (labelled_name thy program o fst)) stmts)
   532   in
   533     rev (Graph.strong_conn program)
   534     |> map (AList.make (Graph.get_node program))
   535     |> map group
   536   end;
   537 
   538 
   539 (** translation kernel **)
   540 
   541 (* generic mechanisms *)
   542 
   543 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
   544   let
   545     fun add_dep name = case dep of NONE => I
   546       | SOME dep => Graph.add_edge (dep, name);
   547     val (name, naming') = case lookup naming thing
   548      of SOME name => (name, naming)
   549       | NONE => declare thing naming;
   550   in case try (Graph.get_node program) name
   551    of SOME stmt => program
   552         |> add_dep name
   553         |> pair naming'
   554         |> pair dep
   555         |> pair name
   556     | NONE => program
   557         |> Graph.default_node (name, NoStmt)
   558         |> add_dep name
   559         |> pair naming'
   560         |> curry generate (SOME name)
   561         ||> snd
   562         |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
   563         |> pair dep
   564         |> pair name
   565   end;
   566 
   567 fun not_wellsorted thy thm ty sort e =
   568   let
   569     val err_class = Sorts.class_error (Syntax.pp_global thy) e;
   570     val err_thm = case thm
   571      of SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")" | NONE => "";
   572     val err_typ = "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort "
   573       ^ Syntax.string_of_sort_global thy sort;
   574   in error ("Wellsortedness error" ^ err_thm ^ ":\n" ^ err_typ ^ "\n" ^ err_class) end;
   575 
   576 
   577 (* translation *)
   578 
   579 fun ensure_tyco thy algbr eqngr tyco =
   580   let
   581     val stmt_datatype =
   582       let
   583         val (vs, cos) = Code.get_datatype thy tyco;
   584       in
   585         fold_map (translate_tyvar_sort thy algbr eqngr) vs
   586         ##>> fold_map (fn (c, tys) =>
   587           ensure_const thy algbr eqngr c
   588           ##>> fold_map (translate_typ thy algbr eqngr) tys) cos
   589         #>> (fn info => Datatype (tyco, info))
   590       end;
   591   in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
   592 and ensure_const thy algbr eqngr c =
   593   let
   594     fun stmt_datatypecons tyco =
   595       ensure_tyco thy algbr eqngr tyco
   596       #>> (fn tyco => Datatypecons (c, tyco));
   597     fun stmt_classparam class =
   598       ensure_class thy algbr eqngr class
   599       #>> (fn class => Classparam (c, class));
   600     fun stmt_fun raw_eqns =
   601       let
   602         val eqns = burrow_fst (clean_thms thy) raw_eqns;
   603         val (vs, ty) = Code.typscheme_eqns thy c (map fst eqns);
   604       in
   605         fold_map (translate_tyvar_sort thy algbr eqngr) vs
   606         ##>> translate_typ thy algbr eqngr ty
   607         ##>> fold_map (translate_eqn thy algbr eqngr) eqns
   608         #>> (fn info => Fun (c, info))
   609       end;
   610     val stmt_const = case Code.get_datatype_of_constr thy c
   611      of SOME tyco => stmt_datatypecons tyco
   612       | NONE => (case AxClass.class_of_param thy c
   613          of SOME class => stmt_classparam class
   614           | NONE => stmt_fun (Code_Preproc.eqns eqngr c))
   615   in ensure_stmt lookup_const (declare_const thy) stmt_const c end
   616 and ensure_class thy (algbr as (_, algebra)) eqngr class =
   617   let
   618     val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
   619     val cs = #params (AxClass.get_info thy class);
   620     val stmt_class =
   621       fold_map (fn superclass => ensure_class thy algbr eqngr superclass
   622         ##>> ensure_classrel thy algbr eqngr (class, superclass)) superclasses
   623       ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr c
   624         ##>> translate_typ thy algbr eqngr ty) cs
   625       #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
   626   in ensure_stmt lookup_class (declare_class thy) stmt_class class end
   627 and ensure_classrel thy algbr eqngr (subclass, superclass) =
   628   let
   629     val stmt_classrel =
   630       ensure_class thy algbr eqngr subclass
   631       ##>> ensure_class thy algbr eqngr superclass
   632       #>> Classrel;
   633   in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (subclass, superclass) end
   634 and ensure_inst thy (algbr as (_, algebra)) eqngr (class, tyco) =
   635   let
   636     val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
   637     val classparams = these (try (#params o AxClass.get_info thy) class);
   638     val vs = Name.names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
   639     val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
   640     val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
   641       Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
   642     val arity_typ = Type (tyco, map TFree vs);
   643     val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
   644     fun translate_superarity superclass =
   645       ensure_class thy algbr eqngr superclass
   646       ##>> ensure_classrel thy algbr eqngr (class, superclass)
   647       ##>> translate_dicts thy algbr eqngr NONE (arity_typ, [superclass])
   648       #>> (fn ((superclass, classrel), [DictConst (inst, dss)]) =>
   649             (superclass, (classrel, (inst, dss))));
   650     fun translate_classparam_inst (c, ty) =
   651       let
   652         val c_inst = Const (c, map_type_tfree (K arity_typ') ty);
   653         val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy c_inst);
   654         val c_ty = (apsnd Logic.unvarifyT o dest_Const o snd
   655           o Logic.dest_equals o Thm.prop_of) thm;
   656       in
   657         ensure_const thy algbr eqngr c
   658         ##>> translate_const thy algbr eqngr (SOME thm) c_ty
   659         #>> (fn (c, IConst c_inst) => ((c, c_inst), (thm, true)))
   660       end;
   661     val stmt_inst =
   662       ensure_class thy algbr eqngr class
   663       ##>> ensure_tyco thy algbr eqngr tyco
   664       ##>> fold_map (translate_tyvar_sort thy algbr eqngr) vs
   665       ##>> fold_map translate_superarity superclasses
   666       ##>> fold_map translate_classparam_inst classparams
   667       #>> (fn ((((class, tyco), arity), superarities), classparams) =>
   668              Classinst ((class, (tyco, arity)), (superarities, classparams)));
   669   in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
   670 and translate_typ thy algbr eqngr (TFree (v, _)) =
   671       pair (ITyVar (unprefix "'" v))
   672   | translate_typ thy algbr eqngr (Type (tyco, tys)) =
   673       ensure_tyco thy algbr eqngr tyco
   674       ##>> fold_map (translate_typ thy algbr eqngr) tys
   675       #>> (fn (tyco, tys) => tyco `%% tys)
   676 and translate_term thy algbr eqngr thm (Const (c, ty)) =
   677       translate_app thy algbr eqngr thm ((c, ty), [])
   678   | translate_term thy algbr eqngr thm (Free (v, _)) =
   679       pair (IVar (SOME v))
   680   | translate_term thy algbr eqngr thm (Abs (v, ty, t)) =
   681       let
   682         val (v', t') = Syntax.variant_abs (Name.desymbolize false v, ty, t);
   683         val v'' = if member (op =) (Term.add_free_names t' []) v'
   684           then SOME v' else NONE
   685       in
   686         translate_typ thy algbr eqngr ty
   687         ##>> translate_term thy algbr eqngr thm t'
   688         #>> (fn (ty, t) => (v'', ty) `|=> t)
   689       end
   690   | translate_term thy algbr eqngr thm (t as _ $ _) =
   691       case strip_comb t
   692        of (Const (c, ty), ts) =>
   693             translate_app thy algbr eqngr thm ((c, ty), ts)
   694         | (t', ts) =>
   695             translate_term thy algbr eqngr thm t'
   696             ##>> fold_map (translate_term thy algbr eqngr thm) ts
   697             #>> (fn (t, ts) => t `$$ ts)
   698 and translate_eqn thy algbr eqngr (thm, proper) =
   699   let
   700     val (args, rhs) = (apfst (snd o strip_comb) o Logic.dest_equals
   701       o Logic.unvarify o prop_of) thm;
   702   in
   703     fold_map (translate_term thy algbr eqngr (SOME thm)) args
   704     ##>> translate_term thy algbr eqngr (SOME thm) rhs
   705     #>> rpair (thm, proper)
   706   end
   707 and translate_const thy algbr eqngr thm (c, ty) =
   708   let
   709     val tys = Sign.const_typargs thy (c, ty);
   710     val sorts = Code_Preproc.sortargs eqngr c;
   711     val tys_args = (fst o Term.strip_type) ty;
   712   in
   713     ensure_const thy algbr eqngr c
   714     ##>> fold_map (translate_typ thy algbr eqngr) tys
   715     ##>> fold_map (translate_dicts thy algbr eqngr thm) (tys ~~ sorts)
   716     ##>> fold_map (translate_typ thy algbr eqngr) tys_args
   717     #>> (fn (((c, tys), iss), tys_args) => IConst (c, ((tys, iss), tys_args)))
   718   end
   719 and translate_app_const thy algbr eqngr thm (c_ty, ts) =
   720   translate_const thy algbr eqngr thm c_ty
   721   ##>> fold_map (translate_term thy algbr eqngr thm) ts
   722   #>> (fn (t, ts) => t `$$ ts)
   723 and translate_case thy algbr eqngr thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
   724   let
   725     fun arg_types num_args ty = (fst o chop num_args o fst o strip_type) ty;
   726     val tys = arg_types num_args (snd c_ty);
   727     val ty = nth tys t_pos;
   728     fun mk_constr c t = let val n = Code.args_number thy c
   729       in ((c, arg_types n (fastype_of t) ---> ty), n) end;
   730     val constrs = if null case_pats then []
   731       else map2 mk_constr case_pats (nth_drop t_pos ts);
   732     fun casify naming constrs ty ts =
   733       let
   734         val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
   735         fun collapse_clause vs_map ts body =
   736           let
   737           in case body
   738            of IConst (c, _) => if member (op =) undefineds c
   739                 then []
   740                 else [(ts, body)]
   741             | ICase (((IVar (SOME v), _), subclauses), _) =>
   742                 if forall (fn (pat', body') => exists_var pat' v
   743                   orelse not (exists_var body' v)) subclauses
   744                 then case AList.lookup (op =) vs_map v
   745                  of SOME i => maps (fn (pat', body') =>
   746                       collapse_clause (AList.delete (op =) v vs_map)
   747                         (nth_map i (K pat') ts) body') subclauses
   748                   | NONE => [(ts, body)]
   749                 else [(ts, body)]
   750             | _ => [(ts, body)]
   751           end;
   752         fun mk_clause mk tys t =
   753           let
   754             val (vs, body) = unfold_abs_eta tys t;
   755             val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
   756             val ts = map (IVar o fst) vs;
   757           in map mk (collapse_clause vs_map ts body) end;
   758         val t = nth ts t_pos;
   759         val ts_clause = nth_drop t_pos ts;
   760         val clauses = if null case_pats
   761           then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
   762           else maps (fn ((constr as IConst (_, (_, tys)), n), t) =>
   763             mk_clause (fn (ts, body) => (constr `$$ ts, body)) (curry Library.take n tys) t)
   764               (constrs ~~ ts_clause);
   765       in ((t, ty), clauses) end;
   766   in
   767     translate_const thy algbr eqngr thm c_ty
   768     ##>> fold_map (fn (constr, n) => translate_const thy algbr eqngr thm constr #>> rpair n) constrs
   769     ##>> translate_typ thy algbr eqngr ty
   770     ##>> fold_map (translate_term thy algbr eqngr thm) ts
   771     #-> (fn (((t, constrs), ty), ts) =>
   772       `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
   773   end
   774 and translate_app_case thy algbr eqngr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
   775   if length ts < num_args then
   776     let
   777       val k = length ts;
   778       val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
   779       val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
   780       val vs = Name.names ctxt "a" tys;
   781     in
   782       fold_map (translate_typ thy algbr eqngr) tys
   783       ##>> translate_case thy algbr eqngr thm case_scheme ((c, ty), ts @ map Free vs)
   784       #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
   785     end
   786   else if length ts > num_args then
   787     translate_case thy algbr eqngr thm case_scheme ((c, ty), Library.take (num_args, ts))
   788     ##>> fold_map (translate_term thy algbr eqngr thm) (Library.drop (num_args, ts))
   789     #>> (fn (t, ts) => t `$$ ts)
   790   else
   791     translate_case thy algbr eqngr thm case_scheme ((c, ty), ts)
   792 and translate_app thy algbr eqngr thm (c_ty_ts as ((c, _), _)) =
   793   case Code.get_case_scheme thy c
   794    of SOME case_scheme => translate_app_case thy algbr eqngr thm case_scheme c_ty_ts
   795     | NONE => translate_app_const thy algbr eqngr thm c_ty_ts
   796 and translate_tyvar_sort thy (algbr as (proj_sort, _)) eqngr (v, sort) =
   797   fold_map (ensure_class thy algbr eqngr) (proj_sort sort)
   798   #>> (fn sort => (unprefix "'" v, sort))
   799 and translate_dicts thy (algbr as (proj_sort, algebra)) eqngr thm (ty, sort) =
   800   let
   801     datatype typarg =
   802         Global of (class * string) * typarg list list
   803       | Local of (class * class) list * (string * (int * sort));
   804     fun class_relation (Global ((_, tyco), yss), _) class =
   805           Global ((class, tyco), yss)
   806       | class_relation (Local (classrels, v), subclass) superclass =
   807           Local ((subclass, superclass) :: classrels, v);
   808     fun type_constructor tyco yss class =
   809       Global ((class, tyco), (map o map) fst yss);
   810     fun type_variable (TFree (v, sort)) =
   811       let
   812         val sort' = proj_sort sort;
   813       in map_index (fn (n, class) => (Local ([], (v, (n, sort'))), class)) sort' end;
   814     val typargs = Sorts.of_sort_derivation algebra
   815       {class_relation = class_relation, type_constructor = type_constructor,
   816        type_variable = type_variable} (ty, proj_sort sort)
   817       handle Sorts.CLASS_ERROR e => not_wellsorted thy thm ty sort e;
   818     fun mk_dict (Global (inst, yss)) =
   819           ensure_inst thy algbr eqngr inst
   820           ##>> (fold_map o fold_map) mk_dict yss
   821           #>> (fn (inst, dss) => DictConst (inst, dss))
   822       | mk_dict (Local (classrels, (v, (n, sort)))) =
   823           fold_map (ensure_classrel thy algbr eqngr) classrels
   824           #>> (fn classrels => DictVar (classrels, (unprefix "'" v, (n, length sort))))
   825   in fold_map mk_dict typargs end;
   826 
   827 
   828 (* store *)
   829 
   830 structure Program = Code_Data_Fun
   831 (
   832   type T = naming * program;
   833   val empty = (empty_naming, Graph.empty);
   834   fun purge thy cs (naming, program) =
   835     let
   836       val names_delete = cs
   837         |> map_filter (lookup_const naming)
   838         |> filter (can (Graph.get_node program))
   839         |> Graph.all_preds program;
   840       val program' = Graph.del_nodes names_delete program;
   841     in (naming, program') end;
   842 );
   843 
   844 val cached_program = Program.get;
   845 
   846 fun invoke_generation thy (algebra, eqngr) f name =
   847   Program.change_yield thy (fn naming_program => (NONE, naming_program)
   848     |> f thy algebra eqngr name
   849     |-> (fn name => fn (_, naming_program) => (name, naming_program)));
   850 
   851 
   852 (* program generation *)
   853 
   854 fun consts_program thy cs =
   855   let
   856     fun project_consts cs (naming, program) =
   857       let
   858         val cs_all = Graph.all_succs program cs;
   859       in (cs, (naming, Graph.subgraph (member (op =) cs_all) program)) end;
   860     fun generate_consts thy algebra eqngr =
   861       fold_map (ensure_const thy algebra eqngr);
   862   in
   863     invoke_generation thy (Code_Preproc.obtain thy cs []) generate_consts cs
   864     |-> project_consts
   865   end;
   866 
   867 
   868 (* value evaluation *)
   869 
   870 fun ensure_value thy algbr eqngr t =
   871   let
   872     val ty = fastype_of t;
   873     val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
   874       o dest_TFree))) t [];
   875     val stmt_value =
   876       fold_map (translate_tyvar_sort thy algbr eqngr) vs
   877       ##>> translate_typ thy algbr eqngr ty
   878       ##>> translate_term thy algbr eqngr NONE t
   879       #>> (fn ((vs, ty), t) => Fun
   880         (Term.dummy_patternN, ((vs, ty), [(([], t), (Drule.dummy_thm, true))])));
   881     fun term_value (dep, (naming, program1)) =
   882       let
   883         val Fun (_, (vs_ty, [(([], t), _)])) =
   884           Graph.get_node program1 Term.dummy_patternN;
   885         val deps = Graph.imm_succs program1 Term.dummy_patternN;
   886         val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
   887         val deps_all = Graph.all_succs program2 deps;
   888         val program3 = Graph.subgraph (member (op =) deps_all) program2;
   889       in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
   890   in
   891     ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
   892     #> snd
   893     #> term_value
   894   end;
   895 
   896 fun base_evaluator thy evaluator algebra eqngr vs t =
   897   let
   898     val (((naming, program), (((vs', ty'), t'), deps)), _) =
   899       invoke_generation thy (algebra, eqngr) ensure_value t;
   900     val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
   901   in evaluator naming program ((vs'', (vs', ty')), t') deps end;
   902 
   903 fun eval_conv thy = Code_Preproc.eval_conv thy o base_evaluator thy;
   904 fun eval thy postproc = Code_Preproc.eval thy postproc o base_evaluator thy;
   905 
   906 
   907 (** diagnostic commands **)
   908 
   909 fun read_const_exprs thy =
   910   let
   911     fun consts_of some_thyname =
   912       let
   913         val thy' = case some_thyname
   914          of SOME thyname => ThyInfo.the_theory thyname thy
   915           | NONE => thy;
   916         val cs = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
   917           ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
   918         fun belongs_here c =
   919           not (exists (fn thy'' => Sign.declared_const thy'' c) (Theory.parents_of thy'))
   920       in case some_thyname
   921        of NONE => cs
   922         | SOME thyname => filter belongs_here cs
   923       end;
   924     fun read_const_expr "*" = ([], consts_of NONE)
   925       | read_const_expr s = if String.isSuffix ".*" s
   926           then ([], consts_of (SOME (unsuffix ".*" s)))
   927           else ([Code.read_const thy s], []);
   928   in pairself flat o split_list o map read_const_expr end;
   929 
   930 fun code_depgr thy consts =
   931   let
   932     val (_, eqngr) = Code_Preproc.obtain thy consts [];
   933     val select = Graph.all_succs eqngr consts;
   934   in
   935     eqngr
   936     |> not (null consts) ? Graph.subgraph (member (op =) select) 
   937     |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
   938   end;
   939 
   940 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
   941 
   942 fun code_deps thy consts =
   943   let
   944     val eqngr = code_depgr thy consts;
   945     val constss = Graph.strong_conn eqngr;
   946     val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
   947       Symtab.update (const, consts)) consts) constss;
   948     fun succs consts = consts
   949       |> maps (Graph.imm_succs eqngr)
   950       |> subtract (op =) consts
   951       |> map (the o Symtab.lookup mapping)
   952       |> distinct (op =);
   953     val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
   954     fun namify consts = map (Code.string_of_const thy) consts
   955       |> commas;
   956     val prgr = map (fn (consts, constss) =>
   957       { name = namify consts, ID = namify consts, dir = "", unfold = true,
   958         path = "", parents = map namify constss }) conn;
   959   in Present.display_graph prgr end;
   960 
   961 local
   962 
   963 structure P = OuterParse
   964 and K = OuterKeyword
   965 
   966 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
   967 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
   968 
   969 in
   970 
   971 val _ =
   972   OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
   973     (Scan.repeat P.term_group
   974       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
   975         o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
   976 
   977 val _ =
   978   OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
   979     (Scan.repeat P.term_group
   980       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
   981         o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
   982 
   983 end;
   984 
   985 end; (*struct*)
   986 
   987 
   988 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;