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