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