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