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