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