src/Tools/Code/code_thingol.ML
author haftmann
Mon, 05 Oct 2009 08:36:33 +0200
changeset 32872 019201eb7e07
parent 32802 a0f38d8d633a
child 32873 333945c9ac6a
permissions -rw-r--r--
variables in type schemes must be renamed simultaneously with variables in equations
     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 raw_eqns =
   558       let
   559         val eqns = burrow_fst (clean_thms thy) raw_eqns;
   560         val ((vs, ty), _) = Code.typscheme_rhss_eqns thy c (map fst eqns);
   561       in
   562         fold_map (translate_tyvar_sort thy algbr funcgr) vs
   563         ##>> translate_typ thy algbr funcgr ty
   564         ##>> fold_map (translate_eqn thy algbr funcgr) eqns
   565         #>> (fn info => Fun (c, info))
   566       end;
   567     val stmt_const = case Code.get_datatype_of_constr thy c
   568      of SOME tyco => stmt_datatypecons tyco
   569       | NONE => (case AxClass.class_of_param thy c
   570          of SOME class => stmt_classparam class
   571           | NONE => stmt_fun (Code_Preproc.eqns funcgr c))
   572   in ensure_stmt lookup_const (declare_const thy) stmt_const c end
   573 and ensure_class thy (algbr as (_, algebra)) funcgr class =
   574   let
   575     val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
   576     val cs = #params (AxClass.get_info thy class);
   577     val stmt_class =
   578       fold_map (fn superclass => ensure_class thy algbr funcgr superclass
   579         ##>> ensure_classrel thy algbr funcgr (class, superclass)) superclasses
   580       ##>> fold_map (fn (c, ty) => ensure_const thy algbr funcgr c
   581         ##>> translate_typ thy algbr funcgr ty) cs
   582       #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
   583   in ensure_stmt lookup_class (declare_class thy) stmt_class class end
   584 and ensure_classrel thy algbr funcgr (subclass, superclass) =
   585   let
   586     val stmt_classrel =
   587       ensure_class thy algbr funcgr subclass
   588       ##>> ensure_class thy algbr funcgr superclass
   589       #>> Classrel;
   590   in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (subclass, superclass) end
   591 and ensure_inst thy (algbr as (_, algebra)) funcgr (class, tyco) =
   592   let
   593     val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
   594     val classparams = these (try (#params o AxClass.get_info thy) class);
   595     val vs = Name.names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
   596     val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
   597     val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
   598       Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
   599     val arity_typ = Type (tyco, map TFree vs);
   600     val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
   601     fun translate_superarity superclass =
   602       ensure_class thy algbr funcgr superclass
   603       ##>> ensure_classrel thy algbr funcgr (class, superclass)
   604       ##>> translate_dicts thy algbr funcgr NONE (arity_typ, [superclass])
   605       #>> (fn ((superclass, classrel), [DictConst (inst, dss)]) =>
   606             (superclass, (classrel, (inst, dss))));
   607     fun translate_classparam_inst (c, ty) =
   608       let
   609         val c_inst = Const (c, map_type_tfree (K arity_typ') ty);
   610         val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy c_inst);
   611         val c_ty = (apsnd Logic.unvarifyT o dest_Const o snd
   612           o Logic.dest_equals o Thm.prop_of) thm;
   613       in
   614         ensure_const thy algbr funcgr c
   615         ##>> translate_const thy algbr funcgr (SOME thm) c_ty
   616         #>> (fn (c, IConst c_inst) => ((c, c_inst), (thm, true)))
   617       end;
   618     val stmt_inst =
   619       ensure_class thy algbr funcgr class
   620       ##>> ensure_tyco thy algbr funcgr tyco
   621       ##>> fold_map (translate_tyvar_sort thy algbr funcgr) vs
   622       ##>> fold_map translate_superarity superclasses
   623       ##>> fold_map translate_classparam_inst classparams
   624       #>> (fn ((((class, tyco), arity), superarities), classparams) =>
   625              Classinst ((class, (tyco, arity)), (superarities, classparams)));
   626   in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
   627 and translate_typ thy algbr funcgr (TFree (v, _)) =
   628       pair (ITyVar (unprefix "'" v))
   629   | translate_typ thy algbr funcgr (Type (tyco, tys)) =
   630       ensure_tyco thy algbr funcgr tyco
   631       ##>> fold_map (translate_typ thy algbr funcgr) tys
   632       #>> (fn (tyco, tys) => tyco `%% tys)
   633 and translate_term thy algbr funcgr thm (Const (c, ty)) =
   634       translate_app thy algbr funcgr thm ((c, ty), [])
   635   | translate_term thy algbr funcgr thm (Free (v, _)) =
   636       pair (IVar (SOME v))
   637   | translate_term thy algbr funcgr thm (Abs (v, ty, t)) =
   638       let
   639         val (v', t') = Syntax.variant_abs (Name.desymbolize false v, ty, t);
   640         val v'' = if member (op =) (Term.add_free_names t' []) v'
   641           then SOME v' else NONE
   642       in
   643         translate_typ thy algbr funcgr ty
   644         ##>> translate_term thy algbr funcgr thm t'
   645         #>> (fn (ty, t) => (v'', ty) `|=> t)
   646       end
   647   | translate_term thy algbr funcgr thm (t as _ $ _) =
   648       case strip_comb t
   649        of (Const (c, ty), ts) =>
   650             translate_app thy algbr funcgr thm ((c, ty), ts)
   651         | (t', ts) =>
   652             translate_term thy algbr funcgr thm t'
   653             ##>> fold_map (translate_term thy algbr funcgr thm) ts
   654             #>> (fn (t, ts) => t `$$ ts)
   655 and translate_eqn thy algbr funcgr (thm, proper) =
   656   let
   657     val (args, rhs) = (apfst (snd o strip_comb) o Logic.dest_equals
   658       o Logic.unvarify o prop_of) thm;
   659   in
   660     fold_map (translate_term thy algbr funcgr (SOME thm)) args
   661     ##>> translate_term thy algbr funcgr (SOME thm) rhs
   662     #>> rpair (thm, proper)
   663   end
   664 and translate_const thy algbr funcgr thm (c, ty) =
   665   let
   666     val tys = Sign.const_typargs thy (c, ty);
   667     val sorts = (map snd o fst o Code_Preproc.typ funcgr) c;
   668     val tys_args = (fst o Term.strip_type) ty;
   669   in
   670     ensure_const thy algbr funcgr c
   671     ##>> fold_map (translate_typ thy algbr funcgr) tys
   672     ##>> fold_map (translate_dicts thy algbr funcgr thm) (tys ~~ sorts)
   673     ##>> fold_map (translate_typ thy algbr funcgr) tys_args
   674     #>> (fn (((c, tys), iss), tys_args) => IConst (c, ((tys, iss), tys_args)))
   675   end
   676 and translate_app_const thy algbr funcgr thm (c_ty, ts) =
   677   translate_const thy algbr funcgr thm c_ty
   678   ##>> fold_map (translate_term thy algbr funcgr thm) ts
   679   #>> (fn (t, ts) => t `$$ ts)
   680 and translate_case thy algbr funcgr thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
   681   let
   682     fun arg_types num_args ty = (fst o chop num_args o fst o strip_type) ty;
   683     val tys = arg_types num_args (snd c_ty);
   684     val ty = nth tys t_pos;
   685     fun mk_constr c t = let val n = Code.args_number thy c
   686       in ((c, arg_types n (fastype_of t) ---> ty), n) end;
   687     val constrs = if null case_pats then []
   688       else map2 mk_constr case_pats (nth_drop t_pos ts);
   689     fun casify naming constrs ty ts =
   690       let
   691         val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
   692         fun collapse_clause vs_map ts body =
   693           let
   694           in case body
   695            of IConst (c, _) => if member (op =) undefineds c
   696                 then []
   697                 else [(ts, body)]
   698             | ICase (((IVar (SOME v), _), subclauses), _) =>
   699                 if forall (fn (pat', body') => exists_var pat' v
   700                   orelse not (exists_var body' v)) subclauses
   701                 then case AList.lookup (op =) vs_map v
   702                  of SOME i => maps (fn (pat', body') =>
   703                       collapse_clause (AList.delete (op =) v vs_map)
   704                         (nth_map i (K pat') ts) body') subclauses
   705                   | NONE => [(ts, body)]
   706                 else [(ts, body)]
   707             | _ => [(ts, body)]
   708           end;
   709         fun mk_clause mk tys t =
   710           let
   711             val (vs, body) = unfold_abs_eta tys t;
   712             val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
   713             val ts = map (IVar o fst) vs;
   714           in map mk (collapse_clause vs_map ts body) end;
   715         val t = nth ts t_pos;
   716         val ts_clause = nth_drop t_pos ts;
   717         val clauses = if null case_pats
   718           then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
   719           else maps (fn ((constr as IConst (_, (_, tys)), n), t) =>
   720             mk_clause (fn (ts, body) => (constr `$$ ts, body)) (curry Library.take n tys) t)
   721               (constrs ~~ ts_clause);
   722       in ((t, ty), clauses) end;
   723   in
   724     translate_const thy algbr funcgr thm c_ty
   725     ##>> fold_map (fn (constr, n) => translate_const thy algbr funcgr thm constr #>> rpair n) constrs
   726     ##>> translate_typ thy algbr funcgr ty
   727     ##>> fold_map (translate_term thy algbr funcgr thm) ts
   728     #-> (fn (((t, constrs), ty), ts) =>
   729       `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
   730   end
   731 and translate_app_case thy algbr funcgr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
   732   if length ts < num_args then
   733     let
   734       val k = length ts;
   735       val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
   736       val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
   737       val vs = Name.names ctxt "a" tys;
   738     in
   739       fold_map (translate_typ thy algbr funcgr) tys
   740       ##>> translate_case thy algbr funcgr thm case_scheme ((c, ty), ts @ map Free vs)
   741       #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
   742     end
   743   else if length ts > num_args then
   744     translate_case thy algbr funcgr thm case_scheme ((c, ty), Library.take (num_args, ts))
   745     ##>> fold_map (translate_term thy algbr funcgr thm) (Library.drop (num_args, ts))
   746     #>> (fn (t, ts) => t `$$ ts)
   747   else
   748     translate_case thy algbr funcgr thm case_scheme ((c, ty), ts)
   749 and translate_app thy algbr funcgr thm (c_ty_ts as ((c, _), _)) =
   750   case Code.get_case_scheme thy c
   751    of SOME case_scheme => translate_app_case thy algbr funcgr thm case_scheme c_ty_ts
   752     | NONE => translate_app_const thy algbr funcgr thm c_ty_ts
   753 and translate_tyvar_sort thy (algbr as (proj_sort, _)) funcgr (v, sort) =
   754   fold_map (ensure_class thy algbr funcgr) (proj_sort sort)
   755   #>> (fn sort => (unprefix "'" v, sort))
   756 and translate_dicts thy (algbr as (proj_sort, algebra)) funcgr thm (ty, sort) =
   757   let
   758     datatype typarg =
   759         Global of (class * string) * typarg list list
   760       | Local of (class * class) list * (string * (int * sort));
   761     fun class_relation (Global ((_, tyco), yss), _) class =
   762           Global ((class, tyco), yss)
   763       | class_relation (Local (classrels, v), subclass) superclass =
   764           Local ((subclass, superclass) :: classrels, v);
   765     fun type_constructor tyco yss class =
   766       Global ((class, tyco), (map o map) fst yss);
   767     fun type_variable (TFree (v, sort)) =
   768       let
   769         val sort' = proj_sort sort;
   770       in map_index (fn (n, class) => (Local ([], (v, (n, sort'))), class)) sort' end;
   771     val typargs = Sorts.of_sort_derivation algebra
   772       {class_relation = class_relation, type_constructor = type_constructor,
   773        type_variable = type_variable} (ty, proj_sort sort)
   774       handle Sorts.CLASS_ERROR e => not_wellsorted thy thm ty sort e;
   775     fun mk_dict (Global (inst, yss)) =
   776           ensure_inst thy algbr funcgr inst
   777           ##>> (fold_map o fold_map) mk_dict yss
   778           #>> (fn (inst, dss) => DictConst (inst, dss))
   779       | mk_dict (Local (classrels, (v, (n, sort)))) =
   780           fold_map (ensure_classrel thy algbr funcgr) classrels
   781           #>> (fn classrels => DictVar (classrels, (unprefix "'" v, (n, length sort))))
   782   in fold_map mk_dict typargs end;
   783 
   784 
   785 (* store *)
   786 
   787 structure Program = Code_Data_Fun
   788 (
   789   type T = naming * program;
   790   val empty = (empty_naming, Graph.empty);
   791   fun purge thy cs (naming, program) =
   792     let
   793       val names_delete = cs
   794         |> map_filter (lookup_const naming)
   795         |> filter (can (Graph.get_node program))
   796         |> Graph.all_preds program;
   797       val program' = Graph.del_nodes names_delete program;
   798     in (naming, program') end;
   799 );
   800 
   801 val cached_program = Program.get;
   802 
   803 fun invoke_generation thy (algebra, funcgr) f name =
   804   Program.change_yield thy (fn naming_program => (NONE, naming_program)
   805     |> f thy algebra funcgr name
   806     |-> (fn name => fn (_, naming_program) => (name, naming_program)));
   807 
   808 
   809 (* program generation *)
   810 
   811 fun consts_program thy cs =
   812   let
   813     fun project_consts cs (naming, program) =
   814       let
   815         val cs_all = Graph.all_succs program cs;
   816       in (cs, (naming, Graph.subgraph (member (op =) cs_all) program)) end;
   817     fun generate_consts thy algebra funcgr =
   818       fold_map (ensure_const thy algebra funcgr);
   819   in
   820     invoke_generation thy (Code_Preproc.obtain thy cs []) generate_consts cs
   821     |-> project_consts
   822   end;
   823 
   824 
   825 (* value evaluation *)
   826 
   827 fun ensure_value thy algbr funcgr t =
   828   let
   829     val ty = fastype_of t;
   830     val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
   831       o dest_TFree))) t [];
   832     val stmt_value =
   833       fold_map (translate_tyvar_sort thy algbr funcgr) vs
   834       ##>> translate_typ thy algbr funcgr ty
   835       ##>> translate_term thy algbr funcgr NONE t
   836       #>> (fn ((vs, ty), t) => Fun
   837         (Term.dummy_patternN, ((vs, ty), [(([], t), (Drule.dummy_thm, true))])));
   838     fun term_value (dep, (naming, program1)) =
   839       let
   840         val Fun (_, (vs_ty, [(([], t), _)])) =
   841           Graph.get_node program1 Term.dummy_patternN;
   842         val deps = Graph.imm_succs program1 Term.dummy_patternN;
   843         val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
   844         val deps_all = Graph.all_succs program2 deps;
   845         val program3 = Graph.subgraph (member (op =) deps_all) program2;
   846       in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
   847   in
   848     ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
   849     #> snd
   850     #> term_value
   851   end;
   852 
   853 fun base_evaluator thy evaluator algebra funcgr vs t =
   854   let
   855     val (((naming, program), (((vs', ty'), t'), deps)), _) =
   856       invoke_generation thy (algebra, funcgr) ensure_value t;
   857     val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
   858   in evaluator naming program ((vs'', (vs', ty')), t') deps end;
   859 
   860 fun eval_conv thy = Code_Preproc.eval_conv thy o base_evaluator thy;
   861 fun eval thy postproc = Code_Preproc.eval thy postproc o base_evaluator thy;
   862 
   863 
   864 (** diagnostic commands **)
   865 
   866 fun read_const_exprs thy =
   867   let
   868     fun consts_of some_thyname =
   869       let
   870         val thy' = case some_thyname
   871          of SOME thyname => ThyInfo.the_theory thyname thy
   872           | NONE => thy;
   873         val cs = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
   874           ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
   875         fun belongs_here c =
   876           not (exists (fn thy'' => Sign.declared_const thy'' c) (Theory.parents_of thy'))
   877       in case some_thyname
   878        of NONE => cs
   879         | SOME thyname => filter belongs_here cs
   880       end;
   881     fun read_const_expr "*" = ([], consts_of NONE)
   882       | read_const_expr s = if String.isSuffix ".*" s
   883           then ([], consts_of (SOME (unsuffix ".*" s)))
   884           else ([Code.read_const thy s], []);
   885   in pairself flat o split_list o map read_const_expr end;
   886 
   887 fun code_depgr thy consts =
   888   let
   889     val (_, eqngr) = Code_Preproc.obtain thy consts [];
   890     val select = Graph.all_succs eqngr consts;
   891   in
   892     eqngr
   893     |> not (null consts) ? Graph.subgraph (member (op =) select) 
   894     |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
   895   end;
   896 
   897 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
   898 
   899 fun code_deps thy consts =
   900   let
   901     val eqngr = code_depgr thy consts;
   902     val constss = Graph.strong_conn eqngr;
   903     val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
   904       Symtab.update (const, consts)) consts) constss;
   905     fun succs consts = consts
   906       |> maps (Graph.imm_succs eqngr)
   907       |> subtract (op =) consts
   908       |> map (the o Symtab.lookup mapping)
   909       |> distinct (op =);
   910     val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
   911     fun namify consts = map (Code.string_of_const thy) consts
   912       |> commas;
   913     val prgr = map (fn (consts, constss) =>
   914       { name = namify consts, ID = namify consts, dir = "", unfold = true,
   915         path = "", parents = map namify constss }) conn;
   916   in Present.display_graph prgr end;
   917 
   918 local
   919 
   920 structure P = OuterParse
   921 and K = OuterKeyword
   922 
   923 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
   924 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
   925 
   926 in
   927 
   928 val _ =
   929   OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
   930     (Scan.repeat P.term_group
   931       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
   932         o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
   933 
   934 val _ =
   935   OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
   936     (Scan.repeat P.term_group
   937       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
   938         o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
   939 
   940 end;
   941 
   942 end; (*struct*)
   943 
   944 
   945 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;