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