src/Tools/code/code_thingol.ML
author haftmann
Fri Apr 17 14:29:56 2009 +0200 (2009-04-17)
changeset 30947 dd551284a300
parent 30942 1e246776f876
child 30970 3fe2e418a071
permissions -rw-r--r--
re-engineering of evaluation conversions
haftmann@24219
     1
(*  Title:      Tools/code/code_thingol.ML
haftmann@24219
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@24219
     3
haftmann@24219
     4
Intermediate language ("Thin-gol") representing executable code.
haftmann@24918
     5
Representation and translation.
haftmann@24219
     6
*)
haftmann@24219
     7
haftmann@24219
     8
infix 8 `%%;
haftmann@24219
     9
infix 4 `$;
haftmann@24219
    10
infix 4 `$$;
haftmann@24219
    11
infixr 3 `|->;
haftmann@24219
    12
infixr 3 `|-->;
haftmann@24219
    13
haftmann@24219
    14
signature BASIC_CODE_THINGOL =
haftmann@24219
    15
sig
haftmann@24219
    16
  type vname = string;
haftmann@24219
    17
  datatype dict =
haftmann@24219
    18
      DictConst of string * dict list list
haftmann@24219
    19
    | DictVar of string list * (vname * (int * int));
haftmann@24219
    20
  datatype itype =
haftmann@24219
    21
      `%% of string * itype list
haftmann@24219
    22
    | ITyVar of vname;
haftmann@24591
    23
  type const = string * (dict list list * itype list (*types of arguments*))
haftmann@24219
    24
  datatype iterm =
haftmann@24591
    25
      IConst of const
haftmann@24219
    26
    | IVar of vname
haftmann@24219
    27
    | `$ of iterm * iterm
haftmann@24219
    28
    | `|-> of (vname * itype) * iterm
haftmann@24219
    29
    | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
haftmann@24219
    30
        (*((term, type), [(selector pattern, body term )]), primitive term)*)
haftmann@24219
    31
  val `$$ : iterm * iterm list -> iterm;
haftmann@24219
    32
  val `|--> : (vname * itype) list * iterm -> iterm;
haftmann@24219
    33
  type typscheme = (vname * sort) list * itype;
haftmann@24219
    34
end;
haftmann@24219
    35
haftmann@24219
    36
signature CODE_THINGOL =
haftmann@24219
    37
sig
haftmann@28663
    38
  include BASIC_CODE_THINGOL
haftmann@28663
    39
  val unfoldl: ('a -> ('a * 'b) option) -> 'a -> 'a * 'b list
haftmann@28663
    40
  val unfoldr: ('a -> ('b * 'a) option) -> 'a -> 'b list * 'a
haftmann@28663
    41
  val unfold_fun: itype -> itype list * itype
haftmann@28663
    42
  val unfold_app: iterm -> iterm * iterm list
haftmann@28663
    43
  val split_abs: iterm -> (((vname * iterm option) * itype) * iterm) option
haftmann@28663
    44
  val unfold_abs: iterm -> ((vname * iterm option) * itype) list * iterm
haftmann@28663
    45
  val split_let: iterm -> (((iterm * itype) * iterm) * iterm) option
haftmann@28663
    46
  val unfold_let: iterm -> ((iterm * itype) * iterm) list * iterm
haftmann@24219
    47
  val unfold_const_app: iterm ->
haftmann@28663
    48
    ((string * (dict list list * itype list)) * iterm list) option
haftmann@24219
    49
  val collapse_let: ((vname * itype) * iterm) * iterm
haftmann@28663
    50
    -> (iterm * itype) * (iterm * iterm) list
haftmann@28663
    51
  val eta_expand: int -> (string * (dict list list * itype list)) * iterm list -> iterm
haftmann@28663
    52
  val contains_dictvar: iterm -> bool
haftmann@28663
    53
  val locally_monomorphic: iterm -> bool
haftmann@28663
    54
  val fold_constnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
haftmann@28663
    55
  val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
haftmann@28663
    56
  val fold_unbound_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
haftmann@28663
    57
haftmann@28663
    58
  type naming
haftmann@28706
    59
  val empty_naming: naming
haftmann@28663
    60
  val lookup_class: naming -> class -> string option
haftmann@28663
    61
  val lookup_classrel: naming -> class * class -> string option
haftmann@28663
    62
  val lookup_tyco: naming -> string -> string option
haftmann@28663
    63
  val lookup_instance: naming -> class * string -> string option
haftmann@28663
    64
  val lookup_const: naming -> string -> string option
haftmann@24219
    65
haftmann@24918
    66
  datatype stmt =
haftmann@27024
    67
      NoStmt
haftmann@28663
    68
    | Fun of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
haftmann@28663
    69
    | Datatype of string * ((vname * sort) list * (string * itype list) list)
haftmann@28663
    70
    | Datatypecons of string * string
haftmann@28663
    71
    | Class of class * (vname * ((class * string) list * (string * itype) list))
haftmann@24219
    72
    | Classrel of class * class
haftmann@28663
    73
    | Classparam of string * class
haftmann@24219
    74
    | Classinst of (class * (string * (vname * sort) list))
haftmann@24219
    75
          * ((class * (string * (string * dict list list))) list
haftmann@28663
    76
        * ((string * const) * (thm * bool)) list)
haftmann@28663
    77
  type program = stmt Graph.T
haftmann@28663
    78
  val empty_funs: program -> string list
haftmann@28663
    79
  val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
haftmann@28663
    80
  val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
haftmann@28663
    81
  val is_cons: program -> string -> bool
haftmann@28663
    82
  val contr_classparam_typs: program -> string -> itype option list
haftmann@24219
    83
haftmann@28663
    84
  val consts_program: theory -> string list -> string list * (naming * program)
haftmann@28663
    85
  val cached_program: theory -> naming * program
haftmann@30947
    86
  val eval_conv: theory -> (sort -> sort)
haftmann@30947
    87
    -> (naming -> program -> (((string * sort) list * typscheme) * (string * itype) list) * iterm -> string list -> cterm -> thm)
haftmann@28663
    88
    -> cterm -> thm
haftmann@30947
    89
  val eval_term: theory -> (sort -> sort)
haftmann@30947
    90
    -> (naming -> program -> (((string * sort) list * typscheme) * (string * itype) list) * iterm -> string list -> term)
haftmann@30947
    91
    -> term -> term
haftmann@30947
    92
  val eval: theory -> (sort -> sort)
haftmann@30947
    93
    -> (naming -> program -> (((string * sort) list * typscheme) * (string * itype) list) * iterm -> string list -> 'a)
haftmann@28663
    94
    -> term -> 'a
haftmann@24219
    95
end;
haftmann@24219
    96
haftmann@28054
    97
structure Code_Thingol: CODE_THINGOL =
haftmann@24219
    98
struct
haftmann@24219
    99
haftmann@24219
   100
(** auxiliary **)
haftmann@24219
   101
haftmann@24219
   102
fun unfoldl dest x =
haftmann@24219
   103
  case dest x
haftmann@24219
   104
   of NONE => (x, [])
haftmann@24219
   105
    | SOME (x1, x2) =>
haftmann@24219
   106
        let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
haftmann@24219
   107
haftmann@24219
   108
fun unfoldr dest x =
haftmann@24219
   109
  case dest x
haftmann@24219
   110
   of NONE => ([], x)
haftmann@24219
   111
    | SOME (x1, x2) =>
haftmann@24219
   112
        let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
haftmann@24219
   113
haftmann@24219
   114
haftmann@29962
   115
(** language core - types, terms **)
haftmann@24219
   116
haftmann@24219
   117
type vname = string;
haftmann@24219
   118
haftmann@24219
   119
datatype dict =
haftmann@24219
   120
    DictConst of string * dict list list
haftmann@24219
   121
  | DictVar of string list * (vname * (int * int));
haftmann@24219
   122
haftmann@24219
   123
datatype itype =
haftmann@24219
   124
    `%% of string * itype list
haftmann@24219
   125
  | ITyVar of vname;
haftmann@24219
   126
haftmann@24591
   127
type const = string * (dict list list * itype list (*types of arguments*))
haftmann@24591
   128
haftmann@24219
   129
datatype iterm =
haftmann@24591
   130
    IConst of const
haftmann@24219
   131
  | IVar of vname
haftmann@24219
   132
  | `$ of iterm * iterm
haftmann@24219
   133
  | `|-> of (vname * itype) * iterm
haftmann@24219
   134
  | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
haftmann@24219
   135
    (*see also signature*)
haftmann@24219
   136
haftmann@24219
   137
val op `$$ = Library.foldl (op `$);
haftmann@24219
   138
val op `|--> = Library.foldr (op `|->);
haftmann@24219
   139
haftmann@24219
   140
val unfold_app = unfoldl
haftmann@24219
   141
  (fn op `$ t => SOME t
haftmann@24219
   142
    | _ => NONE);
haftmann@24219
   143
haftmann@24219
   144
val split_abs =
haftmann@24219
   145
  (fn (v, ty) `|-> (t as ICase (((IVar w, _), [(p, t')]), _)) =>
haftmann@24219
   146
        if v = w then SOME (((v, SOME p), ty), t') else SOME (((v, NONE), ty), t)
haftmann@24219
   147
    | (v, ty) `|-> t => SOME (((v, NONE), ty), t)
haftmann@24219
   148
    | _ => NONE);
haftmann@24219
   149
haftmann@24219
   150
val unfold_abs = unfoldr split_abs;
haftmann@24219
   151
haftmann@24219
   152
val split_let = 
haftmann@24219
   153
  (fn ICase (((td, ty), [(p, t)]), _) => SOME (((p, ty), td), t)
haftmann@24219
   154
    | _ => NONE);
haftmann@24219
   155
haftmann@24219
   156
val unfold_let = unfoldr split_let;
haftmann@24219
   157
haftmann@24219
   158
fun unfold_const_app t =
haftmann@24219
   159
 case unfold_app t
haftmann@24219
   160
  of (IConst c, ts) => SOME (c, ts)
haftmann@24219
   161
   | _ => NONE;
haftmann@24219
   162
haftmann@24219
   163
fun fold_aiterms f (t as IConst _) = f t
haftmann@24219
   164
  | fold_aiterms f (t as IVar _) = f t
haftmann@24219
   165
  | fold_aiterms f (t1 `$ t2) = fold_aiterms f t1 #> fold_aiterms f t2
haftmann@24219
   166
  | fold_aiterms f (t as _ `|-> t') = f t #> fold_aiterms f t'
haftmann@24219
   167
  | fold_aiterms f (ICase (_, t)) = fold_aiterms f t;
haftmann@24219
   168
haftmann@24219
   169
fun fold_constnames f =
haftmann@24219
   170
  let
haftmann@24219
   171
    fun add (IConst (c, _)) = f c
haftmann@24219
   172
      | add _ = I;
haftmann@24219
   173
  in fold_aiterms add end;
haftmann@24219
   174
haftmann@24219
   175
fun fold_varnames f =
haftmann@24219
   176
  let
haftmann@24219
   177
    fun add (IVar v) = f v
haftmann@24219
   178
      | add ((v, _) `|-> _) = f v
haftmann@24219
   179
      | add _ = I;
haftmann@24219
   180
  in fold_aiterms add end;
haftmann@24219
   181
haftmann@24219
   182
fun fold_unbound_varnames f =
haftmann@24219
   183
  let
haftmann@24219
   184
    fun add _ (IConst _) = I
haftmann@24219
   185
      | add vs (IVar v) = if not (member (op =) vs v) then f v else I
haftmann@24219
   186
      | add vs (t1 `$ t2) = add vs t1 #> add vs t2
haftmann@24219
   187
      | add vs ((v, _) `|-> t) = add (insert (op =) v vs) t
haftmann@24219
   188
      | add vs (ICase (_, t)) = add vs t;
haftmann@24219
   189
  in add [] end;
haftmann@24219
   190
haftmann@24219
   191
fun collapse_let (((v, ty), se), be as ICase (((IVar w, _), ds), _)) =
haftmann@24219
   192
      let
haftmann@24219
   193
        fun exists_v t = fold_unbound_varnames (fn w => fn b =>
haftmann@24219
   194
          b orelse v = w) t false;
haftmann@24219
   195
      in if v = w andalso forall (fn (t1, t2) =>
haftmann@24219
   196
        exists_v t1 orelse not (exists_v t2)) ds
haftmann@24219
   197
        then ((se, ty), ds)
haftmann@24219
   198
        else ((se, ty), [(IVar v, be)])
haftmann@24219
   199
      end
haftmann@24219
   200
  | collapse_let (((v, ty), se), be) =
haftmann@24219
   201
      ((se, ty), [(IVar v, be)])
haftmann@24219
   202
haftmann@27711
   203
fun eta_expand k (c as (_, (_, tys)), ts) =
haftmann@24219
   204
  let
haftmann@24219
   205
    val j = length ts;
haftmann@24219
   206
    val l = k - j;
haftmann@24219
   207
    val ctxt = (fold o fold_varnames) Name.declare ts Name.context;
haftmann@24219
   208
    val vs_tys = Name.names ctxt "a" ((curry Library.take l o curry Library.drop j) tys);
haftmann@24219
   209
  in vs_tys `|--> IConst c `$$ ts @ map (fn (v, _) => IVar v) vs_tys end;
haftmann@24219
   210
haftmann@24662
   211
fun contains_dictvar t =
haftmann@24662
   212
  let
haftmann@24662
   213
    fun contains (DictConst (_, dss)) = (fold o fold) contains dss
haftmann@24662
   214
      | contains (DictVar _) = K true;
haftmann@24662
   215
  in
haftmann@24662
   216
    fold_aiterms
haftmann@24662
   217
      (fn IConst (_, (dss, _)) => (fold o fold) contains dss | _ => I) t false
haftmann@24662
   218
  end;
haftmann@24662
   219
  
haftmann@25621
   220
fun locally_monomorphic (IConst _) = false
haftmann@25621
   221
  | locally_monomorphic (IVar _) = true
haftmann@25621
   222
  | locally_monomorphic (t `$ _) = locally_monomorphic t
haftmann@25621
   223
  | locally_monomorphic (_ `|-> t) = locally_monomorphic t
haftmann@25621
   224
  | locally_monomorphic (ICase ((_, ds), _)) = exists (locally_monomorphic o snd) ds;
haftmann@25621
   225
haftmann@25621
   226
haftmann@28688
   227
(** namings **)
haftmann@28663
   228
haftmann@28663
   229
(* policies *)
haftmann@28663
   230
haftmann@28663
   231
local
haftmann@28663
   232
  fun thyname_of thy f x = the (AList.lookup (op =) (f x) Markup.theory_nameN);
haftmann@28663
   233
  fun thyname_of_class thy =
haftmann@28663
   234
    thyname_of thy (ProofContext.query_class (ProofContext.init thy));
haftmann@28663
   235
  fun thyname_of_tyco thy =
haftmann@28663
   236
    thyname_of thy (Type.the_tags (Sign.tsig_of thy));
haftmann@28663
   237
  fun thyname_of_instance thy inst = case AxClass.arity_property thy inst Markup.theory_nameN
haftmann@28663
   238
   of [] => error ("no such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
haftmann@28663
   239
    | thyname :: _ => thyname;
haftmann@28706
   240
  fun thyname_of_const thy c = case AxClass.class_of_param thy c
haftmann@28706
   241
   of SOME class => thyname_of_class thy class
haftmann@28706
   242
    | NONE => (case Code.get_datatype_of_constr thy c
haftmann@28706
   243
       of SOME dtco => thyname_of_tyco thy dtco
haftmann@28706
   244
        | NONE => thyname_of thy (Consts.the_tags (Sign.consts_of thy)) c);
haftmann@28663
   245
  fun namify thy get_basename get_thyname name =
haftmann@28663
   246
    let
haftmann@28663
   247
      val prefix = get_thyname thy name;
haftmann@30648
   248
      val base = (Code_Name.purify_base o get_basename) name;
wenzelm@30364
   249
    in Long_Name.append prefix base end;
haftmann@28663
   250
in
haftmann@28663
   251
wenzelm@30364
   252
fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
haftmann@28663
   253
fun namify_classrel thy = namify thy (fn (class1, class2) => 
wenzelm@30364
   254
  Long_Name.base_name class2 ^ "_" ^ Long_Name.base_name class1) (fn thy => thyname_of_class thy o fst);
haftmann@28663
   255
  (*order fits nicely with composed projections*)
haftmann@28688
   256
fun namify_tyco thy "fun" = "Pure.fun"
wenzelm@30364
   257
  | namify_tyco thy tyco = namify thy Long_Name.base_name thyname_of_tyco tyco;
haftmann@28663
   258
fun namify_instance thy = namify thy (fn (class, tyco) => 
wenzelm@30364
   259
  Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
wenzelm@30364
   260
fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
haftmann@28663
   261
haftmann@28663
   262
end; (* local *)
haftmann@28663
   263
haftmann@28663
   264
haftmann@28688
   265
(* data *)
haftmann@28663
   266
haftmann@28663
   267
datatype naming = Naming of {
haftmann@28663
   268
  class: class Symtab.table * Name.context,
haftmann@30648
   269
  classrel: string Symreltab.table * Name.context,
haftmann@28663
   270
  tyco: string Symtab.table * Name.context,
haftmann@30648
   271
  instance: string Symreltab.table * Name.context,
haftmann@28663
   272
  const: string Symtab.table * Name.context
haftmann@28663
   273
}
haftmann@28663
   274
haftmann@28663
   275
fun dest_Naming (Naming naming) = naming;
haftmann@28663
   276
haftmann@28663
   277
val empty_naming = Naming {
haftmann@28663
   278
  class = (Symtab.empty, Name.context),
haftmann@30648
   279
  classrel = (Symreltab.empty, Name.context),
haftmann@28663
   280
  tyco = (Symtab.empty, Name.context),
haftmann@30648
   281
  instance = (Symreltab.empty, Name.context),
haftmann@28663
   282
  const = (Symtab.empty, Name.context)
haftmann@28663
   283
};
haftmann@28663
   284
haftmann@28663
   285
local
haftmann@28663
   286
  fun mk_naming (class, classrel, tyco, instance, const) =
haftmann@28663
   287
    Naming { class = class, classrel = classrel,
haftmann@28663
   288
      tyco = tyco, instance = instance, const = const };
haftmann@28663
   289
  fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
haftmann@28663
   290
    mk_naming (f (class, classrel, tyco, instance, const));
haftmann@28663
   291
in
haftmann@28663
   292
  fun map_class f = map_naming
haftmann@28663
   293
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   294
      (f class, classrel, tyco, inst, const));
haftmann@28663
   295
  fun map_classrel f = map_naming
haftmann@28663
   296
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   297
      (class, f classrel, tyco, inst, const));
haftmann@28663
   298
  fun map_tyco f = map_naming
haftmann@28663
   299
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   300
      (class, classrel, f tyco, inst, const));
haftmann@28663
   301
  fun map_instance f = map_naming
haftmann@28663
   302
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   303
      (class, classrel, tyco, f inst, const));
haftmann@28663
   304
  fun map_const f = map_naming
haftmann@28663
   305
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   306
      (class, classrel, tyco, inst, f const));
haftmann@28663
   307
end; (*local*)
haftmann@28663
   308
haftmann@28663
   309
fun add_variant update (thing, name) (tab, used) =
haftmann@28663
   310
  let
haftmann@28663
   311
    val (name', used') = yield_singleton Name.variants name used;
haftmann@28663
   312
    val tab' = update (thing, name') tab;
haftmann@28663
   313
  in (tab', used') end;
haftmann@28663
   314
haftmann@28663
   315
fun declare thy mapp lookup update namify thing =
haftmann@28663
   316
  mapp (add_variant update (thing, namify thy thing))
haftmann@28663
   317
  #> `(fn naming => the (lookup naming thing));
haftmann@28663
   318
haftmann@28688
   319
haftmann@28688
   320
(* lookup and declare *)
haftmann@28688
   321
haftmann@28688
   322
local
haftmann@28688
   323
haftmann@28688
   324
val suffix_class = "class";
haftmann@28688
   325
val suffix_classrel = "classrel"
haftmann@28688
   326
val suffix_tyco = "tyco";
haftmann@28688
   327
val suffix_instance = "inst";
haftmann@28688
   328
val suffix_const = "const";
haftmann@28688
   329
haftmann@28688
   330
fun add_suffix nsp NONE = NONE
wenzelm@30364
   331
  | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
haftmann@28688
   332
haftmann@28688
   333
in
haftmann@28688
   334
haftmann@28663
   335
val lookup_class = add_suffix suffix_class
haftmann@28663
   336
  oo Symtab.lookup o fst o #class o dest_Naming;
haftmann@28663
   337
val lookup_classrel = add_suffix suffix_classrel
haftmann@30648
   338
  oo Symreltab.lookup o fst o #classrel o dest_Naming;
haftmann@28663
   339
val lookup_tyco = add_suffix suffix_tyco
haftmann@28663
   340
  oo Symtab.lookup o fst o #tyco o dest_Naming;
haftmann@28663
   341
val lookup_instance = add_suffix suffix_instance
haftmann@30648
   342
  oo Symreltab.lookup o fst o #instance o dest_Naming;
haftmann@28663
   343
val lookup_const = add_suffix suffix_const
haftmann@28663
   344
  oo Symtab.lookup o fst o #const o dest_Naming;
haftmann@28663
   345
haftmann@28663
   346
fun declare_class thy = declare thy map_class
haftmann@28663
   347
  lookup_class Symtab.update_new namify_class;
haftmann@28663
   348
fun declare_classrel thy = declare thy map_classrel
haftmann@30648
   349
  lookup_classrel Symreltab.update_new namify_classrel;
haftmann@28663
   350
fun declare_tyco thy = declare thy map_tyco
haftmann@28663
   351
  lookup_tyco Symtab.update_new namify_tyco;
haftmann@28663
   352
fun declare_instance thy = declare thy map_instance
haftmann@30648
   353
  lookup_instance Symreltab.update_new namify_instance;
haftmann@28663
   354
fun declare_const thy = declare thy map_const
haftmann@28663
   355
  lookup_const Symtab.update_new namify_const;
haftmann@28663
   356
haftmann@28688
   357
val unfold_fun = unfoldr
haftmann@28688
   358
  (fn "Pure.fun.tyco" `%% [ty1, ty2] => SOME (ty1, ty2)
haftmann@28688
   359
    | _ => NONE); (*depends on suffix_tyco and namify_tyco!*)
haftmann@28688
   360
haftmann@28688
   361
end; (* local *)
haftmann@28688
   362
haftmann@24219
   363
haftmann@27103
   364
(** statements, abstract programs **)
haftmann@24219
   365
haftmann@24219
   366
type typscheme = (vname * sort) list * itype;
haftmann@24918
   367
datatype stmt =
haftmann@27024
   368
    NoStmt
haftmann@28663
   369
  | Fun of string * (typscheme * ((iterm list * iterm) * (thm * bool)) list)
haftmann@28663
   370
  | Datatype of string * ((vname * sort) list * (string * itype list) list)
haftmann@28663
   371
  | Datatypecons of string * string
haftmann@28663
   372
  | Class of class * (vname * ((class * string) list * (string * itype) list))
haftmann@24219
   373
  | Classrel of class * class
haftmann@28663
   374
  | Classparam of string * class
haftmann@24219
   375
  | Classinst of (class * (string * (vname * sort) list))
haftmann@24219
   376
        * ((class * (string * (string * dict list list))) list
haftmann@28350
   377
      * ((string * const) * (thm * bool)) list);
haftmann@24219
   378
haftmann@27103
   379
type program = stmt Graph.T;
haftmann@24219
   380
haftmann@27103
   381
fun empty_funs program =
haftmann@28663
   382
  Graph.fold (fn (name, (Fun (c, (_, [])), _)) => cons c
haftmann@27103
   383
               | _ => I) program [];
haftmann@24219
   384
haftmann@27711
   385
fun map_terms_bottom_up f (t as IConst _) = f t
haftmann@27711
   386
  | map_terms_bottom_up f (t as IVar _) = f t
haftmann@27711
   387
  | map_terms_bottom_up f (t1 `$ t2) = f
haftmann@27711
   388
      (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
haftmann@27711
   389
  | map_terms_bottom_up f ((v, ty) `|-> t) = f
haftmann@27711
   390
      ((v, ty) `|-> map_terms_bottom_up f t)
haftmann@27711
   391
  | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
haftmann@27711
   392
      (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
haftmann@27711
   393
        (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
haftmann@27711
   394
haftmann@27711
   395
fun map_terms_stmt f NoStmt = NoStmt
haftmann@28663
   396
  | map_terms_stmt f (Fun (c, (tysm, eqs))) = Fun (c, (tysm, (map o apfst)
haftmann@28663
   397
      (fn (ts, t) => (map f ts, f t)) eqs))
haftmann@27711
   398
  | map_terms_stmt f (stmt as Datatype _) = stmt
haftmann@27711
   399
  | map_terms_stmt f (stmt as Datatypecons _) = stmt
haftmann@27711
   400
  | map_terms_stmt f (stmt as Class _) = stmt
haftmann@27711
   401
  | map_terms_stmt f (stmt as Classrel _) = stmt
haftmann@27711
   402
  | map_terms_stmt f (stmt as Classparam _) = stmt
haftmann@27711
   403
  | map_terms_stmt f (Classinst (arity, (superarities, classparms))) =
haftmann@27711
   404
      Classinst (arity, (superarities, (map o apfst o apsnd) (fn const =>
haftmann@27711
   405
        case f (IConst const) of IConst const' => const') classparms));
haftmann@27711
   406
haftmann@27103
   407
fun is_cons program name = case Graph.get_node program name
haftmann@24219
   408
 of Datatypecons _ => true
haftmann@24219
   409
  | _ => false;
haftmann@24219
   410
haftmann@27103
   411
fun contr_classparam_typs program name = case Graph.get_node program name
haftmann@28663
   412
 of Classparam (_, class) => let
haftmann@28663
   413
        val Class (_, (_, (_, params))) = Graph.get_node program class;
haftmann@25621
   414
        val SOME ty = AList.lookup (op =) params name;
haftmann@25621
   415
        val (tys, res_ty) = unfold_fun ty;
haftmann@25621
   416
        fun no_tyvar (_ `%% tys) = forall no_tyvar tys
haftmann@25621
   417
          | no_tyvar (ITyVar _) = false;
haftmann@25621
   418
      in if no_tyvar res_ty
haftmann@25621
   419
        then map (fn ty => if no_tyvar ty then NONE else SOME ty) tys
haftmann@25621
   420
        else []
haftmann@25621
   421
      end
haftmann@25621
   422
  | _ => [];
haftmann@25621
   423
haftmann@24219
   424
haftmann@27103
   425
(** translation kernel **)
haftmann@24219
   426
haftmann@28724
   427
(* generic mechanisms *)
haftmann@28724
   428
haftmann@28663
   429
fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
haftmann@24219
   430
  let
haftmann@28706
   431
    fun add_dep name = case dep of NONE => I
haftmann@28706
   432
      | SOME dep => Graph.add_edge (dep, name);
haftmann@28706
   433
    val (name, naming') = case lookup naming thing
haftmann@28706
   434
     of SOME name => (name, naming)
haftmann@28706
   435
      | NONE => declare thing naming;
haftmann@28706
   436
  in case try (Graph.get_node program) name
haftmann@28706
   437
   of SOME stmt => program
haftmann@28663
   438
        |> add_dep name
haftmann@28706
   439
        |> pair naming'
haftmann@28663
   440
        |> pair dep
haftmann@28663
   441
        |> pair name
haftmann@28706
   442
    | NONE => program
haftmann@28706
   443
        |> Graph.default_node (name, NoStmt)
haftmann@28706
   444
        |> add_dep name
haftmann@28706
   445
        |> pair naming'
haftmann@28706
   446
        |> curry generate (SOME name)
haftmann@28706
   447
        ||> snd
haftmann@28706
   448
        |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
haftmann@28706
   449
        |> pair dep
haftmann@28706
   450
        |> pair name
haftmann@24219
   451
  end;
haftmann@24219
   452
haftmann@26972
   453
fun not_wellsorted thy thm ty sort e =
haftmann@26972
   454
  let
haftmann@26972
   455
    val err_class = Sorts.class_error (Syntax.pp_global thy) e;
haftmann@26972
   456
    val err_thm = case thm
haftmann@30023
   457
     of SOME thm => "\n(in code equation " ^ Display.string_of_thm thm ^ ")" | NONE => "";
haftmann@26972
   458
    val err_typ = "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort "
haftmann@26972
   459
      ^ Syntax.string_of_sort_global thy sort;
haftmann@26972
   460
  in error ("Wellsortedness error" ^ err_thm ^ ":\n" ^ err_typ ^ "\n" ^ err_class) end;
haftmann@26972
   461
haftmann@28724
   462
haftmann@28724
   463
(* translation *)
haftmann@28724
   464
haftmann@30932
   465
fun ensure_tyco thy algbr funcgr tyco =
haftmann@30932
   466
  let
haftmann@30932
   467
    val stmt_datatype =
haftmann@30932
   468
      let
haftmann@30932
   469
        val (vs, cos) = Code.get_datatype thy tyco;
haftmann@30932
   470
      in
haftmann@30932
   471
        fold_map (translate_tyvar_sort thy algbr funcgr) vs
haftmann@30932
   472
        ##>> fold_map (fn (c, tys) =>
haftmann@30932
   473
          ensure_const thy algbr funcgr c
haftmann@30932
   474
          ##>> fold_map (translate_typ thy algbr funcgr) tys) cos
haftmann@30932
   475
        #>> (fn info => Datatype (tyco, info))
haftmann@30932
   476
      end;
haftmann@30932
   477
  in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
haftmann@30932
   478
and ensure_const thy algbr funcgr c =
haftmann@30932
   479
  let
haftmann@30932
   480
    fun stmt_datatypecons tyco =
haftmann@30932
   481
      ensure_tyco thy algbr funcgr tyco
haftmann@30932
   482
      #>> (fn tyco => Datatypecons (c, tyco));
haftmann@30932
   483
    fun stmt_classparam class =
haftmann@30932
   484
      ensure_class thy algbr funcgr class
haftmann@30932
   485
      #>> (fn class => Classparam (c, class));
haftmann@30932
   486
    fun stmt_fun ((vs, ty), raw_thms) =
haftmann@30932
   487
      let
haftmann@30932
   488
        val thms = if null (Term.add_tfreesT ty []) orelse (null o fst o strip_type) ty
haftmann@30932
   489
          then raw_thms
haftmann@30932
   490
          else (map o apfst) (Code_Unit.expand_eta thy 1) raw_thms;
haftmann@30932
   491
      in
haftmann@30932
   492
        fold_map (translate_tyvar_sort thy algbr funcgr) vs
haftmann@30932
   493
        ##>> translate_typ thy algbr funcgr ty
haftmann@30932
   494
        ##>> fold_map (translate_eq thy algbr funcgr) thms
haftmann@30932
   495
        #>> (fn info => Fun (c, info))
haftmann@30932
   496
      end;
haftmann@30932
   497
    val stmt_const = case Code.get_datatype_of_constr thy c
haftmann@30932
   498
     of SOME tyco => stmt_datatypecons tyco
haftmann@30932
   499
      | NONE => (case AxClass.class_of_param thy c
haftmann@30932
   500
         of SOME class => stmt_classparam class
haftmann@30932
   501
          | NONE => stmt_fun (Code_Wellsorted.typ funcgr c, Code_Wellsorted.eqns funcgr c))
haftmann@30932
   502
  in ensure_stmt lookup_const (declare_const thy) stmt_const c end
haftmann@30932
   503
and ensure_class thy (algbr as (_, algebra)) funcgr class =
haftmann@24918
   504
  let
haftmann@28924
   505
    val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
wenzelm@24969
   506
    val cs = #params (AxClass.get_info thy class);
haftmann@24918
   507
    val stmt_class =
haftmann@24918
   508
      fold_map (fn superclass => ensure_class thy algbr funcgr superclass
haftmann@24918
   509
        ##>> ensure_classrel thy algbr funcgr (class, superclass)) superclasses
haftmann@24918
   510
      ##>> fold_map (fn (c, ty) => ensure_const thy algbr funcgr c
haftmann@28688
   511
        ##>> translate_typ thy algbr funcgr ty) cs
haftmann@28663
   512
      #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
haftmann@28663
   513
  in ensure_stmt lookup_class (declare_class thy) stmt_class class end
haftmann@24918
   514
and ensure_classrel thy algbr funcgr (subclass, superclass) =
haftmann@24918
   515
  let
haftmann@24918
   516
    val stmt_classrel =
haftmann@24918
   517
      ensure_class thy algbr funcgr subclass
haftmann@24918
   518
      ##>> ensure_class thy algbr funcgr superclass
haftmann@24918
   519
      #>> Classrel;
haftmann@28663
   520
  in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (subclass, superclass) end
haftmann@26972
   521
and ensure_inst thy (algbr as (_, algebra)) funcgr (class, tyco) =
haftmann@24918
   522
  let
haftmann@28924
   523
    val superclasses = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
wenzelm@24969
   524
    val classparams = these (try (#params o AxClass.get_info thy) class);
haftmann@24918
   525
    val vs = Name.names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
haftmann@24918
   526
    val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
haftmann@24918
   527
    val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
haftmann@24918
   528
      Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
haftmann@24918
   529
    val arity_typ = Type (tyco, map TFree vs);
haftmann@24918
   530
    val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
haftmann@28688
   531
    fun translate_superarity superclass =
haftmann@24918
   532
      ensure_class thy algbr funcgr superclass
haftmann@24918
   533
      ##>> ensure_classrel thy algbr funcgr (class, superclass)
haftmann@28688
   534
      ##>> translate_dicts thy algbr funcgr NONE (arity_typ, [superclass])
haftmann@24918
   535
      #>> (fn ((superclass, classrel), [DictConst (inst, dss)]) =>
haftmann@24918
   536
            (superclass, (classrel, (inst, dss))));
haftmann@28688
   537
    fun translate_classparam_inst (c, ty) =
haftmann@24918
   538
      let
haftmann@24918
   539
        val c_inst = Const (c, map_type_tfree (K arity_typ') ty);
haftmann@25597
   540
        val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy c_inst);
haftmann@24918
   541
        val c_ty = (apsnd Logic.unvarifyT o dest_Const o snd
haftmann@24918
   542
          o Logic.dest_equals o Thm.prop_of) thm;
haftmann@24918
   543
      in
haftmann@24918
   544
        ensure_const thy algbr funcgr c
haftmann@28688
   545
        ##>> translate_const thy algbr funcgr (SOME thm) c_ty
haftmann@28350
   546
        #>> (fn (c, IConst c_inst) => ((c, c_inst), (thm, true)))
haftmann@24918
   547
      end;
haftmann@24918
   548
    val stmt_inst =
haftmann@24918
   549
      ensure_class thy algbr funcgr class
haftmann@24918
   550
      ##>> ensure_tyco thy algbr funcgr tyco
haftmann@28688
   551
      ##>> fold_map (translate_tyvar_sort thy algbr funcgr) vs
haftmann@28688
   552
      ##>> fold_map translate_superarity superclasses
haftmann@28688
   553
      ##>> fold_map translate_classparam_inst classparams
haftmann@24918
   554
      #>> (fn ((((class, tyco), arity), superarities), classparams) =>
haftmann@24918
   555
             Classinst ((class, (tyco, arity)), (superarities, classparams)));
haftmann@28663
   556
  in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
haftmann@30932
   557
and translate_typ thy algbr funcgr (TFree (v, _)) =
haftmann@30932
   558
      pair (ITyVar (unprefix "'" v))
haftmann@30932
   559
  | translate_typ thy algbr funcgr (Type (tyco, tys)) =
haftmann@24918
   560
      ensure_tyco thy algbr funcgr tyco
haftmann@30932
   561
      ##>> fold_map (translate_typ thy algbr funcgr) tys
haftmann@30932
   562
      #>> (fn (tyco, tys) => tyco `%% tys)
haftmann@28688
   563
and translate_term thy algbr funcgr thm (Const (c, ty)) =
haftmann@28688
   564
      translate_app thy algbr funcgr thm ((c, ty), [])
haftmann@28688
   565
  | translate_term thy algbr funcgr thm (Free (v, _)) =
haftmann@24918
   566
      pair (IVar v)
haftmann@28688
   567
  | translate_term thy algbr funcgr thm (Abs (abs as (_, ty, _))) =
haftmann@24918
   568
      let
haftmann@24918
   569
        val (v, t) = Syntax.variant_abs abs;
haftmann@24918
   570
      in
haftmann@28688
   571
        translate_typ thy algbr funcgr ty
haftmann@28688
   572
        ##>> translate_term thy algbr funcgr thm t
haftmann@24918
   573
        #>> (fn (ty, t) => (v, ty) `|-> t)
haftmann@24918
   574
      end
haftmann@28688
   575
  | translate_term thy algbr funcgr thm (t as _ $ _) =
haftmann@24918
   576
      case strip_comb t
haftmann@24918
   577
       of (Const (c, ty), ts) =>
haftmann@28688
   578
            translate_app thy algbr funcgr thm ((c, ty), ts)
haftmann@24918
   579
        | (t', ts) =>
haftmann@28688
   580
            translate_term thy algbr funcgr thm t'
haftmann@28688
   581
            ##>> fold_map (translate_term thy algbr funcgr thm) ts
haftmann@24918
   582
            #>> (fn (t, ts) => t `$$ ts)
haftmann@30932
   583
and translate_eq thy algbr funcgr (thm, linear) =
haftmann@30932
   584
  let
haftmann@30932
   585
    val (args, rhs) = (apfst (snd o strip_comb) o Logic.dest_equals
haftmann@30932
   586
      o Logic.unvarify o prop_of) thm;
haftmann@30932
   587
  in
haftmann@30932
   588
    fold_map (translate_term thy algbr funcgr (SOME thm)) args
haftmann@30932
   589
    ##>> translate_term thy algbr funcgr (SOME thm) rhs
haftmann@30932
   590
    #>> rpair (thm, linear)
haftmann@30932
   591
  end
haftmann@28688
   592
and translate_const thy algbr funcgr thm (c, ty) =
haftmann@26972
   593
  let
haftmann@26972
   594
    val tys = Sign.const_typargs thy (c, ty);
haftmann@30202
   595
    val sorts = (map snd o fst o Code_Wellsorted.typ funcgr) c;
haftmann@26972
   596
    val tys_args = (fst o Term.strip_type) ty;
haftmann@26972
   597
  in
haftmann@26972
   598
    ensure_const thy algbr funcgr c
haftmann@28688
   599
    ##>> fold_map (translate_dicts thy algbr funcgr thm) (tys ~~ sorts)
haftmann@28688
   600
    ##>> fold_map (translate_typ thy algbr funcgr) tys_args
haftmann@26972
   601
    #>> (fn ((c, iss), tys) => IConst (c, (iss, tys)))
haftmann@26972
   602
  end
haftmann@29973
   603
and translate_app_const thy algbr funcgr thm (c_ty, ts) =
haftmann@28688
   604
  translate_const thy algbr funcgr thm c_ty
haftmann@28688
   605
  ##>> fold_map (translate_term thy algbr funcgr thm) ts
haftmann@24918
   606
  #>> (fn (t, ts) => t `$$ ts)
haftmann@29952
   607
and translate_case thy algbr funcgr thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
haftmann@24918
   608
  let
haftmann@29952
   609
    val (tys, _) = (chop num_args o fst o strip_type o snd) c_ty;
haftmann@29952
   610
    val t = nth ts t_pos;
haftmann@29952
   611
    val ty = nth tys t_pos;
haftmann@29952
   612
    val ts_clause = nth_drop t_pos ts;
haftmann@29952
   613
    fun mk_clause (co, num_co_args) t =
haftmann@24918
   614
      let
haftmann@29952
   615
        val (vs, body) = Term.strip_abs_eta num_co_args t;
haftmann@29952
   616
        val not_undefined = case body
haftmann@29952
   617
         of (Const (c, _)) => not (Code.is_undefined thy c)
haftmann@29952
   618
          | _ => true;
haftmann@29952
   619
        val pat = list_comb (Const (co, map snd vs ---> ty), map Free vs);
haftmann@29952
   620
      in (not_undefined, (pat, body)) end;
haftmann@29952
   621
    val clauses = if null case_pats then let val ([v_ty], body) =
haftmann@29952
   622
        Term.strip_abs_eta 1 (the_single ts_clause)
haftmann@29952
   623
      in [(true, (Free v_ty, body))] end
haftmann@29952
   624
      else map (uncurry mk_clause)
haftmann@29952
   625
        (AList.make (Code_Unit.no_args thy) case_pats ~~ ts_clause);
haftmann@29952
   626
    fun retermify ty (_, (IVar x, body)) =
haftmann@29952
   627
          (x, ty) `|-> body
haftmann@29952
   628
      | retermify _ (_, (pat, body)) =
haftmann@24918
   629
          let
haftmann@29952
   630
            val (IConst (_, (_, tys)), ts) = unfold_app pat;
haftmann@29952
   631
            val vs = map2 (fn IVar x => fn ty => (x, ty)) ts tys;
haftmann@29952
   632
          in vs `|--> body end;
haftmann@29952
   633
    fun mk_icase const t ty clauses =
haftmann@29952
   634
      let
haftmann@29952
   635
        val (ts1, ts2) = chop t_pos (map (retermify ty) clauses);
haftmann@29952
   636
      in
haftmann@29952
   637
        ICase (((t, ty), map_filter (fn (b, d) => if b then SOME d else NONE) clauses),
haftmann@29952
   638
          const `$$ (ts1 @ t :: ts2))
haftmann@29952
   639
      end;
haftmann@24918
   640
  in
haftmann@29952
   641
    translate_const thy algbr funcgr thm c_ty
haftmann@29952
   642
    ##>> translate_term thy algbr funcgr thm t
haftmann@29952
   643
    ##>> translate_typ thy algbr funcgr ty
haftmann@29952
   644
    ##>> fold_map (fn (b, (pat, body)) => translate_term thy algbr funcgr thm pat
haftmann@29952
   645
      ##>> translate_term thy algbr funcgr thm body
haftmann@29952
   646
      #>> pair b) clauses
haftmann@29952
   647
    #>> (fn (((const, t), ty), ds) => mk_icase const t ty ds)
haftmann@24918
   648
  end
haftmann@29973
   649
and translate_app_case thy algbr funcgr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
haftmann@29973
   650
  if length ts < num_args then
haftmann@29973
   651
    let
haftmann@29973
   652
      val k = length ts;
haftmann@29973
   653
      val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
haftmann@29973
   654
      val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
haftmann@29973
   655
      val vs = Name.names ctxt "a" tys;
haftmann@29973
   656
    in
haftmann@29973
   657
      fold_map (translate_typ thy algbr funcgr) tys
haftmann@29973
   658
      ##>> translate_case thy algbr funcgr thm case_scheme ((c, ty), ts @ map Free vs)
haftmann@29973
   659
      #>> (fn (tys, t) => map2 (fn (v, _) => pair v) vs tys `|--> t)
haftmann@29973
   660
    end
haftmann@29973
   661
  else if length ts > num_args then
haftmann@29973
   662
    translate_case thy algbr funcgr thm case_scheme ((c, ty), Library.take (num_args, ts))
haftmann@29973
   663
    ##>> fold_map (translate_term thy algbr funcgr thm) (Library.drop (num_args, ts))
haftmann@29973
   664
    #>> (fn (t, ts) => t `$$ ts)
haftmann@29973
   665
  else
haftmann@29973
   666
    translate_case thy algbr funcgr thm case_scheme ((c, ty), ts)
haftmann@29973
   667
and translate_app thy algbr funcgr thm (c_ty_ts as ((c, _), _)) =
haftmann@29973
   668
  case Code.get_case_scheme thy c
haftmann@30023
   669
   of SOME case_scheme => translate_app_case thy algbr funcgr thm case_scheme c_ty_ts
haftmann@30932
   670
    | NONE => translate_app_const thy algbr funcgr thm c_ty_ts
haftmann@30932
   671
and translate_tyvar_sort thy (algbr as (proj_sort, _)) funcgr (v, sort) =
haftmann@30932
   672
  fold_map (ensure_class thy algbr funcgr) (proj_sort sort)
haftmann@30932
   673
  #>> (fn sort => (unprefix "'" v, sort))
haftmann@30932
   674
and translate_dicts thy (algbr as (proj_sort, algebra)) funcgr thm (ty, sort) =
haftmann@30932
   675
  let
haftmann@30932
   676
    val pp = Syntax.pp_global thy;
haftmann@30932
   677
    datatype typarg =
haftmann@30932
   678
        Global of (class * string) * typarg list list
haftmann@30932
   679
      | Local of (class * class) list * (string * (int * sort));
haftmann@30932
   680
    fun class_relation (Global ((_, tyco), yss), _) class =
haftmann@30932
   681
          Global ((class, tyco), yss)
haftmann@30932
   682
      | class_relation (Local (classrels, v), subclass) superclass =
haftmann@30932
   683
          Local ((subclass, superclass) :: classrels, v);
haftmann@30932
   684
    fun type_constructor tyco yss class =
haftmann@30932
   685
      Global ((class, tyco), (map o map) fst yss);
haftmann@30932
   686
    fun type_variable (TFree (v, sort)) =
haftmann@30932
   687
      let
haftmann@30932
   688
        val sort' = proj_sort sort;
haftmann@30932
   689
      in map_index (fn (n, class) => (Local ([], (v, (n, sort'))), class)) sort' end;
haftmann@30932
   690
    val typargs = Sorts.of_sort_derivation pp algebra
haftmann@30932
   691
      {class_relation = class_relation, type_constructor = type_constructor,
haftmann@30932
   692
       type_variable = type_variable} (ty, proj_sort sort)
haftmann@30932
   693
      handle Sorts.CLASS_ERROR e => not_wellsorted thy thm ty sort e;
haftmann@30932
   694
    fun mk_dict (Global (inst, yss)) =
haftmann@30932
   695
          ensure_inst thy algbr funcgr inst
haftmann@30932
   696
          ##>> (fold_map o fold_map) mk_dict yss
haftmann@30932
   697
          #>> (fn (inst, dss) => DictConst (inst, dss))
haftmann@30932
   698
      | mk_dict (Local (classrels, (v, (k, sort)))) =
haftmann@30932
   699
          fold_map (ensure_classrel thy algbr funcgr) classrels
haftmann@30932
   700
          #>> (fn classrels => DictVar (classrels, (unprefix "'" v, (k, length sort))))
haftmann@30932
   701
  in fold_map mk_dict typargs end;
haftmann@24918
   702
haftmann@25969
   703
haftmann@27103
   704
(* store *)
haftmann@27103
   705
haftmann@27103
   706
structure Program = CodeDataFun
haftmann@27103
   707
(
haftmann@28663
   708
  type T = naming * program;
haftmann@28663
   709
  val empty = (empty_naming, Graph.empty);
haftmann@28706
   710
  fun purge thy cs (naming, program) =
haftmann@27609
   711
    let
haftmann@28706
   712
      val names_delete = cs
haftmann@28706
   713
        |> map_filter (lookup_const naming)
haftmann@28706
   714
        |> filter (can (Graph.get_node program))
haftmann@28706
   715
        |> Graph.all_preds program;
haftmann@28706
   716
      val program' = Graph.del_nodes names_delete program;
haftmann@28706
   717
    in (naming, program') end;
haftmann@27103
   718
);
haftmann@27103
   719
haftmann@27103
   720
val cached_program = Program.get;
haftmann@25969
   721
haftmann@28924
   722
fun invoke_generation thy (algebra, funcgr) f name =
haftmann@28663
   723
  Program.change_yield thy (fn naming_program => (NONE, naming_program)
haftmann@28924
   724
    |> f thy algebra funcgr name
haftmann@28663
   725
    |-> (fn name => fn (_, naming_program) => (name, naming_program)));
haftmann@27103
   726
haftmann@27103
   727
haftmann@27103
   728
(* program generation *)
haftmann@27103
   729
haftmann@27103
   730
fun consts_program thy cs =
haftmann@27103
   731
  let
haftmann@28663
   732
    fun project_consts cs (naming, program) =
haftmann@27103
   733
      let
haftmann@27103
   734
        val cs_all = Graph.all_succs program cs;
haftmann@28663
   735
      in (cs, (naming, Graph.subgraph (member (op =) cs_all) program)) end;
haftmann@27103
   736
    fun generate_consts thy algebra funcgr =
haftmann@27103
   737
      fold_map (ensure_const thy algebra funcgr);
haftmann@27103
   738
  in
haftmann@30942
   739
    invoke_generation thy (Code_Wellsorted.obtain thy cs []) generate_consts cs
haftmann@27103
   740
    |-> project_consts
haftmann@27103
   741
  end;
haftmann@27103
   742
haftmann@27103
   743
haftmann@27103
   744
(* value evaluation *)
haftmann@25969
   745
haftmann@30947
   746
fun ensure_value thy algbr funcgr (fs, t) =
haftmann@24918
   747
  let
haftmann@24918
   748
    val ty = fastype_of t;
haftmann@24918
   749
    val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
haftmann@24918
   750
      o dest_TFree))) t [];
haftmann@24918
   751
    val stmt_value =
haftmann@28688
   752
      fold_map (translate_tyvar_sort thy algbr funcgr) vs
haftmann@28688
   753
      ##>> translate_typ thy algbr funcgr ty
haftmann@28688
   754
      ##>> translate_term thy algbr funcgr NONE t
haftmann@28663
   755
      #>> (fn ((vs, ty), t) => Fun
haftmann@28663
   756
        (Term.dummy_patternN, ((vs, ty), [(([], t), (Drule.dummy_thm, true))])));
haftmann@30947
   757
    fun term_value fs (dep, (naming, program1)) =
haftmann@25969
   758
      let
haftmann@30947
   759
        val Fun (_, (vs_ty, [(([], t), _)])) =
haftmann@28663
   760
          Graph.get_node program1 Term.dummy_patternN;
haftmann@28663
   761
        val deps = Graph.imm_succs program1 Term.dummy_patternN;
haftmann@28663
   762
        val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
haftmann@27103
   763
        val deps_all = Graph.all_succs program2 deps;
haftmann@27103
   764
        val program3 = Graph.subgraph (member (op =) deps_all) program2;
haftmann@30947
   765
      in (((naming, program3), (((vs_ty, fs), t), deps)), (dep, (naming, program2))) end;
haftmann@26011
   766
  in
haftmann@28663
   767
    ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
haftmann@26011
   768
    #> snd
haftmann@30947
   769
    #> fold_map (fn (v, ty) => translate_typ thy algbr funcgr ty
haftmann@30947
   770
         #-> (fn ty' => pair (v, ty'))) fs
haftmann@30947
   771
    #-> (fn fs' => term_value fs')
haftmann@26011
   772
  end;
haftmann@24219
   773
haftmann@30947
   774
fun base_evaluator thy evaluator algebra funcgr vs t =
haftmann@30942
   775
  let
haftmann@30947
   776
    val fs = Term.add_frees t [];
haftmann@30947
   777
    val (((naming, program), ((((vs', ty'), fs'), t'), deps)), _) =
haftmann@30947
   778
      invoke_generation thy (algebra, funcgr) ensure_value (fs, t);
haftmann@30947
   779
    val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
haftmann@30947
   780
  in evaluator naming program (((vs'', (vs', ty')), fs'), t') deps end;
haftmann@30942
   781
haftmann@30947
   782
fun eval_conv thy prep_sort = Code_Wellsorted.eval_conv thy prep_sort o base_evaluator thy;
haftmann@30947
   783
fun eval_term thy prep_sort = Code_Wellsorted.eval_term thy prep_sort o base_evaluator thy;
haftmann@30947
   784
fun eval thy prep_sort = Code_Wellsorted.eval thy prep_sort o base_evaluator thy;
haftmann@30942
   785
haftmann@30942
   786
haftmann@30942
   787
(** diagnostic commands **)
haftmann@30942
   788
haftmann@30942
   789
fun code_depgr thy consts =
haftmann@30942
   790
  let
haftmann@30942
   791
    val (_, eqngr) = Code_Wellsorted.obtain thy consts [];
haftmann@30942
   792
    val select = Graph.all_succs eqngr consts;
haftmann@30942
   793
  in
haftmann@30942
   794
    eqngr
haftmann@30942
   795
    |> not (null consts) ? Graph.subgraph (member (op =) select) 
haftmann@30942
   796
    |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
haftmann@30942
   797
  end;
haftmann@30942
   798
haftmann@30942
   799
fun code_thms thy = Pretty.writeln o Code_Wellsorted.pretty thy o code_depgr thy;
haftmann@30942
   800
haftmann@30942
   801
fun code_deps thy consts =
haftmann@27103
   802
  let
haftmann@30942
   803
    val eqngr = code_depgr thy consts;
haftmann@30942
   804
    val constss = Graph.strong_conn eqngr;
haftmann@30942
   805
    val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
haftmann@30942
   806
      Symtab.update (const, consts)) consts) constss;
haftmann@30942
   807
    fun succs consts = consts
haftmann@30942
   808
      |> maps (Graph.imm_succs eqngr)
haftmann@30942
   809
      |> subtract (op =) consts
haftmann@30942
   810
      |> map (the o Symtab.lookup mapping)
haftmann@30942
   811
      |> distinct (op =);
haftmann@30942
   812
    val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
haftmann@30942
   813
    fun namify consts = map (Code_Unit.string_of_const thy) consts
haftmann@30942
   814
      |> commas;
haftmann@30942
   815
    val prgr = map (fn (consts, constss) =>
haftmann@30942
   816
      { name = namify consts, ID = namify consts, dir = "", unfold = true,
haftmann@30942
   817
        path = "", parents = map namify constss }) conn;
haftmann@30942
   818
  in Present.display_graph prgr end;
haftmann@30942
   819
haftmann@30942
   820
local
haftmann@27103
   821
haftmann@30942
   822
structure P = OuterParse
haftmann@30942
   823
and K = OuterKeyword
haftmann@30942
   824
haftmann@30942
   825
fun code_thms_cmd thy = code_thms thy o op @ o Code_Name.read_const_exprs thy;
haftmann@30942
   826
fun code_deps_cmd thy = code_deps thy o op @ o Code_Name.read_const_exprs thy;
haftmann@30942
   827
haftmann@30942
   828
in
haftmann@30942
   829
haftmann@30942
   830
val _ =
haftmann@30942
   831
  OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
haftmann@30942
   832
    (Scan.repeat P.term_group
haftmann@30942
   833
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
   834
        o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
   835
haftmann@30942
   836
val _ =
haftmann@30942
   837
  OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
haftmann@30942
   838
    (Scan.repeat P.term_group
haftmann@30942
   839
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
   840
        o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
   841
haftmann@30942
   842
end;
haftmann@27103
   843
haftmann@24219
   844
end; (*struct*)
haftmann@24219
   845
haftmann@24219
   846
haftmann@28054
   847
structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;