src/Tools/Code/code_thingol.ML
author haftmann
Tue Jun 30 18:23:50 2009 +0200 (2009-06-30)
changeset 31890 e943b039f0ac
parent 31889 fb2c8a687529
child 31892 a2139b503981
permissions -rw-r--r--
an intermediate step towards a refined translation of cases
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@31890
   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@29952
   634
    val (tys, _) = (chop num_args o fst o strip_type o snd) c_ty;
haftmann@29952
   635
    val t = nth ts t_pos;
haftmann@29952
   636
    val ty = nth tys t_pos;
haftmann@29952
   637
    val ts_clause = nth_drop t_pos ts;
haftmann@31890
   638
    val undefineds = Code.undefineds thy;
haftmann@29952
   639
    fun mk_clause (co, num_co_args) t =
haftmann@24918
   640
      let
haftmann@29952
   641
        val (vs, body) = Term.strip_abs_eta num_co_args t;
haftmann@29952
   642
        val not_undefined = case body
haftmann@31890
   643
         of (Const (c, _)) => not (member (op =) undefineds c)
haftmann@29952
   644
          | _ => true;
haftmann@29952
   645
        val pat = list_comb (Const (co, map snd vs ---> ty), map Free vs);
haftmann@29952
   646
      in (not_undefined, (pat, body)) end;
haftmann@29952
   647
    val clauses = if null case_pats then let val ([v_ty], body) =
haftmann@29952
   648
        Term.strip_abs_eta 1 (the_single ts_clause)
haftmann@29952
   649
      in [(true, (Free v_ty, body))] end
haftmann@29952
   650
      else map (uncurry mk_clause)
haftmann@31156
   651
        (AList.make (Code.no_args thy) case_pats ~~ ts_clause);
haftmann@31889
   652
    fun retermify ty (_, (IVar v, body)) =
haftmann@31889
   653
          (v, ty) `|=> body
haftmann@29952
   654
      | retermify _ (_, (pat, body)) =
haftmann@24918
   655
          let
haftmann@29952
   656
            val (IConst (_, (_, tys)), ts) = unfold_app pat;
haftmann@31889
   657
            val vs = map2 (fn IVar v => fn ty => (v, ty)) ts tys;
haftmann@31724
   658
          in vs `|==> body end;
haftmann@29952
   659
    fun mk_icase const t ty clauses =
haftmann@29952
   660
      let
haftmann@29952
   661
        val (ts1, ts2) = chop t_pos (map (retermify ty) clauses);
haftmann@29952
   662
      in
haftmann@29952
   663
        ICase (((t, ty), map_filter (fn (b, d) => if b then SOME d else NONE) clauses),
haftmann@29952
   664
          const `$$ (ts1 @ t :: ts2))
haftmann@29952
   665
      end;
haftmann@24918
   666
  in
haftmann@29952
   667
    translate_const thy algbr funcgr thm c_ty
haftmann@29952
   668
    ##>> translate_term thy algbr funcgr thm t
haftmann@29952
   669
    ##>> translate_typ thy algbr funcgr ty
haftmann@29952
   670
    ##>> fold_map (fn (b, (pat, body)) => translate_term thy algbr funcgr thm pat
haftmann@29952
   671
      ##>> translate_term thy algbr funcgr thm body
haftmann@29952
   672
      #>> pair b) clauses
haftmann@29952
   673
    #>> (fn (((const, t), ty), ds) => mk_icase const t ty ds)
haftmann@24918
   674
  end
haftmann@31889
   675
haftmann@31890
   676
(*and translate_case' thy algbr funcgr thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
haftmann@31889
   677
  let
haftmann@31890
   678
    fun casify naming ts tys =
haftmann@31889
   679
      let
haftmann@31889
   680
        val t = nth ts t_pos;
haftmann@31889
   681
        val ty = nth tys t_pos;
haftmann@31889
   682
        val ts_clause = nth_drop t_pos ts;
haftmann@31890
   683
        val tyss_clause = map (fst o unfold_fun) (nth_drop t_pos tys);
haftmann@31890
   684
haftmann@31890
   685
        val undefineds = map_filter (lookup_const naming) (*Code.undefineds thy*) [];
haftmann@31889
   686
haftmann@31890
   687
        fun mk_clause co (tys, t) =
haftmann@31889
   688
          let
haftmann@31890
   689
            val (vs, t') = unfold_abs_eta tys t;
haftmann@31890
   690
            val is_undefined = case t
haftmann@31890
   691
             of Const (c, _) => member (op =) undefineds c
haftmann@31890
   692
              | _ => false;
haftmann@31890
   693
          in if is_undefined then NONE else (_, t) end;
haftmann@31890
   694
haftmann@31889
   695
            val not_undefined = case body
haftmann@31889
   696
             of (Const (c, _)) => not (Code.is_undefined thy c)
haftmann@31889
   697
              | _ => true;
haftmann@31889
   698
            val pat = list_comb (Const (co, map snd vs ---> ty), map Free vs);
haftmann@31889
   699
          in (not_undefined, (pat, body)) end;
haftmann@31889
   700
haftmann@31890
   701
        val clauses = if null case_pats then let val ([(v, _)], t) =
haftmann@31890
   702
            unfold_abs_eta (the_single tyss_clause) (the_single ts_clause) 
haftmann@31890
   703
          in [(IVar v, t)] end
haftmann@31890
   704
          else map2 mk_clause case_pats (tyss_clause ~~ ts_clause);
haftmann@31889
   705
haftmann@31889
   706
      in ((t, ty), map_filter (fn (b, d) => if b then SOME d else NONE) clauses) end;
haftmann@31889
   707
  in
haftmann@31889
   708
    translate_const thy algbr funcgr thm c_ty
haftmann@31889
   709
    ##>> fold_map (translate_term thy algbr funcgr thm) ts
haftmann@31890
   710
    #-> (fn (t as IConst (c, (_, tys)), ts) =>
haftmann@31890
   711
      `(fn (naming, _) => pair (ICase (casify naming ts tys, t `$$ ts))))
haftmann@31889
   712
  end*)
haftmann@31889
   713
haftmann@29973
   714
and translate_app_case thy algbr funcgr thm (case_scheme as (num_args, _)) ((c, ty), ts) =
haftmann@29973
   715
  if length ts < num_args then
haftmann@29973
   716
    let
haftmann@29973
   717
      val k = length ts;
haftmann@29973
   718
      val tys = (curry Library.take (num_args - k) o curry Library.drop k o fst o strip_type) ty;
haftmann@29973
   719
      val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
haftmann@29973
   720
      val vs = Name.names ctxt "a" tys;
haftmann@29973
   721
    in
haftmann@29973
   722
      fold_map (translate_typ thy algbr funcgr) tys
haftmann@29973
   723
      ##>> translate_case thy algbr funcgr thm case_scheme ((c, ty), ts @ map Free vs)
haftmann@31888
   724
      #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
haftmann@29973
   725
    end
haftmann@29973
   726
  else if length ts > num_args then
haftmann@29973
   727
    translate_case thy algbr funcgr thm case_scheme ((c, ty), Library.take (num_args, ts))
haftmann@29973
   728
    ##>> fold_map (translate_term thy algbr funcgr thm) (Library.drop (num_args, ts))
haftmann@29973
   729
    #>> (fn (t, ts) => t `$$ ts)
haftmann@29973
   730
  else
haftmann@29973
   731
    translate_case thy algbr funcgr thm case_scheme ((c, ty), ts)
haftmann@29973
   732
and translate_app thy algbr funcgr thm (c_ty_ts as ((c, _), _)) =
haftmann@29973
   733
  case Code.get_case_scheme thy c
haftmann@30023
   734
   of SOME case_scheme => translate_app_case thy algbr funcgr thm case_scheme c_ty_ts
haftmann@30932
   735
    | NONE => translate_app_const thy algbr funcgr thm c_ty_ts
haftmann@30932
   736
and translate_tyvar_sort thy (algbr as (proj_sort, _)) funcgr (v, sort) =
haftmann@30932
   737
  fold_map (ensure_class thy algbr funcgr) (proj_sort sort)
haftmann@30932
   738
  #>> (fn sort => (unprefix "'" v, sort))
haftmann@30932
   739
and translate_dicts thy (algbr as (proj_sort, algebra)) funcgr thm (ty, sort) =
haftmann@30932
   740
  let
haftmann@30932
   741
    val pp = Syntax.pp_global thy;
haftmann@30932
   742
    datatype typarg =
haftmann@30932
   743
        Global of (class * string) * typarg list list
haftmann@30932
   744
      | Local of (class * class) list * (string * (int * sort));
haftmann@30932
   745
    fun class_relation (Global ((_, tyco), yss), _) class =
haftmann@30932
   746
          Global ((class, tyco), yss)
haftmann@30932
   747
      | class_relation (Local (classrels, v), subclass) superclass =
haftmann@30932
   748
          Local ((subclass, superclass) :: classrels, v);
haftmann@30932
   749
    fun type_constructor tyco yss class =
haftmann@30932
   750
      Global ((class, tyco), (map o map) fst yss);
haftmann@30932
   751
    fun type_variable (TFree (v, sort)) =
haftmann@30932
   752
      let
haftmann@30932
   753
        val sort' = proj_sort sort;
haftmann@30932
   754
      in map_index (fn (n, class) => (Local ([], (v, (n, sort'))), class)) sort' end;
haftmann@30932
   755
    val typargs = Sorts.of_sort_derivation pp algebra
haftmann@30932
   756
      {class_relation = class_relation, type_constructor = type_constructor,
haftmann@30932
   757
       type_variable = type_variable} (ty, proj_sort sort)
haftmann@30932
   758
      handle Sorts.CLASS_ERROR e => not_wellsorted thy thm ty sort e;
haftmann@30932
   759
    fun mk_dict (Global (inst, yss)) =
haftmann@30932
   760
          ensure_inst thy algbr funcgr inst
haftmann@30932
   761
          ##>> (fold_map o fold_map) mk_dict yss
haftmann@30932
   762
          #>> (fn (inst, dss) => DictConst (inst, dss))
haftmann@30932
   763
      | mk_dict (Local (classrels, (v, (k, sort)))) =
haftmann@30932
   764
          fold_map (ensure_classrel thy algbr funcgr) classrels
haftmann@30932
   765
          #>> (fn classrels => DictVar (classrels, (unprefix "'" v, (k, length sort))))
haftmann@30932
   766
  in fold_map mk_dict typargs end;
haftmann@24918
   767
haftmann@25969
   768
haftmann@27103
   769
(* store *)
haftmann@27103
   770
haftmann@27103
   771
structure Program = CodeDataFun
haftmann@27103
   772
(
haftmann@28663
   773
  type T = naming * program;
haftmann@28663
   774
  val empty = (empty_naming, Graph.empty);
haftmann@28706
   775
  fun purge thy cs (naming, program) =
haftmann@27609
   776
    let
haftmann@28706
   777
      val names_delete = cs
haftmann@28706
   778
        |> map_filter (lookup_const naming)
haftmann@28706
   779
        |> filter (can (Graph.get_node program))
haftmann@28706
   780
        |> Graph.all_preds program;
haftmann@28706
   781
      val program' = Graph.del_nodes names_delete program;
haftmann@28706
   782
    in (naming, program') end;
haftmann@27103
   783
);
haftmann@27103
   784
haftmann@27103
   785
val cached_program = Program.get;
haftmann@25969
   786
haftmann@28924
   787
fun invoke_generation thy (algebra, funcgr) f name =
haftmann@28663
   788
  Program.change_yield thy (fn naming_program => (NONE, naming_program)
haftmann@28924
   789
    |> f thy algebra funcgr name
haftmann@28663
   790
    |-> (fn name => fn (_, naming_program) => (name, naming_program)));
haftmann@27103
   791
haftmann@27103
   792
haftmann@27103
   793
(* program generation *)
haftmann@27103
   794
haftmann@27103
   795
fun consts_program thy cs =
haftmann@27103
   796
  let
haftmann@28663
   797
    fun project_consts cs (naming, program) =
haftmann@27103
   798
      let
haftmann@27103
   799
        val cs_all = Graph.all_succs program cs;
haftmann@28663
   800
      in (cs, (naming, Graph.subgraph (member (op =) cs_all) program)) end;
haftmann@27103
   801
    fun generate_consts thy algebra funcgr =
haftmann@27103
   802
      fold_map (ensure_const thy algebra funcgr);
haftmann@27103
   803
  in
haftmann@31125
   804
    invoke_generation thy (Code_Preproc.obtain thy cs []) generate_consts cs
haftmann@27103
   805
    |-> project_consts
haftmann@27103
   806
  end;
haftmann@27103
   807
haftmann@27103
   808
haftmann@27103
   809
(* value evaluation *)
haftmann@25969
   810
haftmann@31063
   811
fun ensure_value thy algbr funcgr t =
haftmann@24918
   812
  let
haftmann@24918
   813
    val ty = fastype_of t;
haftmann@24918
   814
    val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
haftmann@24918
   815
      o dest_TFree))) t [];
haftmann@24918
   816
    val stmt_value =
haftmann@28688
   817
      fold_map (translate_tyvar_sort thy algbr funcgr) vs
haftmann@28688
   818
      ##>> translate_typ thy algbr funcgr ty
haftmann@28688
   819
      ##>> translate_term thy algbr funcgr NONE t
haftmann@28663
   820
      #>> (fn ((vs, ty), t) => Fun
haftmann@28663
   821
        (Term.dummy_patternN, ((vs, ty), [(([], t), (Drule.dummy_thm, true))])));
haftmann@31063
   822
    fun term_value (dep, (naming, program1)) =
haftmann@25969
   823
      let
haftmann@30947
   824
        val Fun (_, (vs_ty, [(([], t), _)])) =
haftmann@28663
   825
          Graph.get_node program1 Term.dummy_patternN;
haftmann@28663
   826
        val deps = Graph.imm_succs program1 Term.dummy_patternN;
haftmann@28663
   827
        val program2 = Graph.del_nodes [Term.dummy_patternN] program1;
haftmann@27103
   828
        val deps_all = Graph.all_succs program2 deps;
haftmann@27103
   829
        val program3 = Graph.subgraph (member (op =) deps_all) program2;
haftmann@31063
   830
      in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
haftmann@26011
   831
  in
haftmann@28663
   832
    ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
haftmann@26011
   833
    #> snd
haftmann@31063
   834
    #> term_value
haftmann@26011
   835
  end;
haftmann@24219
   836
haftmann@30947
   837
fun base_evaluator thy evaluator algebra funcgr vs t =
haftmann@30942
   838
  let
haftmann@31063
   839
    val (((naming, program), (((vs', ty'), t'), deps)), _) =
haftmann@31063
   840
      invoke_generation thy (algebra, funcgr) ensure_value t;
haftmann@30947
   841
    val vs'' = map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v)) vs';
haftmann@31063
   842
  in evaluator naming program ((vs'', (vs', ty')), t') deps end;
haftmann@30942
   843
haftmann@31125
   844
fun eval_conv thy prep_sort = Code_Preproc.eval_conv thy prep_sort o base_evaluator thy;
haftmann@31125
   845
fun eval thy prep_sort postproc = Code_Preproc.eval thy prep_sort postproc o base_evaluator thy;
haftmann@30942
   846
haftmann@30942
   847
haftmann@30942
   848
(** diagnostic commands **)
haftmann@30942
   849
haftmann@31036
   850
fun read_const_exprs thy =
haftmann@31036
   851
  let
haftmann@31036
   852
    fun consts_of some_thyname =
haftmann@31036
   853
      let
haftmann@31036
   854
        val thy' = case some_thyname
haftmann@31036
   855
         of SOME thyname => ThyInfo.the_theory thyname thy
haftmann@31036
   856
          | NONE => thy;
haftmann@31036
   857
        val cs = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
haftmann@31036
   858
          ((snd o #constants o Consts.dest o #consts o Sign.rep_sg) thy') [];
haftmann@31036
   859
        fun belongs_here c =
haftmann@31036
   860
          not (exists (fn thy'' => Sign.declared_const thy'' c) (Theory.parents_of thy'))
haftmann@31036
   861
      in case some_thyname
haftmann@31036
   862
       of NONE => cs
haftmann@31036
   863
        | SOME thyname => filter belongs_here cs
haftmann@31036
   864
      end;
haftmann@31036
   865
    fun read_const_expr "*" = ([], consts_of NONE)
haftmann@31036
   866
      | read_const_expr s = if String.isSuffix ".*" s
haftmann@31036
   867
          then ([], consts_of (SOME (unsuffix ".*" s)))
haftmann@31156
   868
          else ([Code.read_const thy s], []);
haftmann@31036
   869
  in pairself flat o split_list o map read_const_expr end;
haftmann@31036
   870
haftmann@30942
   871
fun code_depgr thy consts =
haftmann@30942
   872
  let
haftmann@31125
   873
    val (_, eqngr) = Code_Preproc.obtain thy consts [];
haftmann@30942
   874
    val select = Graph.all_succs eqngr consts;
haftmann@30942
   875
  in
haftmann@30942
   876
    eqngr
haftmann@30942
   877
    |> not (null consts) ? Graph.subgraph (member (op =) select) 
haftmann@30942
   878
    |> Graph.map_nodes ((apsnd o map o apfst) (AxClass.overload thy))
haftmann@30942
   879
  end;
haftmann@30942
   880
haftmann@31125
   881
fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
haftmann@30942
   882
haftmann@30942
   883
fun code_deps thy consts =
haftmann@27103
   884
  let
haftmann@30942
   885
    val eqngr = code_depgr thy consts;
haftmann@30942
   886
    val constss = Graph.strong_conn eqngr;
haftmann@30942
   887
    val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
haftmann@30942
   888
      Symtab.update (const, consts)) consts) constss;
haftmann@30942
   889
    fun succs consts = consts
haftmann@30942
   890
      |> maps (Graph.imm_succs eqngr)
haftmann@30942
   891
      |> subtract (op =) consts
haftmann@30942
   892
      |> map (the o Symtab.lookup mapping)
haftmann@30942
   893
      |> distinct (op =);
haftmann@30942
   894
    val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
haftmann@31156
   895
    fun namify consts = map (Code.string_of_const thy) consts
haftmann@30942
   896
      |> commas;
haftmann@30942
   897
    val prgr = map (fn (consts, constss) =>
haftmann@30942
   898
      { name = namify consts, ID = namify consts, dir = "", unfold = true,
haftmann@30942
   899
        path = "", parents = map namify constss }) conn;
haftmann@30942
   900
  in Present.display_graph prgr end;
haftmann@30942
   901
haftmann@30942
   902
local
haftmann@27103
   903
haftmann@30942
   904
structure P = OuterParse
haftmann@30942
   905
and K = OuterKeyword
haftmann@30942
   906
haftmann@31036
   907
fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
haftmann@31036
   908
fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
haftmann@30942
   909
haftmann@30942
   910
in
haftmann@30942
   911
haftmann@30942
   912
val _ =
haftmann@30942
   913
  OuterSyntax.improper_command "code_thms" "print system of code equations for code" OuterKeyword.diag
haftmann@30942
   914
    (Scan.repeat P.term_group
haftmann@30942
   915
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
   916
        o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
   917
haftmann@30942
   918
val _ =
haftmann@30942
   919
  OuterSyntax.improper_command "code_deps" "visualize dependencies of code equations for code" OuterKeyword.diag
haftmann@30942
   920
    (Scan.repeat P.term_group
haftmann@30942
   921
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
   922
        o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
   923
haftmann@30942
   924
end;
haftmann@27103
   925
haftmann@24219
   926
end; (*struct*)
haftmann@24219
   927
haftmann@24219
   928
haftmann@28054
   929
structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;