src/Tools/Code/code_thingol.ML
author haftmann
Tue Jun 30 19:31:50 2009 +0200 (2009-06-30)
changeset 31892 a2139b503981
parent 31890 e943b039f0ac
child 31935 3896169e6ff9
permissions -rw-r--r--
improved treatment of case patterns
     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     fun arg_types num_args ty = (fst o chop num_args o fst o strip_type) ty;
   635     val tys = arg_types num_args (snd c_ty);
   636     val ty = nth tys t_pos;
   637     fun mk_constr c t = let val n = Code.no_args thy c
   638       in ((c, arg_types (Code.no_args thy c) (fastype_of t) ---> ty), n) end;
   639     val constrs = if null case_pats then []
   640       else map2 mk_constr case_pats (nth_drop t_pos ts);
   641     fun casify naming constrs ty ts =
   642       let
   643         val t = nth ts t_pos;
   644         val ts_clause = nth_drop t_pos ts;
   645         val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
   646         fun mk_clause ((constr as IConst (_, (_, tys)), n), t) =
   647           let
   648             val (vs, t') = unfold_abs_eta (curry Library.take n tys) t;
   649             val is_undefined = case t
   650              of IConst (c, _) => member (op =) undefineds c
   651               | _ => false;
   652           in if is_undefined then NONE else SOME (constr `$$ map (IVar o fst) vs, t') end;
   653         val clauses = if null case_pats then let val ([(v, _)], t) =
   654             unfold_abs_eta [ty] (the_single ts_clause)
   655           in [(IVar v, t)] end
   656           else map_filter mk_clause (constrs ~~ ts_clause);
   657       in ((t, ty), clauses) end;
   658   in
   659     translate_const thy algbr funcgr thm c_ty
   660     ##>> fold_map (fn (constr, n) => translate_const thy algbr funcgr thm constr #>> rpair n) constrs
   661     ##>> translate_typ thy algbr funcgr ty
   662     ##>> fold_map (translate_term thy algbr funcgr thm) ts
   663     #-> (fn (((t, constrs), ty), ts) =>
   664       `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
   665   end
   666 and translate_app_case thy algbr funcgr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
   667   if length ts < num_args then
   668     let
   669       val k = length ts;
   670       val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
   671       val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
   672       val vs = Name.names ctxt "a" tys;
   673     in
   674       fold_map (translate_typ thy algbr funcgr) tys
   675       ##>> translate_case thy algbr funcgr thm case_scheme ((c, ty), ts @ map Free vs)
   676       #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
   677     end
   678   else if length ts > num_args then
   679     translate_case thy algbr funcgr thm case_scheme ((c, ty), Library.take (num_args, ts))
   680     ##>> fold_map (translate_term thy algbr funcgr thm) (Library.drop (num_args, ts))
   681     #>> (fn (t, ts) => t `$$ ts)
   682   else
   683     translate_case thy algbr funcgr thm case_scheme ((c, ty), ts)
   684 and translate_app thy algbr funcgr thm (c_ty_ts as ((c, _), _)) =
   685   case Code.get_case_scheme thy c
   686    of SOME case_scheme => translate_app_case thy algbr funcgr thm case_scheme c_ty_ts
   687     | NONE => translate_app_const thy algbr funcgr thm c_ty_ts
   688 and translate_tyvar_sort thy (algbr as (proj_sort, _)) funcgr (v, sort) =
   689   fold_map (ensure_class thy algbr funcgr) (proj_sort sort)
   690   #>> (fn sort => (unprefix "'" v, sort))
   691 and translate_dicts thy (algbr as (proj_sort, algebra)) funcgr thm (ty, sort) =
   692   let
   693     val pp = Syntax.pp_global thy;
   694     datatype typarg =
   695         Global of (class * string) * typarg list list
   696       | Local of (class * class) list * (string * (int * sort));
   697     fun class_relation (Global ((_, tyco), yss), _) class =
   698           Global ((class, tyco), yss)
   699       | class_relation (Local (classrels, v), subclass) superclass =
   700           Local ((subclass, superclass) :: classrels, v);
   701     fun type_constructor tyco yss class =
   702       Global ((class, tyco), (map o map) fst yss);
   703     fun type_variable (TFree (v, sort)) =
   704       let
   705         val sort' = proj_sort sort;
   706       in map_index (fn (n, class) => (Local ([], (v, (n, sort'))), class)) sort' end;
   707     val typargs = Sorts.of_sort_derivation pp algebra
   708       {class_relation = class_relation, type_constructor = type_constructor,
   709        type_variable = type_variable} (ty, proj_sort sort)
   710       handle Sorts.CLASS_ERROR e => not_wellsorted thy thm ty sort e;
   711     fun mk_dict (Global (inst, yss)) =
   712           ensure_inst thy algbr funcgr inst
   713           ##>> (fold_map o fold_map) mk_dict yss
   714           #>> (fn (inst, dss) => DictConst (inst, dss))
   715       | mk_dict (Local (classrels, (v, (k, sort)))) =
   716           fold_map (ensure_classrel thy algbr funcgr) classrels
   717           #>> (fn classrels => DictVar (classrels, (unprefix "'" v, (k, length sort))))
   718   in fold_map mk_dict typargs end;
   719 
   720 
   721 (* store *)
   722 
   723 structure Program = CodeDataFun
   724 (
   725   type T = naming * program;
   726   val empty = (empty_naming, Graph.empty);
   727   fun purge thy cs (naming, program) =
   728     let
   729       val names_delete = cs
   730         |> map_filter (lookup_const naming)
   731         |> filter (can (Graph.get_node program))
   732         |> Graph.all_preds program;
   733       val program' = Graph.del_nodes names_delete program;
   734     in (naming, program') end;
   735 );
   736 
   737 val cached_program = Program.get;
   738 
   739 fun invoke_generation thy (algebra, funcgr) f name =
   740   Program.change_yield thy (fn naming_program => (NONE, naming_program)
   741     |> f thy algebra funcgr name
   742     |-> (fn name => fn (_, naming_program) => (name, naming_program)));
   743 
   744 
   745 (* program generation *)
   746 
   747 fun consts_program thy cs =
   748   let
   749     fun project_consts cs (naming, program) =
   750       let
   751         val cs_all = Graph.all_succs program cs;
   752       in (cs, (naming, Graph.subgraph (member (op =) cs_all) program)) end;
   753     fun generate_consts thy algebra funcgr =
   754       fold_map (ensure_const thy algebra funcgr);
   755   in
   756     invoke_generation thy (Code_Preproc.obtain thy cs []) generate_consts cs
   757     |-> project_consts
   758   end;
   759 
   760 
   761 (* value evaluation *)
   762 
   763 fun ensure_value thy algbr funcgr t =
   764   let
   765     val ty = fastype_of t;
   766     val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
   767       o dest_TFree))) t [];
   768     val stmt_value =
   769       fold_map (translate_tyvar_sort thy algbr funcgr) vs
   770       ##>> translate_typ thy algbr funcgr ty
   771       ##>> translate_term thy algbr funcgr NONE t
   772       #>> (fn ((vs, ty), t) => Fun
   773         (Term.dummy_patternN, ((vs, ty), [(([], t), (Drule.dummy_thm, true))])));
   774     fun term_value (dep, (naming, program1)) =
   775       let
   776         val Fun (_, (vs_ty, [(([], t), _)])) =
   777           Graph.get_node program1 Term.dummy_patternN;
   778         val deps = Graph.imm_succs program1 Term.dummy_patternN;
   779         val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
   780         val deps_all = Graph.all_succs program2 deps;
   781         val program3 = Graph.subgraph (member (op =) deps_all) program2;
   782       in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
   783   in
   784     ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
   785     #> snd
   786     #> term_value
   787   end;
   788 
   789 fun base_evaluator thy evaluator algebra funcgr vs t =
   790   let
   791     val (((naming, program), (((vs', ty'), t'), deps)), _) =
   792       invoke_generation thy (algebra, funcgr) ensure_value t;
   793     val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
   794   in evaluator naming program ((vs'', (vs', ty')), t') deps end;
   795 
   796 fun eval_conv thy prep_sort = Code_Preproc.eval_conv thy prep_sort o base_evaluator thy;
   797 fun eval thy prep_sort postproc = Code_Preproc.eval thy prep_sort postproc o base_evaluator thy;
   798 
   799 
   800 (** diagnostic commands **)
   801 
   802 fun read_const_exprs thy =
   803   let
   804     fun consts_of some_thyname =
   805       let
   806         val thy' = case some_thyname
   807          of SOME thyname => ThyInfo.the_theory thyname thy
   808           | NONE => thy;
   809         val cs = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
   810           ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
   811         fun belongs_here c =
   812           not (exists (fn thy'' => Sign.declared_const thy'' c) (Theory.parents_of thy'))
   813       in case some_thyname
   814        of NONE => cs
   815         | SOME thyname => filter belongs_here cs
   816       end;
   817     fun read_const_expr "*" = ([], consts_of NONE)
   818       | read_const_expr s = if String.isSuffix ".*" s
   819           then ([], consts_of (SOME (unsuffix ".*" s)))
   820           else ([Code.read_const thy s], []);
   821   in pairself flat o split_list o map read_const_expr end;
   822 
   823 fun code_depgr thy consts =
   824   let
   825     val (_, eqngr) = Code_Preproc.obtain thy consts [];
   826     val select = Graph.all_succs eqngr consts;
   827   in
   828     eqngr
   829     |> not (null consts) ? Graph.subgraph (member (op =) select) 
   830     |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
   831   end;
   832 
   833 fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
   834 
   835 fun code_deps thy consts =
   836   let
   837     val eqngr = code_depgr thy consts;
   838     val constss = Graph.strong_conn eqngr;
   839     val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
   840       Symtab.update (const, consts)) consts) constss;
   841     fun succs consts = consts
   842       |> maps (Graph.imm_succs eqngr)
   843       |> subtract (op =) consts
   844       |> map (the o Symtab.lookup mapping)
   845       |> distinct (op =);
   846     val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
   847     fun namify consts = map (Code.string_of_const thy) consts
   848       |> commas;
   849     val prgr = map (fn (consts, constss) =>
   850       { name = namify consts, ID = namify consts, dir = "", unfold = true,
   851         path = "", parents = map namify constss }) conn;
   852   in Present.display_graph prgr end;
   853 
   854 local
   855 
   856 structure P = OuterParse
   857 and K = OuterKeyword
   858 
   859 fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
   860 fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
   861 
   862 in
   863 
   864 val _ =
   865   OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
   866     (Scan.repeat P.term_group
   867       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
   868         o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
   869 
   870 val _ =
   871   OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
   872     (Scan.repeat P.term_group
   873       >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
   874         o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
   875 
   876 end;
   877 
   878 end; (*struct*)
   879 
   880 
   881 structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;