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