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