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