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