src/Tools/Code/code_thingol.ML
author bulwahn
Wed, 07 Sep 2011 13:51:36 +0200
changeset 45661 fddb09e6f84d
parent 45660 26b19918e670
child 45663 238c6c7da908
permissions -rw-r--r--
removing previous crude approximation to add type annotations to disambiguate types
     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 * itype)) * bool)
    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 labelled_name: theory -> program -> string -> string
    92   val group_stmts: theory -> program
    93     -> ((string * stmt) list * (string * stmt) list
    94       * ((string * stmt) list * (string * stmt) list)) list
    95 
    96   val read_const_exprs: theory -> string list -> string list * string list
    97   val consts_program: theory -> bool -> string list -> string list * (naming * program)
    98   val dynamic_conv: theory -> (naming -> program
    99     -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
   100     -> conv
   101   val dynamic_value: theory -> ((term -> term) -> 'a -> 'a) -> (naming -> program
   102     -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
   103     -> term -> 'a
   104   val static_conv: theory -> string list -> (naming -> program -> string list
   105     -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
   106     -> conv
   107   val static_conv_simple: theory -> string list
   108     -> (program -> (string * sort) list -> term -> conv) -> conv
   109   val static_value: theory -> ((term -> term) -> 'a -> 'a) -> string list ->
   110     (naming -> program -> string list
   111       -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
   112     -> term -> 'a
   113 end;
   114 
   115 structure Code_Thingol: CODE_THINGOL =
   116 struct
   117 
   118 (** auxiliary **)
   119 
   120 fun unfoldl dest x =
   121   case dest x
   122    of NONE => (x, [])
   123     | SOME (x1, x2) =>
   124         let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
   125 
   126 fun unfoldr dest x =
   127   case dest x
   128    of NONE => ([], x)
   129     | SOME (x1, x2) =>
   130         let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
   131 
   132 
   133 (** language core - types, terms **)
   134 
   135 type vname = string;
   136 
   137 datatype dict =
   138     Dict of string list * plain_dict
   139 and plain_dict = 
   140     Dict_Const of string * dict list list
   141   | Dict_Var of vname * (int * int)
   142 
   143 datatype itype =
   144     `%% of string * itype list
   145   | ITyVar of vname;
   146 
   147 type const = string * (((itype list * dict list list) *
   148   (itype list (*types of arguments*) * itype (*body type*))) * bool (*requires type annotation*))
   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.invent_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.invent_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') = Name.variant 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 lookup_classparam_instance program name = program |> Graph.get_first
   480   (fn (_, (Classinst ((class, _), (_, (param_insts, _))), _)) =>
   481     Option.map (fn ((const, _), _) => (class, const))
   482       (find_first (fn ((_, (inst_const, _)), _) => inst_const = name) param_insts) | _ => NONE)
   483   
   484 fun labelled_name thy program name =
   485   let val ctxt = Proof_Context.init_global thy in
   486     case Graph.get_node program name of
   487       Fun (c, _) => quote (Code.string_of_const thy c)
   488     | Datatype (tyco, _) => "type " ^ quote (Proof_Context.extern_type ctxt tyco)
   489     | Datatypecons (c, _) => quote (Code.string_of_const thy c)
   490     | Class (class, _) => "class " ^ quote (Proof_Context.extern_class ctxt class)
   491     | Classrel (sub, super) =>
   492         let
   493           val Class (sub, _) = Graph.get_node program sub;
   494           val Class (super, _) = Graph.get_node program super;
   495         in
   496           quote (Proof_Context.extern_class ctxt sub ^ " < " ^ Proof_Context.extern_class ctxt super)
   497         end
   498     | Classparam (c, _) => quote (Code.string_of_const thy c)
   499     | Classinst ((class, (tyco, _)), _) =>
   500         let
   501           val Class (class, _) = Graph.get_node program class;
   502           val Datatype (tyco, _) = Graph.get_node program tyco;
   503         in
   504           quote (Proof_Context.extern_type ctxt tyco ^ " :: " ^ Proof_Context.extern_class ctxt class)
   505         end
   506   end;
   507 
   508 fun linear_stmts program =
   509   rev (Graph.strong_conn program)
   510   |> map (AList.make (Graph.get_node program));
   511 
   512 fun group_stmts thy program =
   513   let
   514     fun is_fun (_, Fun _) = true | is_fun _ = false;
   515     fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
   516     fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
   517     fun is_class (_, Class _) = true | is_class _ = false;
   518     fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
   519     fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
   520     fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
   521     fun group stmts =
   522       if forall (is_datatypecons orf is_datatype) stmts
   523       then (filter is_datatype stmts, [], ([], []))
   524       else if forall (is_class orf is_classrel orf is_classparam) stmts
   525       then ([], filter is_class stmts, ([], []))
   526       else if forall (is_fun orf is_classinst) stmts
   527       then ([], [], List.partition is_fun stmts)
   528       else error ("Illegal mutual dependencies: " ^
   529         (commas o map (labelled_name thy program o fst)) stmts)
   530   in
   531     linear_stmts program
   532     |> map group
   533   end;
   534 
   535 
   536 (** translation kernel **)
   537 
   538 (* generic mechanisms *)
   539 
   540 fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
   541   let
   542     fun add_dep name = case dep of NONE => I
   543       | SOME dep => Graph.add_edge (dep, name);
   544     val (name, naming') = case lookup naming thing
   545      of SOME name => (name, naming)
   546       | NONE => declare thing naming;
   547   in case try (Graph.get_node program) name
   548    of SOME stmt => program
   549         |> add_dep name
   550         |> pair naming'
   551         |> pair dep
   552         |> pair name
   553     | NONE => program
   554         |> Graph.default_node (name, NoStmt)
   555         |> add_dep name
   556         |> pair naming'
   557         |> curry generate (SOME name)
   558         ||> snd
   559         |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
   560         |> pair dep
   561         |> pair name
   562   end;
   563 
   564 exception PERMISSIVE of unit;
   565 
   566 fun translation_error thy permissive some_thm msg sub_msg =
   567   if permissive
   568   then raise PERMISSIVE ()
   569   else
   570     let
   571       val err_thm =
   572         (case some_thm of
   573           SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")"
   574         | NONE => "");
   575     in error (msg ^ err_thm ^ ":\n" ^ sub_msg) end;
   576 
   577 fun not_wellsorted thy permissive some_thm ty sort e =
   578   let
   579     val ctxt = Syntax.init_pretty_global thy;
   580     val err_class = Sorts.class_error ctxt e;
   581     val err_typ =
   582       "Type " ^ Syntax.string_of_typ ctxt ty ^ " not of sort " ^
   583         Syntax.string_of_sort_global thy sort;
   584   in
   585     translation_error thy permissive some_thm "Wellsortedness error"
   586       (err_typ ^ "\n" ^ err_class)
   587   end;
   588 
   589 (* inference of type annotations for disambiguation with type classes *)
   590 
   591 fun annotate_term (Const (c', T'), Const (c, T)) tvar_names =
   592     let
   593       val tvar_names' = Term.add_tvar_namesT T' tvar_names
   594     in
   595       (Const (c, if eq_set (op =) (tvar_names, tvar_names') then T else Type("", [T])), tvar_names')
   596     end
   597   | annotate_term (t1 $ u1, t $ u) tvar_names =
   598     let
   599       val (u', tvar_names') = annotate_term (u1, u) tvar_names
   600       val (t', tvar_names'') = annotate_term (t1, t) tvar_names'    
   601     in
   602       (t' $ u', tvar_names'')
   603     end
   604   | annotate_term (Abs (_, _, t1) , Abs (x, T, t)) tvar_names =
   605     apfst (fn t => Abs (x, T, t)) (annotate_term (t1, t) tvar_names)
   606   | annotate_term (_, t) tvar_names = (t, tvar_names)
   607 
   608 fun annotate_eqns thy eqns = 
   609   let
   610     val ctxt = ProofContext.init_global thy
   611     val erase = map_types (fn _ => Type_Infer.anyT [])
   612     val reinfer = singleton (Type_Infer_Context.infer_types ctxt)
   613     fun add_annotations ((args, (rhs, some_abs)), (SOME th, proper)) =
   614       let
   615         val (lhs, drhs) = Logic.dest_equals (prop_of (Thm.unvarify_global th))
   616         val drhs' = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase drhs))))
   617         val (rhs', _) = annotate_term (drhs', rhs) []
   618      in
   619         ((args, (rhs', some_abs)), (SOME th, proper))
   620      end
   621      | add_annotations eqn = eqn
   622   in
   623     map add_annotations eqns
   624   end;
   625 
   626 (* translation *)
   627 
   628 fun ensure_tyco thy algbr eqngr permissive tyco =
   629   let
   630     val ((vs, cos), _) = Code.get_type thy tyco;
   631     val stmt_datatype =
   632       fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
   633       ##>> fold_map (fn (c, (vs, tys)) =>
   634         ensure_const thy algbr eqngr permissive c
   635         ##>> pair (map (unprefix "'" o fst) vs)
   636         ##>> fold_map (translate_typ thy algbr eqngr permissive) tys) cos
   637       #>> (fn info => Datatype (tyco, info));
   638   in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
   639 and ensure_const thy algbr eqngr permissive c =
   640   let
   641     fun stmt_datatypecons tyco =
   642       ensure_tyco thy algbr eqngr permissive tyco
   643       #>> (fn tyco => Datatypecons (c, tyco));
   644     fun stmt_classparam class =
   645       ensure_class thy algbr eqngr permissive class
   646       #>> (fn class => Classparam (c, class));
   647     fun stmt_fun cert =
   648       let
   649         val ((vs, ty), eqns) = Code.equations_of_cert thy cert;
   650         val eqns' = annotate_eqns thy eqns
   651         val some_case_cong = Code.get_case_cong thy c;
   652       in
   653         fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
   654         ##>> translate_typ thy algbr eqngr permissive ty
   655         ##>> translate_eqns thy algbr eqngr permissive eqns'
   656         #>> (fn info => Fun (c, (info, some_case_cong)))
   657       end;
   658     val stmt_const = case Code.get_type_of_constr_or_abstr thy c
   659      of SOME (tyco, _) => stmt_datatypecons tyco
   660       | NONE => (case AxClass.class_of_param thy c
   661          of SOME class => stmt_classparam class
   662           | NONE => stmt_fun (Code_Preproc.cert eqngr c))
   663   in ensure_stmt lookup_const (declare_const thy) stmt_const c end
   664 and ensure_class thy (algbr as (_, algebra)) eqngr permissive class =
   665   let
   666     val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
   667     val cs = #params (AxClass.get_info thy class);
   668     val stmt_class =
   669       fold_map (fn super_class => ensure_class thy algbr eqngr permissive super_class
   670         ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)) super_classes
   671       ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr permissive c
   672         ##>> translate_typ thy algbr eqngr permissive ty) cs
   673       #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
   674   in ensure_stmt lookup_class (declare_class thy) stmt_class class end
   675 and ensure_classrel thy algbr eqngr permissive (sub_class, super_class) =
   676   let
   677     val stmt_classrel =
   678       ensure_class thy algbr eqngr permissive sub_class
   679       ##>> ensure_class thy algbr eqngr permissive super_class
   680       #>> Classrel;
   681   in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (sub_class, super_class) end
   682 and ensure_inst thy (algbr as (_, algebra)) eqngr permissive (class, tyco) =
   683   let
   684     val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
   685     val these_classparams = these o try (#params o AxClass.get_info thy);
   686     val classparams = these_classparams class;
   687     val further_classparams = maps these_classparams
   688       ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
   689     val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
   690     val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
   691     val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
   692       Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
   693     val arity_typ = Type (tyco, map TFree vs);
   694     val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
   695     fun translate_super_instance super_class =
   696       ensure_class thy algbr eqngr permissive super_class
   697       ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)
   698       ##>> translate_dicts thy algbr eqngr permissive NONE (arity_typ, [super_class])
   699       #>> (fn ((super_class, classrel), [Dict ([], Dict_Const (inst, dss))]) =>
   700             (super_class, (classrel, (inst, dss))));
   701     fun translate_classparam_instance (c, ty) =
   702       let
   703         val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
   704         val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy raw_const);
   705         val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
   706           o Logic.dest_equals o Thm.prop_of) thm;
   707       in
   708         ensure_const thy algbr eqngr permissive c
   709         ##>> translate_const thy algbr eqngr permissive (SOME thm) (const, NONE)
   710         #>> (fn (c, IConst const') => ((c, const'), (thm, true)))
   711       end;
   712     val stmt_inst =
   713       ensure_class thy algbr eqngr permissive class
   714       ##>> ensure_tyco thy algbr eqngr permissive tyco
   715       ##>> fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
   716       ##>> fold_map translate_super_instance super_classes
   717       ##>> fold_map translate_classparam_instance classparams
   718       ##>> fold_map translate_classparam_instance further_classparams
   719       #>> (fn (((((class, tyco), arity_args), super_instances),
   720         classparam_instances), further_classparam_instances) =>
   721           Classinst ((class, (tyco, arity_args)), (super_instances,
   722             (classparam_instances, further_classparam_instances))));
   723   in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
   724 and translate_typ thy algbr eqngr permissive (TFree (v, _)) =
   725       pair (ITyVar (unprefix "'" v))
   726   | translate_typ thy algbr eqngr permissive (Type (tyco, tys)) =
   727       ensure_tyco thy algbr eqngr permissive tyco
   728       ##>> fold_map (translate_typ thy algbr eqngr permissive) tys
   729       #>> (fn (tyco, tys) => tyco `%% tys)
   730 and translate_term thy algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
   731       translate_app thy algbr eqngr permissive some_thm (((c, ty), []), some_abs)
   732   | translate_term thy algbr eqngr permissive some_thm (Free (v, _), some_abs) =
   733       pair (IVar (SOME v))
   734   | translate_term thy algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
   735       let
   736         val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize false v, ty, t);
   737         val v'' = if member (op =) (Term.add_free_names t' []) v'
   738           then SOME v' else NONE
   739       in
   740         translate_typ thy algbr eqngr permissive ty
   741         ##>> translate_term thy algbr eqngr permissive some_thm (t', some_abs)
   742         #>> (fn (ty, t) => (v'', ty) `|=> t)
   743       end
   744   | translate_term thy algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
   745       case strip_comb t
   746        of (Const (c, ty), ts) =>
   747             translate_app thy algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
   748         | (t', ts) =>
   749             translate_term thy algbr eqngr permissive some_thm (t', some_abs)
   750             ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
   751             #>> (fn (t, ts) => t `$$ ts)
   752 and translate_eqn thy algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
   753   fold_map (translate_term thy algbr eqngr permissive some_thm) args
   754   ##>> translate_term thy algbr eqngr permissive some_thm (rhs, some_abs)
   755   #>> rpair (some_thm, proper)
   756 and translate_eqns thy algbr eqngr permissive eqns prgrm =
   757   prgrm |> fold_map (translate_eqn thy algbr eqngr permissive) eqns
   758     handle PERMISSIVE () => ([], prgrm)
   759 and translate_const thy algbr eqngr permissive some_thm ((c, ty), some_abs) =
   760   let
   761     val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
   762         andalso Code.is_abstr thy c
   763         then translation_error thy permissive some_thm
   764           "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
   765       else ()
   766     val (annotate, ty') = (case ty of Type("", [ty']) => (true, ty') | ty' => (false, ty'))
   767     val arg_typs = Sign.const_typargs thy (c, ty');
   768     val sorts = Code_Preproc.sortargs eqngr c;
   769     val (function_typs, body_typ) = Term.strip_type ty';
   770   in
   771     ensure_const thy algbr eqngr permissive c
   772     ##>> fold_map (translate_typ thy algbr eqngr permissive) arg_typs
   773     ##>> fold_map (translate_dicts thy algbr eqngr permissive some_thm) (arg_typs ~~ sorts)
   774     ##>> fold_map (translate_typ thy algbr eqngr permissive) (body_typ :: function_typs)
   775     #>> (fn (((c, arg_typs), dss), body_typ :: function_typs) =>
   776       IConst (c, (((arg_typs, dss), (function_typs, body_typ)), annotate)))
   777   end
   778 and translate_app_const thy algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
   779   translate_const thy algbr eqngr permissive some_thm (c_ty, some_abs)
   780   ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
   781   #>> (fn (t, ts) => t `$$ ts)
   782 and translate_case thy algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
   783   let
   784     fun arg_types num_args ty = fst (chop num_args (binder_types ty));
   785     val tys = arg_types num_args (snd c_ty);
   786     val ty = nth tys t_pos;
   787     fun mk_constr c t = let val n = Code.args_number thy c
   788       in ((c, arg_types n (fastype_of t) ---> ty), n) end;
   789     val constrs = if null case_pats then []
   790       else map2 mk_constr case_pats (nth_drop t_pos ts);
   791     fun casify naming constrs ty ts =
   792       let
   793         val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
   794         fun collapse_clause vs_map ts body =
   795           let
   796           in case body
   797            of IConst (c, _) => if member (op =) undefineds c
   798                 then []
   799                 else [(ts, body)]
   800             | ICase (((IVar (SOME v), _), subclauses), _) =>
   801                 if forall (fn (pat', body') => exists_var pat' v
   802                   orelse not (exists_var body' v)) subclauses
   803                 then case AList.lookup (op =) vs_map v
   804                  of SOME i => maps (fn (pat', body') =>
   805                       collapse_clause (AList.delete (op =) v vs_map)
   806                         (nth_map i (K pat') ts) body') subclauses
   807                   | NONE => [(ts, body)]
   808                 else [(ts, body)]
   809             | _ => [(ts, body)]
   810           end;
   811         fun mk_clause mk tys t =
   812           let
   813             val (vs, body) = unfold_abs_eta tys t;
   814             val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
   815             val ts = map (IVar o fst) vs;
   816           in map mk (collapse_clause vs_map ts body) end;
   817         val t = nth ts t_pos;
   818         val ts_clause = nth_drop t_pos ts;
   819         val clauses = if null case_pats
   820           then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
   821           else maps (fn ((constr as IConst (_, ((_, (tys, _)), _)), n), t) =>
   822             mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
   823               (constrs ~~ ts_clause);
   824       in ((t, ty), clauses) end;
   825   in
   826     translate_const thy algbr eqngr permissive some_thm (c_ty, NONE)
   827     ##>> fold_map (fn (constr, n) => translate_const thy algbr eqngr permissive some_thm (constr, NONE)
   828       #>> rpair n) constrs
   829     ##>> translate_typ thy algbr eqngr permissive ty
   830     ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
   831     #-> (fn (((t, constrs), ty), ts) =>
   832       `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
   833   end
   834 and translate_app_case thy algbr eqngr permissive some_thm (case_scheme as (num_args, _)) ((c, ty), ts) =
   835   if length ts < num_args then
   836     let
   837       val k = length ts;
   838       val tys = (take (num_args - k) o drop k o fst o strip_type) ty;
   839       val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
   840       val vs = Name.invent_names ctxt "a" tys;
   841     in
   842       fold_map (translate_typ thy algbr eqngr permissive) tys
   843       ##>> translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts @ map Free vs)
   844       #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
   845     end
   846   else if length ts > num_args then
   847     translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), take num_args ts)
   848     ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) (drop num_args ts)
   849     #>> (fn (t, ts) => t `$$ ts)
   850   else
   851     translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts)
   852 and translate_app thy algbr eqngr permissive some_thm (c_ty_ts as ((c, _), _), some_abs) =
   853   case Code.get_case_scheme thy c
   854    of SOME case_scheme => translate_app_case thy algbr eqngr permissive some_thm case_scheme c_ty_ts
   855     | NONE => translate_app_const thy algbr eqngr permissive some_thm (c_ty_ts, some_abs)
   856 and translate_tyvar_sort thy (algbr as (proj_sort, _)) eqngr permissive (v, sort) =
   857   fold_map (ensure_class thy algbr eqngr permissive) (proj_sort sort)
   858   #>> (fn sort => (unprefix "'" v, sort))
   859 and translate_dicts thy (algbr as (proj_sort, algebra)) eqngr permissive some_thm (ty, sort) =
   860   let
   861     datatype typarg_witness =
   862         Weakening of (class * class) list * plain_typarg_witness
   863     and plain_typarg_witness =
   864         Global of (class * string) * typarg_witness list list
   865       | Local of string * (int * sort);
   866     fun class_relation ((Weakening (classrels, x)), sub_class) super_class =
   867       Weakening ((sub_class, super_class) :: classrels, x);
   868     fun type_constructor (tyco, _) dss class =
   869       Weakening ([], Global ((class, tyco), (map o map) fst dss));
   870     fun type_variable (TFree (v, sort)) =
   871       let
   872         val sort' = proj_sort sort;
   873       in map_index (fn (n, class) => (Weakening ([], Local (v, (n, sort'))), class)) sort' end;
   874     val typarg_witnesses = Sorts.of_sort_derivation algebra
   875       {class_relation = K (Sorts.classrel_derivation algebra class_relation),
   876        type_constructor = type_constructor,
   877        type_variable = type_variable} (ty, proj_sort sort)
   878       handle Sorts.CLASS_ERROR e => not_wellsorted thy permissive some_thm ty sort e;
   879     fun mk_dict (Weakening (classrels, x)) =
   880           fold_map (ensure_classrel thy algbr eqngr permissive) classrels
   881           ##>> mk_plain_dict x
   882           #>> Dict 
   883     and mk_plain_dict (Global (inst, dss)) =
   884           ensure_inst thy algbr eqngr permissive inst
   885           ##>> (fold_map o fold_map) mk_dict dss
   886           #>> (fn (inst, dss) => Dict_Const (inst, dss))
   887       | mk_plain_dict (Local (v, (n, sort))) =
   888           pair (Dict_Var (unprefix "'" v, (n, length sort)))
   889   in fold_map mk_dict typarg_witnesses end;
   890 
   891 
   892 (* store *)
   893 
   894 structure Program = Code_Data
   895 (
   896   type T = naming * program;
   897   val empty = (empty_naming, Graph.empty);
   898 );
   899 
   900 fun invoke_generation ignore_cache thy (algebra, eqngr) f name =
   901   Program.change_yield (if ignore_cache then NONE else SOME thy)
   902     (fn naming_program => (NONE, naming_program)
   903       |> f thy algebra eqngr name
   904       |-> (fn name => fn (_, naming_program) => (name, naming_program)));
   905 
   906 
   907 (* program generation *)
   908 
   909 fun consts_program thy permissive consts =
   910   let
   911     fun project_consts consts (naming, program) =
   912       if permissive then (consts, (naming, program))
   913       else (consts, (naming, Graph.subgraph
   914         (member (op =) (Graph.all_succs program consts)) program));
   915     fun generate_consts thy algebra eqngr =
   916       fold_map (ensure_const thy algebra eqngr permissive);
   917   in
   918     invoke_generation permissive thy (Code_Preproc.obtain false thy consts [])
   919       generate_consts consts
   920     |-> project_consts
   921   end;
   922 
   923 
   924 (* value evaluation *)
   925 
   926 fun ensure_value thy algbr eqngr t =
   927   let
   928     val ty = fastype_of t;
   929     val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
   930       o dest_TFree))) t [];
   931     val stmt_value =
   932       fold_map (translate_tyvar_sort thy algbr eqngr false) vs
   933       ##>> translate_typ thy algbr eqngr false ty
   934       ##>> translate_term thy algbr eqngr false NONE (Code.subst_signatures thy t, NONE)
   935       #>> (fn ((vs, ty), t) => Fun
   936         (Term.dummy_patternN, (((vs, ty), [(([], t), (NONE, true))]), NONE)));
   937     fun term_value (dep, (naming, program1)) =
   938       let
   939         val Fun (_, ((vs_ty, [(([], t), _)]), _)) =
   940           Graph.get_node program1 Term.dummy_patternN;
   941         val deps = Graph.immediate_succs program1 Term.dummy_patternN;
   942         val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
   943         val deps_all = Graph.all_succs program2 deps;
   944         val program3 = Graph.subgraph (member (op =) deps_all) program2;
   945       in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
   946   in
   947     ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
   948     #> snd
   949     #> term_value
   950   end;
   951 
   952 fun original_sorts vs =
   953   map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v));
   954 
   955 fun dynamic_evaluator thy evaluator algebra eqngr vs t =
   956   let
   957     val (((naming, program), (((vs', ty'), t'), deps)), _) =
   958       invoke_generation false thy (algebra, eqngr) ensure_value t;
   959   in evaluator naming program ((original_sorts vs vs', (vs', ty')), t') deps end;
   960 
   961 fun dynamic_conv thy evaluator =
   962   Code_Preproc.dynamic_conv thy (dynamic_evaluator thy evaluator);
   963 
   964 fun dynamic_value thy postproc evaluator =
   965   Code_Preproc.dynamic_value thy postproc (dynamic_evaluator thy evaluator);
   966 
   967 fun lift_evaluation thy evaluation' algebra eqngr naming program vs t =
   968   let
   969     val (((_, program'), (((vs', ty'), t'), deps)), _) =
   970       ensure_value thy algebra eqngr t (NONE, (naming, program));
   971   in evaluation' ((original_sorts vs vs', (vs', ty')), t') deps end;
   972 
   973 fun lift_evaluator thy evaluator' consts algebra eqngr =
   974   let
   975     fun generate_consts thy algebra eqngr =
   976       fold_map (ensure_const thy algebra eqngr false);
   977     val (consts', (naming, program)) =
   978       invoke_generation true thy (algebra, eqngr) generate_consts consts;
   979     val evaluation' = evaluator' naming program consts';
   980   in lift_evaluation thy evaluation' algebra eqngr naming program end;
   981 
   982 fun lift_evaluator_simple thy evaluator' consts algebra eqngr =
   983   let
   984     fun generate_consts thy algebra eqngr =
   985       fold_map (ensure_const thy algebra eqngr false);
   986     val (consts', (naming, program)) =
   987       invoke_generation true thy (algebra, eqngr) generate_consts consts;
   988   in evaluator' program end;
   989 
   990 fun static_conv thy consts conv =
   991   Code_Preproc.static_conv thy consts (lift_evaluator thy conv consts);
   992 
   993 fun static_conv_simple thy consts conv =
   994   Code_Preproc.static_conv thy consts (lift_evaluator_simple thy conv consts);
   995 
   996 fun static_value thy postproc consts evaluator =
   997   Code_Preproc.static_value thy postproc consts (lift_evaluator thy evaluator consts);
   998 
   999 
  1000 (** diagnostic commands **)
  1001 
  1002 fun read_const_exprs thy =
  1003   let
  1004     fun consts_of thy' = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
  1005       ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
  1006     fun belongs_here thy' c = forall
  1007       (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
  1008     fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
  1009     fun read_const_expr "_" = ([], consts_of thy)
  1010       | read_const_expr s = if String.isSuffix "._" s
  1011           then ([], consts_of_select (Context.this_theory thy (unsuffix "._" s)))
  1012           else ([Code.read_const thy s], []);
  1013   in pairself flat o split_list o map read_const_expr end;
  1014 
  1015 fun code_depgr thy consts =
  1016   let
  1017     val (_, eqngr) = Code_Preproc.obtain true thy consts [];
  1018     val all_consts = Graph.all_succs eqngr consts;
  1019   in Graph.subgraph (member (op =) all_consts) eqngr end;
  1020 
  1021 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
  1022 
  1023 fun code_deps thy consts =
  1024   let
  1025     val eqngr = code_depgr thy consts;
  1026     val constss = Graph.strong_conn eqngr;
  1027     val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
  1028       Symtab.update (const, consts)) consts) constss;
  1029     fun succs consts = consts
  1030       |> maps (Graph.immediate_succs eqngr)
  1031       |> subtract (op =) consts
  1032       |> map (the o Symtab.lookup mapping)
  1033       |> distinct (op =);
  1034     val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
  1035     fun namify consts = map (Code.string_of_const thy) consts
  1036       |> commas;
  1037     val prgr = map (fn (consts, constss) =>
  1038       { name = namify consts, ID = namify consts, dir = "", unfold = true,
  1039         path = "", parents = map namify constss }) conn;
  1040   in Present.display_graph prgr end;
  1041 
  1042 local
  1043 
  1044 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
  1045 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
  1046 
  1047 in
  1048 
  1049 val _ =
  1050   Outer_Syntax.improper_command "code_thms" "print system of code equations for code" Keyword.diag
  1051     (Scan.repeat1 Parse.term_group
  1052       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
  1053         o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
  1054 
  1055 val _ =
  1056   Outer_Syntax.improper_command "code_deps" "visualize dependencies of code equations for code"
  1057     Keyword.diag
  1058     (Scan.repeat1 Parse.term_group
  1059       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
  1060         o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
  1061 
  1062 end;
  1063 
  1064 end; (*struct*)
  1065 
  1066 
  1067 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;