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