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