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