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