src/Tools/code/code_thingol.ML
author haftmann
Wed May 06 19:09:14 2009 +0200 (2009-05-06)
changeset 31054 841c9f67f9e7
parent 31049 396d4d6a1594
child 31063 88aaab83b6fc
permissions -rw-r--r--
explicit type arguments in constants
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@30947
    88
    -> (naming -> program -> (((string * sort) list * typscheme) * (string * itype) list) * iterm -> string list -> cterm -> thm)
haftmann@28663
    89
    -> cterm -> thm
haftmann@30970
    90
  val eval: theory -> (sort -> sort) -> ((term -> term) -> 'a -> 'a)
haftmann@30947
    91
    -> (naming -> program -> (((string * sort) list * typscheme) * (string * itype) list) * 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@29962
   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@30648
   275
  classrel: string Symreltab.table * Name.context,
haftmann@28663
   276
  tyco: string Symtab.table * Name.context,
haftmann@30648
   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@30648
   285
  classrel = (Symreltab.empty, Name.context),
haftmann@28663
   286
  tyco = (Symtab.empty, Name.context),
haftmann@30648
   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@30648
   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@30648
   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@30648
   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@30648
   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@30023
   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@30932
   501
          else (map o apfst) (Code_Unit.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@30932
   512
          | NONE => stmt_fun (Code_Wellsorted.typ funcgr c, Code_Wellsorted.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@30932
   594
and translate_eq thy algbr funcgr (thm, linear) =
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@30932
   601
    #>> rpair (thm, linear)
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@30202
   606
    val sorts = (map snd o fst o Code_Wellsorted.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@29973
   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@29952
   619
and translate_case thy algbr funcgr thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
haftmann@24918
   620
  let
haftmann@29952
   621
    val (tys, _) = (chop num_args o fst o strip_type o snd) c_ty;
haftmann@29952
   622
    val t = nth ts t_pos;
haftmann@29952
   623
    val ty = nth tys t_pos;
haftmann@29952
   624
    val ts_clause = nth_drop t_pos ts;
haftmann@29952
   625
    fun mk_clause (co, num_co_args) t =
haftmann@24918
   626
      let
haftmann@29952
   627
        val (vs, body) = Term.strip_abs_eta num_co_args t;
haftmann@29952
   628
        val not_undefined = case body
haftmann@29952
   629
         of (Const (c, _)) => not (Code.is_undefined thy c)
haftmann@29952
   630
          | _ => true;
haftmann@29952
   631
        val pat = list_comb (Const (co, map snd vs ---> ty), map Free vs);
haftmann@29952
   632
      in (not_undefined, (pat, body)) end;
haftmann@29952
   633
    val clauses = if null case_pats then let val ([v_ty], body) =
haftmann@29952
   634
        Term.strip_abs_eta 1 (the_single ts_clause)
haftmann@29952
   635
      in [(true, (Free v_ty, body))] end
haftmann@29952
   636
      else map (uncurry mk_clause)
haftmann@29952
   637
        (AList.make (Code_Unit.no_args thy) case_pats ~~ ts_clause);
haftmann@29952
   638
    fun retermify ty (_, (IVar x, body)) =
haftmann@29952
   639
          (x, ty) `|-> body
haftmann@29952
   640
      | retermify _ (_, (pat, body)) =
haftmann@24918
   641
          let
haftmann@29952
   642
            val (IConst (_, (_, tys)), ts) = unfold_app pat;
haftmann@29952
   643
            val vs = map2 (fn IVar x => fn ty => (x, ty)) ts tys;
haftmann@29952
   644
          in vs `|--> body end;
haftmann@29952
   645
    fun mk_icase const t ty clauses =
haftmann@29952
   646
      let
haftmann@29952
   647
        val (ts1, ts2) = chop t_pos (map (retermify ty) clauses);
haftmann@29952
   648
      in
haftmann@29952
   649
        ICase (((t, ty), map_filter (fn (b, d) => if b then SOME d else NONE) clauses),
haftmann@29952
   650
          const `$$ (ts1 @ t :: ts2))
haftmann@29952
   651
      end;
haftmann@24918
   652
  in
haftmann@29952
   653
    translate_const thy algbr funcgr thm c_ty
haftmann@29952
   654
    ##>> translate_term thy algbr funcgr thm t
haftmann@29952
   655
    ##>> translate_typ thy algbr funcgr ty
haftmann@29952
   656
    ##>> fold_map (fn (b, (pat, body)) => translate_term thy algbr funcgr thm pat
haftmann@29952
   657
      ##>> translate_term thy algbr funcgr thm body
haftmann@29952
   658
      #>> pair b) clauses
haftmann@29952
   659
    #>> (fn (((const, t), ty), ds) => mk_icase const t ty ds)
haftmann@24918
   660
  end
haftmann@29973
   661
and translate_app_case thy algbr funcgr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
haftmann@29973
   662
  if length ts < num_args then
haftmann@29973
   663
    let
haftmann@29973
   664
      val k = length ts;
haftmann@29973
   665
      val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
haftmann@29973
   666
      val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
haftmann@29973
   667
      val vs = Name.names ctxt "a" tys;
haftmann@29973
   668
    in
haftmann@29973
   669
      fold_map (translate_typ thy algbr funcgr) tys
haftmann@29973
   670
      ##>> translate_case thy algbr funcgr thm case_scheme ((c, ty), ts @ map Free vs)
haftmann@29973
   671
      #>> (fn (tys, t) => map2 (fn (v, _) => pair v) vs tys `|--> t)
haftmann@29973
   672
    end
haftmann@29973
   673
  else if length ts > num_args then
haftmann@29973
   674
    translate_case thy algbr funcgr thm case_scheme ((c, ty), Library.take (num_args, ts))
haftmann@29973
   675
    ##>> fold_map (translate_term thy algbr funcgr thm) (Library.drop (num_args, ts))
haftmann@29973
   676
    #>> (fn (t, ts) => t `$$ ts)
haftmann@29973
   677
  else
haftmann@29973
   678
    translate_case thy algbr funcgr thm case_scheme ((c, ty), ts)
haftmann@29973
   679
and translate_app thy algbr funcgr thm (c_ty_ts as ((c, _), _)) =
haftmann@29973
   680
  case Code.get_case_scheme thy c
haftmann@30023
   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@25969
   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@30942
   751
    invoke_generation thy (Code_Wellsorted.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@30947
   758
fun ensure_value thy algbr funcgr (fs, 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@30947
   769
    fun term_value fs (dep, (naming, program1)) =
haftmann@25969
   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@30947
   777
      in (((naming, program3), (((vs_ty, fs), t), deps)), (dep, (naming, program2))) end;
haftmann@26011
   778
  in
haftmann@28663
   779
    ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
haftmann@26011
   780
    #> snd
haftmann@30947
   781
    #> fold_map (fn (v, ty) => translate_typ thy algbr funcgr ty
haftmann@30947
   782
         #-> (fn ty' => pair (v, ty'))) fs
haftmann@30947
   783
    #-> (fn fs' => term_value fs')
haftmann@26011
   784
  end;
haftmann@24219
   785
haftmann@30947
   786
fun base_evaluator thy evaluator algebra funcgr vs t =
haftmann@30942
   787
  let
haftmann@30947
   788
    val fs = Term.add_frees t [];
haftmann@30947
   789
    val (((naming, program), ((((vs', ty'), fs'), t'), deps)), _) =
haftmann@30947
   790
      invoke_generation thy (algebra, funcgr) ensure_value (fs, t);
haftmann@30947
   791
    val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
haftmann@30947
   792
  in evaluator naming program (((vs'', (vs', ty')), fs'), t') deps end;
haftmann@30942
   793
haftmann@30947
   794
fun eval_conv thy prep_sort = Code_Wellsorted.eval_conv thy prep_sort o base_evaluator thy;
haftmann@30970
   795
fun eval thy prep_sort postproc = Code_Wellsorted.eval thy prep_sort postproc o base_evaluator thy;
haftmann@30942
   796
haftmann@30942
   797
haftmann@30942
   798
(** diagnostic commands **)
haftmann@30942
   799
haftmann@31036
   800
fun read_const_exprs thy =
haftmann@31036
   801
  let
haftmann@31036
   802
    fun consts_of some_thyname =
haftmann@31036
   803
      let
haftmann@31036
   804
        val thy' = case some_thyname
haftmann@31036
   805
         of SOME thyname => ThyInfo.the_theory thyname thy
haftmann@31036
   806
          | NONE => thy;
haftmann@31036
   807
        val cs = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
haftmann@31036
   808
          ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
haftmann@31036
   809
        fun belongs_here c =
haftmann@31036
   810
          not (exists (fn thy'' => Sign.declared_const thy'' c) (Theory.parents_of thy'))
haftmann@31036
   811
      in case some_thyname
haftmann@31036
   812
       of NONE => cs
haftmann@31036
   813
        | SOME thyname => filter belongs_here cs
haftmann@31036
   814
      end;
haftmann@31036
   815
    fun read_const_expr "*" = ([], consts_of NONE)
haftmann@31036
   816
      | read_const_expr s = if String.isSuffix ".*" s
haftmann@31036
   817
          then ([], consts_of (SOME (unsuffix ".*" s)))
haftmann@31036
   818
          else ([Code_Unit.read_const thy s], []);
haftmann@31036
   819
  in pairself flat o split_list o map read_const_expr end;
haftmann@31036
   820
haftmann@30942
   821
fun code_depgr thy consts =
haftmann@30942
   822
  let
haftmann@30942
   823
    val (_, eqngr) = Code_Wellsorted.obtain thy consts [];
haftmann@30942
   824
    val select = Graph.all_succs eqngr consts;
haftmann@30942
   825
  in
haftmann@30942
   826
    eqngr
haftmann@30942
   827
    |> not (null consts) ? Graph.subgraph (member (op =) select) 
haftmann@30942
   828
    |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
haftmann@30942
   829
  end;
haftmann@30942
   830
haftmann@30942
   831
fun code_thms thy = Pretty.writeln o Code_Wellsorted.pretty thy o code_depgr thy;
haftmann@30942
   832
haftmann@30942
   833
fun code_deps thy consts =
haftmann@27103
   834
  let
haftmann@30942
   835
    val eqngr = code_depgr thy consts;
haftmann@30942
   836
    val constss = Graph.strong_conn eqngr;
haftmann@30942
   837
    val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
haftmann@30942
   838
      Symtab.update (const, consts)) consts) constss;
haftmann@30942
   839
    fun succs consts = consts
haftmann@30942
   840
      |> maps (Graph.imm_succs eqngr)
haftmann@30942
   841
      |> subtract (op =) consts
haftmann@30942
   842
      |> map (the o Symtab.lookup mapping)
haftmann@30942
   843
      |> distinct (op =);
haftmann@30942
   844
    val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
haftmann@30942
   845
    fun namify consts = map (Code_Unit.string_of_const thy) consts
haftmann@30942
   846
      |> commas;
haftmann@30942
   847
    val prgr = map (fn (consts, constss) =>
haftmann@30942
   848
      { name = namify consts, ID = namify consts, dir = "", unfold = true,
haftmann@30942
   849
        path = "", parents = map namify constss }) conn;
haftmann@30942
   850
  in Present.display_graph prgr end;
haftmann@30942
   851
haftmann@30942
   852
local
haftmann@27103
   853
haftmann@30942
   854
structure P = OuterParse
haftmann@30942
   855
and K = OuterKeyword
haftmann@30942
   856
haftmann@31036
   857
fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
haftmann@31036
   858
fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
haftmann@30942
   859
haftmann@30942
   860
in
haftmann@30942
   861
haftmann@30942
   862
val _ =
haftmann@30942
   863
  OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
haftmann@30942
   864
    (Scan.repeat P.term_group
haftmann@30942
   865
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
   866
        o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
   867
haftmann@30942
   868
val _ =
haftmann@30942
   869
  OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
haftmann@30942
   870
    (Scan.repeat P.term_group
haftmann@30942
   871
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
   872
        o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
   873
haftmann@30942
   874
end;
haftmann@27103
   875
haftmann@24219
   876
end; (*struct*)
haftmann@24219
   877
haftmann@24219
   878
haftmann@28054
   879
structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;