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