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