src/Tools/Code/code_thingol.ML
author haftmann
Thu, 19 Apr 2012 09:58:54 +0200
changeset 48445 6b362107e6d9
parent 48442 1d9faa9f65f9
child 48447 b32aae03e3d6
permissions -rw-r--r--
tuned
haftmann@37743
     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@42653
    18
      Dict of string list * plain_dict
haftmann@41366
    19
  and plain_dict = 
haftmann@41366
    20
      Dict_Const of string * dict list list
haftmann@41366
    21
    | Dict_Var of vname * (int * int)
haftmann@24219
    22
  datatype itype =
haftmann@24219
    23
      `%% of string * itype list
haftmann@24219
    24
    | ITyVar of vname;
bulwahn@45657
    25
  type const = string * (((itype list * dict list list) * (itype list * itype)) * bool)
bulwahn@45880
    26
    (* (f [T1..Tn] {dicts} (_::S1) .. (_::Sm)) :: S =^= (f, ((([T1..Tn], dicts), ([S1..Sm], S)), ambiguous)) *)
haftmann@24219
    27
  datatype iterm =
haftmann@24591
    28
      IConst of const
haftmann@31889
    29
    | IVar of vname option
haftmann@24219
    30
    | `$ of iterm * iterm
haftmann@31888
    31
    | `|=> of (vname option * itype) * iterm
haftmann@24219
    32
    | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
haftmann@24219
    33
        (*((term, type), [(selector pattern, body term )]), primitive term)*)
haftmann@24219
    34
  val `$$ : iterm * iterm list -> iterm;
haftmann@31888
    35
  val `|==> : (vname option * itype) list * iterm -> iterm;
haftmann@24219
    36
  type typscheme = (vname * sort) list * itype;
haftmann@24219
    37
end;
haftmann@24219
    38
haftmann@24219
    39
signature CODE_THINGOL =
haftmann@24219
    40
sig
haftmann@28663
    41
  include BASIC_CODE_THINGOL
haftmann@34084
    42
  val fun_tyco: string
haftmann@28663
    43
  val unfoldl: ('a -> ('a * 'b) option) -> 'a -> 'a * 'b list
haftmann@28663
    44
  val unfoldr: ('a -> ('b * 'a) option) -> 'a -> 'b list * 'a
haftmann@28663
    45
  val unfold_fun: itype -> itype list * itype
haftmann@37640
    46
  val unfold_fun_n: int -> itype -> itype list * itype
haftmann@28663
    47
  val unfold_app: iterm -> iterm * iterm list
haftmann@31888
    48
  val unfold_abs: iterm -> (vname option * itype) list * iterm
haftmann@28663
    49
  val split_let: iterm -> (((iterm * itype) * iterm) * iterm) option
haftmann@28663
    50
  val unfold_let: iterm -> ((iterm * itype) * iterm) list * iterm
haftmann@31889
    51
  val split_pat_abs: iterm -> ((iterm * itype) * iterm) option
haftmann@31889
    52
  val unfold_pat_abs: iterm -> (iterm * itype) list * iterm
haftmann@31049
    53
  val unfold_const_app: iterm -> (const * iterm list) option
haftmann@32909
    54
  val is_IVar: iterm -> bool
haftmann@42653
    55
  val is_IAbs: iterm -> bool
haftmann@31049
    56
  val eta_expand: int -> const * iterm list -> iterm
haftmann@41348
    57
  val contains_dict_var: iterm -> bool
haftmann@31934
    58
  val add_constnames: iterm -> string list -> string list
haftmann@32917
    59
  val add_tyconames: iterm -> string list -> string list
haftmann@28663
    60
  val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
haftmann@28663
    61
haftmann@28663
    62
  type naming
haftmann@28706
    63
  val empty_naming: naming
haftmann@28663
    64
  val lookup_class: naming -> class -> string option
haftmann@28663
    65
  val lookup_classrel: naming -> class * class -> string option
haftmann@28663
    66
  val lookup_tyco: naming -> string -> string option
haftmann@28663
    67
  val lookup_instance: naming -> class * string -> string option
haftmann@28663
    68
  val lookup_const: naming -> string -> string option
haftmann@31054
    69
  val ensure_declared_const: theory -> string -> naming -> string * naming
haftmann@24219
    70
haftmann@24918
    71
  datatype stmt =
haftmann@27024
    72
      NoStmt
haftmann@37412
    73
    | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
haftmann@37423
    74
    | Datatype of string * ((vname * sort) list *
haftmann@37423
    75
        ((string * vname list (*type argument wrt. canonical order*)) * itype list) list)
haftmann@28663
    76
    | Datatypecons of string * string
haftmann@37422
    77
    | Class of class * (vname * ((class * string) list * (string * itype) list))
haftmann@24219
    78
    | Classrel of class * class
haftmann@28663
    79
    | Classparam of string * class
haftmann@37423
    80
    | Classinst of (class * (string * (vname * sort) list) (*class and arity*))
haftmann@37420
    81
          * ((class * (string * (string * dict list list))) list (*super instances*)
haftmann@37423
    82
        * (((string * const) * (thm * bool)) list (*class parameter instances*)
haftmann@37423
    83
          * ((string * const) * (thm * bool)) list (*super class parameter instances*)))
haftmann@28663
    84
  type program = stmt Graph.T
haftmann@28663
    85
  val empty_funs: program -> string list
haftmann@28663
    86
  val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
haftmann@28663
    87
  val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
haftmann@28663
    88
  val is_cons: program -> string -> bool
haftmann@37415
    89
  val is_case: stmt -> bool
haftmann@32895
    90
  val labelled_name: theory -> program -> string -> string
haftmann@32895
    91
  val group_stmts: theory -> program
haftmann@32895
    92
    -> ((string * stmt) list * (string * stmt) list
haftmann@32895
    93
      * ((string * stmt) list * (string * stmt) list)) list
haftmann@24219
    94
haftmann@31036
    95
  val read_const_exprs: theory -> string list -> string list * string list
haftmann@36272
    96
  val consts_program: theory -> bool -> string list -> string list * (naming * program)
haftmann@41432
    97
  val dynamic_conv: theory -> (naming -> program
haftmann@39727
    98
    -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
haftmann@38911
    99
    -> conv
haftmann@41432
   100
  val dynamic_value: theory -> ((term -> term) -> 'a -> 'a) -> (naming -> program
haftmann@39727
   101
    -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
haftmann@28663
   102
    -> term -> 'a
haftmann@41594
   103
  val static_conv: theory -> string list -> (naming -> program -> string list
haftmann@41594
   104
    -> ((string * sort) list * typscheme) * iterm -> string list -> conv)
haftmann@38911
   105
    -> conv
haftmann@41432
   106
  val static_conv_simple: theory -> string list
haftmann@41594
   107
    -> (program -> (string * sort) list -> term -> conv) -> conv
haftmann@41432
   108
  val static_value: theory -> ((term -> term) -> 'a -> 'a) -> string list ->
haftmann@41594
   109
    (naming -> program -> string list
haftmann@41594
   110
      -> ((string * sort) list * typscheme) * iterm -> string list -> 'a)
haftmann@39715
   111
    -> term -> 'a
haftmann@24219
   112
end;
haftmann@24219
   113
haftmann@28054
   114
structure Code_Thingol: CODE_THINGOL =
haftmann@24219
   115
struct
haftmann@24219
   116
haftmann@24219
   117
(** auxiliary **)
haftmann@24219
   118
haftmann@24219
   119
fun unfoldl dest x =
haftmann@24219
   120
  case dest x
haftmann@24219
   121
   of NONE => (x, [])
haftmann@24219
   122
    | SOME (x1, x2) =>
haftmann@24219
   123
        let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
haftmann@24219
   124
haftmann@24219
   125
fun unfoldr dest x =
haftmann@24219
   126
  case dest x
haftmann@24219
   127
   of NONE => ([], x)
haftmann@24219
   128
    | SOME (x1, x2) =>
haftmann@24219
   129
        let val (xs', x') = unfoldr dest x2 in (x1::xs', x') end;
haftmann@24219
   130
haftmann@24219
   131
haftmann@29899
   132
(** language core - types, terms **)
haftmann@24219
   133
haftmann@24219
   134
type vname = string;
haftmann@24219
   135
haftmann@24219
   136
datatype dict =
haftmann@42653
   137
    Dict of string list * plain_dict
haftmann@41366
   138
and plain_dict = 
haftmann@41366
   139
    Dict_Const of string * dict list list
haftmann@41366
   140
  | Dict_Var of vname * (int * int)
haftmann@24219
   141
haftmann@24219
   142
datatype itype =
haftmann@24219
   143
    `%% of string * itype list
haftmann@24219
   144
  | ITyVar of vname;
haftmann@24219
   145
bulwahn@45657
   146
type const = string * (((itype list * dict list list) *
bulwahn@45880
   147
  (itype list (*types of arguments*) * itype (*result type*))) * bool (*requires type annotation*))
haftmann@24591
   148
haftmann@24219
   149
datatype iterm =
haftmann@24591
   150
    IConst of const
haftmann@31889
   151
  | IVar of vname option
haftmann@24219
   152
  | `$ of iterm * iterm
haftmann@31888
   153
  | `|=> of (vname option * itype) * iterm
haftmann@24219
   154
  | ICase of ((iterm * itype) * (iterm * iterm) list) * iterm;
haftmann@24219
   155
    (*see also signature*)
haftmann@24219
   156
haftmann@32909
   157
fun is_IVar (IVar _) = true
haftmann@32909
   158
  | is_IVar _ = false;
haftmann@32909
   159
haftmann@42653
   160
fun is_IAbs (_ `|=> _) = true
haftmann@42653
   161
  | is_IAbs _ = false;
haftmann@42653
   162
haftmann@24219
   163
val op `$$ = Library.foldl (op `$);
haftmann@31724
   164
val op `|==> = Library.foldr (op `|=>);
haftmann@24219
   165
haftmann@24219
   166
val unfold_app = unfoldl
haftmann@24219
   167
  (fn op `$ t => SOME t
haftmann@24219
   168
    | _ => NONE);
haftmann@24219
   169
haftmann@31873
   170
val unfold_abs = unfoldr
haftmann@31873
   171
  (fn op `|=> t => SOME t
haftmann@24219
   172
    | _ => NONE);
haftmann@24219
   173
haftmann@24219
   174
val split_let = 
haftmann@24219
   175
  (fn ICase (((td, ty), [(p, t)]), _) => SOME (((p, ty), td), t)
haftmann@24219
   176
    | _ => NONE);
haftmann@24219
   177
haftmann@24219
   178
val unfold_let = unfoldr split_let;
haftmann@24219
   179
haftmann@24219
   180
fun unfold_const_app t =
haftmann@24219
   181
 case unfold_app t
haftmann@24219
   182
  of (IConst c, ts) => SOME (c, ts)
haftmann@24219
   183
   | _ => NONE;
haftmann@24219
   184
haftmann@32917
   185
fun fold_constexprs f =
haftmann@32917
   186
  let
haftmann@32917
   187
    fun fold' (IConst c) = f c
haftmann@32917
   188
      | fold' (IVar _) = I
haftmann@32917
   189
      | fold' (t1 `$ t2) = fold' t1 #> fold' t2
haftmann@32917
   190
      | fold' (_ `|=> t) = fold' t
haftmann@32917
   191
      | fold' (ICase (((t, _), ds), _)) = fold' t
haftmann@32917
   192
          #> fold (fn (pat, body) => fold' pat #> fold' body) ds
haftmann@32917
   193
  in fold' end;
haftmann@32917
   194
haftmann@32917
   195
val add_constnames = fold_constexprs (fn (c, _) => insert (op =) c);
haftmann@32917
   196
haftmann@32917
   197
fun add_tycos (tyco `%% tys) = insert (op =) tyco #> fold add_tycos tys
haftmann@32917
   198
  | add_tycos (ITyVar _) = I;
haftmann@32917
   199
bulwahn@45656
   200
val add_tyconames = fold_constexprs (fn (_, (((tys, _), _), _)) => fold add_tycos tys);
haftmann@24219
   201
haftmann@24219
   202
fun fold_varnames f =
haftmann@24219
   203
  let
haftmann@31934
   204
    fun fold_aux add f =
haftmann@31934
   205
      let
haftmann@31934
   206
        fun fold_term _ (IConst _) = I
haftmann@31934
   207
          | fold_term vs (IVar (SOME v)) = if member (op =) vs v then I else f v
haftmann@31934
   208
          | fold_term _ (IVar NONE) = I
haftmann@31934
   209
          | fold_term vs (t1 `$ t2) = fold_term vs t1 #> fold_term vs t2
haftmann@31934
   210
          | fold_term vs ((SOME v, _) `|=> t) = fold_term (insert (op =) v vs) t
haftmann@31934
   211
          | fold_term vs ((NONE, _) `|=> t) = fold_term vs t
haftmann@31934
   212
          | fold_term vs (ICase (((t, _), ds), _)) = fold_term vs t #> fold (fold_case vs) ds
haftmann@31934
   213
        and fold_case vs (p, t) = fold_term (add p vs) t;
haftmann@31934
   214
      in fold_term [] end;
haftmann@31934
   215
    fun add t = fold_aux add (insert (op =)) t;
haftmann@31934
   216
  in fold_aux add f end;
haftmann@24219
   217
haftmann@31934
   218
fun exists_var t v = fold_varnames (fn w => fn b => v = w orelse b) t false;
haftmann@31873
   219
haftmann@31889
   220
fun split_pat_abs ((NONE, ty) `|=> t) = SOME ((IVar NONE, ty), t)
haftmann@31888
   221
  | split_pat_abs ((SOME v, ty) `|=> t) = SOME (case t
haftmann@31889
   222
     of ICase (((IVar (SOME w), _), [(p, t')]), _) =>
haftmann@31888
   223
          if v = w andalso (exists_var p v orelse not (exists_var t' v))
haftmann@31889
   224
          then ((p, ty), t')
haftmann@31889
   225
          else ((IVar (SOME v), ty), t)
haftmann@31889
   226
      | _ => ((IVar (SOME v), ty), t))
haftmann@31888
   227
  | split_pat_abs _ = NONE;
haftmann@31873
   228
haftmann@31873
   229
val unfold_pat_abs = unfoldr split_pat_abs;
haftmann@24219
   230
haftmann@31890
   231
fun unfold_abs_eta [] t = ([], t)
haftmann@31890
   232
  | unfold_abs_eta (_ :: tys) (v_ty `|=> t) =
haftmann@31890
   233
      let
haftmann@31890
   234
        val (vs_tys, t') = unfold_abs_eta tys t;
haftmann@31890
   235
      in (v_ty :: vs_tys, t') end
haftmann@31892
   236
  | unfold_abs_eta tys t =
haftmann@31890
   237
      let
haftmann@31890
   238
        val ctxt = fold_varnames Name.declare t Name.context;
wenzelm@44211
   239
        val vs_tys = (map o apfst) SOME (Name.invent_names ctxt "a" tys);
haftmann@31890
   240
      in (vs_tys, t `$$ map (IVar o fst) vs_tys) end;
haftmann@31890
   241
bulwahn@45657
   242
fun eta_expand k (c as (name, ((_, (tys, _)), _)), ts) =
haftmann@24219
   243
  let
haftmann@24219
   244
    val j = length ts;
haftmann@24219
   245
    val l = k - j;
haftmann@37841
   246
    val _ = if l > length tys
haftmann@37841
   247
      then error ("Impossible eta-expansion for constant " ^ quote name) else ();
haftmann@24219
   248
    val ctxt = (fold o fold_varnames) Name.declare ts Name.context;
haftmann@31889
   249
    val vs_tys = (map o apfst) SOME
wenzelm@44211
   250
      (Name.invent_names ctxt "a" ((take l o drop j) tys));
haftmann@31889
   251
  in vs_tys `|==> IConst c `$$ ts @ map (IVar o fst) vs_tys end;
haftmann@24219
   252
haftmann@41348
   253
fun contains_dict_var t =
haftmann@24662
   254
  let
haftmann@41366
   255
    fun cont_dict (Dict (_, d)) = cont_plain_dict d
haftmann@41366
   256
    and cont_plain_dict (Dict_Const (_, dss)) = (exists o exists) cont_dict dss
haftmann@41366
   257
      | cont_plain_dict (Dict_Var _) = true;
bulwahn@45656
   258
    fun cont_term (IConst (_, (((_, dss), _), _))) = (exists o exists) cont_dict dss
haftmann@31934
   259
      | cont_term (IVar _) = false
haftmann@31934
   260
      | cont_term (t1 `$ t2) = cont_term t1 orelse cont_term t2
haftmann@31934
   261
      | cont_term (_ `|=> t) = cont_term t
haftmann@31934
   262
      | cont_term (ICase (_, t)) = cont_term t;
haftmann@31934
   263
  in cont_term t end;
haftmann@25621
   264
haftmann@25621
   265
haftmann@28688
   266
(** namings **)
haftmann@28663
   267
haftmann@28663
   268
(* policies *)
haftmann@28663
   269
haftmann@28663
   270
local
bulwahn@46059
   271
  fun thyname_of_type thy = #theory_name o Name_Space.the_entry (Sign.type_space thy);
wenzelm@33172
   272
  fun thyname_of_class thy = #theory_name o Name_Space.the_entry (Sign.class_space thy);
wenzelm@33172
   273
  fun thyname_of_instance thy inst = case AxClass.thynames_of_arity thy inst
wenzelm@33172
   274
   of [] => error ("No such instance: " ^ quote (snd inst ^ " :: " ^ fst inst))
haftmann@28663
   275
    | thyname :: _ => thyname;
haftmann@28706
   276
  fun thyname_of_const thy c = case AxClass.class_of_param thy c
haftmann@28706
   277
   of SOME class => thyname_of_class thy class
haftmann@35299
   278
    | NONE => (case Code.get_type_of_constr_or_abstr thy c
bulwahn@46059
   279
       of SOME (tyco, _) => thyname_of_type thy tyco
haftmann@48445
   280
        | NONE => #theory_name (Name_Space.the_entry (Sign.const_space thy) c));
haftmann@33409
   281
  fun purify_base "==>" = "follows"
haftmann@39808
   282
    | purify_base "==" = "meta_eq"
haftmann@31036
   283
    | purify_base s = Name.desymbolize false s;
haftmann@28663
   284
  fun namify thy get_basename get_thyname name =
haftmann@28663
   285
    let
haftmann@28663
   286
      val prefix = get_thyname thy name;
haftmann@31036
   287
      val base = (purify_base o get_basename) name;
wenzelm@30364
   288
    in Long_Name.append prefix base end;
haftmann@28663
   289
in
haftmann@28663
   290
wenzelm@30364
   291
fun namify_class thy = namify thy Long_Name.base_name thyname_of_class;
haftmann@37359
   292
fun namify_classrel thy = namify thy (fn (sub_class, super_class) => 
haftmann@37406
   293
    Long_Name.base_name super_class ^ "_" ^ Long_Name.base_name sub_class)
wenzelm@33172
   294
  (fn thy => thyname_of_class thy o fst);
haftmann@28663
   295
  (*order fits nicely with composed projections*)
haftmann@28688
   296
fun namify_tyco thy "fun" = "Pure.fun"
bulwahn@46059
   297
  | namify_tyco thy tyco = namify thy Long_Name.base_name thyname_of_type tyco;
haftmann@28663
   298
fun namify_instance thy = namify thy (fn (class, tyco) => 
wenzelm@30364
   299
  Long_Name.base_name class ^ "_" ^ Long_Name.base_name tyco) thyname_of_instance;
wenzelm@30364
   300
fun namify_const thy = namify thy Long_Name.base_name thyname_of_const;
haftmann@28663
   301
haftmann@28663
   302
end; (* local *)
haftmann@28663
   303
haftmann@28663
   304
haftmann@28688
   305
(* data *)
haftmann@28663
   306
haftmann@28663
   307
datatype naming = Naming of {
haftmann@28663
   308
  class: class Symtab.table * Name.context,
haftmann@30636
   309
  classrel: string Symreltab.table * Name.context,
haftmann@28663
   310
  tyco: string Symtab.table * Name.context,
haftmann@30636
   311
  instance: string Symreltab.table * Name.context,
haftmann@28663
   312
  const: string Symtab.table * Name.context
haftmann@28663
   313
}
haftmann@28663
   314
haftmann@28663
   315
fun dest_Naming (Naming naming) = naming;
haftmann@28663
   316
haftmann@28663
   317
val empty_naming = Naming {
haftmann@28663
   318
  class = (Symtab.empty, Name.context),
haftmann@30636
   319
  classrel = (Symreltab.empty, Name.context),
haftmann@28663
   320
  tyco = (Symtab.empty, Name.context),
haftmann@30636
   321
  instance = (Symreltab.empty, Name.context),
haftmann@28663
   322
  const = (Symtab.empty, Name.context)
haftmann@28663
   323
};
haftmann@28663
   324
haftmann@28663
   325
local
haftmann@28663
   326
  fun mk_naming (class, classrel, tyco, instance, const) =
haftmann@28663
   327
    Naming { class = class, classrel = classrel,
haftmann@28663
   328
      tyco = tyco, instance = instance, const = const };
haftmann@28663
   329
  fun map_naming f (Naming { class, classrel, tyco, instance, const }) =
haftmann@28663
   330
    mk_naming (f (class, classrel, tyco, instance, const));
haftmann@28663
   331
in
haftmann@28663
   332
  fun map_class f = map_naming
haftmann@28663
   333
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   334
      (f class, classrel, tyco, inst, const));
haftmann@28663
   335
  fun map_classrel f = map_naming
haftmann@28663
   336
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   337
      (class, f classrel, tyco, inst, const));
haftmann@28663
   338
  fun map_tyco f = map_naming
haftmann@28663
   339
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   340
      (class, classrel, f tyco, inst, const));
haftmann@28663
   341
  fun map_instance f = map_naming
haftmann@28663
   342
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   343
      (class, classrel, tyco, f inst, const));
haftmann@28663
   344
  fun map_const f = map_naming
haftmann@28663
   345
    (fn (class, classrel, tyco, inst, const) =>
haftmann@28663
   346
      (class, classrel, tyco, inst, f const));
haftmann@28663
   347
end; (*local*)
haftmann@28663
   348
haftmann@28663
   349
fun add_variant update (thing, name) (tab, used) =
haftmann@28663
   350
  let
wenzelm@44208
   351
    val (name', used') = Name.variant name used;
haftmann@28663
   352
    val tab' = update (thing, name') tab;
haftmann@28663
   353
  in (tab', used') end;
haftmann@28663
   354
haftmann@28663
   355
fun declare thy mapp lookup update namify thing =
haftmann@28663
   356
  mapp (add_variant update (thing, namify thy thing))
haftmann@28663
   357
  #> `(fn naming => the (lookup naming thing));
haftmann@28663
   358
haftmann@28688
   359
haftmann@28688
   360
(* lookup and declare *)
haftmann@28688
   361
haftmann@28688
   362
local
haftmann@28688
   363
haftmann@28688
   364
val suffix_class = "class";
haftmann@28688
   365
val suffix_classrel = "classrel"
haftmann@28688
   366
val suffix_tyco = "tyco";
haftmann@28688
   367
val suffix_instance = "inst";
haftmann@28688
   368
val suffix_const = "const";
haftmann@28688
   369
haftmann@28688
   370
fun add_suffix nsp NONE = NONE
wenzelm@30364
   371
  | add_suffix nsp (SOME name) = SOME (Long_Name.append name nsp);
haftmann@28688
   372
haftmann@28688
   373
in
haftmann@28688
   374
haftmann@28663
   375
val lookup_class = add_suffix suffix_class
haftmann@28663
   376
  oo Symtab.lookup o fst o #class o dest_Naming;
haftmann@28663
   377
val lookup_classrel = add_suffix suffix_classrel
haftmann@30636
   378
  oo Symreltab.lookup o fst o #classrel o dest_Naming;
haftmann@28663
   379
val lookup_tyco = add_suffix suffix_tyco
haftmann@28663
   380
  oo Symtab.lookup o fst o #tyco o dest_Naming;
haftmann@28663
   381
val lookup_instance = add_suffix suffix_instance
haftmann@30636
   382
  oo Symreltab.lookup o fst o #instance o dest_Naming;
haftmann@28663
   383
val lookup_const = add_suffix suffix_const
haftmann@28663
   384
  oo Symtab.lookup o fst o #const o dest_Naming;
haftmann@28663
   385
haftmann@28663
   386
fun declare_class thy = declare thy map_class
haftmann@28663
   387
  lookup_class Symtab.update_new namify_class;
haftmann@28663
   388
fun declare_classrel thy = declare thy map_classrel
haftmann@30636
   389
  lookup_classrel Symreltab.update_new namify_classrel;
haftmann@28663
   390
fun declare_tyco thy = declare thy map_tyco
haftmann@28663
   391
  lookup_tyco Symtab.update_new namify_tyco;
haftmann@28663
   392
fun declare_instance thy = declare thy map_instance
haftmann@30636
   393
  lookup_instance Symreltab.update_new namify_instance;
haftmann@28663
   394
fun declare_const thy = declare thy map_const
haftmann@28663
   395
  lookup_const Symtab.update_new namify_const;
haftmann@28663
   396
haftmann@31054
   397
fun ensure_declared_const thy const naming =
haftmann@31054
   398
  case lookup_const naming const
haftmann@31054
   399
   of SOME const' => (const', naming)
haftmann@31054
   400
    | NONE => declare_const thy const naming;
haftmann@31054
   401
haftmann@37359
   402
val fun_tyco = Long_Name.append (namify_tyco Pure.thy "fun") suffix_tyco
haftmann@37359
   403
  (*depends on add_suffix*);
haftmann@34084
   404
haftmann@28688
   405
val unfold_fun = unfoldr
haftmann@34084
   406
  (fn tyco `%% [ty1, ty2] => if tyco = fun_tyco then SOME (ty1, ty2) else NONE
haftmann@37359
   407
    | _ => NONE);
haftmann@28688
   408
haftmann@37640
   409
fun unfold_fun_n n ty =
haftmann@37640
   410
  let
haftmann@37640
   411
    val (tys1, ty1) = unfold_fun ty;
haftmann@37640
   412
    val (tys3, tys2) = chop n tys1;
haftmann@37640
   413
    val ty3 = Library.foldr (fn (ty1, ty2) => fun_tyco `%% [ty1, ty2]) (tys2, ty1);
haftmann@37640
   414
  in (tys3, ty3) end;
haftmann@37640
   415
haftmann@28688
   416
end; (* local *)
haftmann@28688
   417
haftmann@24219
   418
haftmann@27103
   419
(** statements, abstract programs **)
haftmann@24219
   420
haftmann@24219
   421
type typscheme = (vname * sort) list * itype;
haftmann@37422
   422
datatype stmt =
haftmann@27024
   423
    NoStmt
haftmann@37412
   424
  | Fun of string * ((typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option)
haftmann@37423
   425
  | Datatype of string * ((vname * sort) list * ((string * vname list) * itype list) list)
haftmann@28663
   426
  | Datatypecons of string * string
haftmann@37422
   427
  | Class of class * (vname * ((class * string) list * (string * itype) list))
haftmann@24219
   428
  | Classrel of class * class
haftmann@28663
   429
  | Classparam of string * class
haftmann@24219
   430
  | Classinst of (class * (string * (vname * sort) list))
haftmann@37420
   431
        * ((class * (string * (string * dict list list))) list
haftmann@37423
   432
      * (((string * const) * (thm * bool)) list
haftmann@37423
   433
        * ((string * const) * (thm * bool)) list))
haftmann@37423
   434
      (*see also signature*);
haftmann@24219
   435
haftmann@27103
   436
type program = stmt Graph.T;
haftmann@24219
   437
haftmann@27103
   438
fun empty_funs program =
haftmann@37412
   439
  Graph.fold (fn (name, (Fun (c, ((_, []), _)), _)) => cons c
haftmann@27103
   440
               | _ => I) program [];
haftmann@24219
   441
haftmann@27711
   442
fun map_terms_bottom_up f (t as IConst _) = f t
haftmann@27711
   443
  | map_terms_bottom_up f (t as IVar _) = f t
haftmann@27711
   444
  | map_terms_bottom_up f (t1 `$ t2) = f
haftmann@27711
   445
      (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
haftmann@31724
   446
  | map_terms_bottom_up f ((v, ty) `|=> t) = f
haftmann@31724
   447
      ((v, ty) `|=> map_terms_bottom_up f t)
haftmann@27711
   448
  | map_terms_bottom_up f (ICase (((t, ty), ps), t0)) = f
haftmann@27711
   449
      (ICase (((map_terms_bottom_up f t, ty), (map o pairself)
haftmann@27711
   450
        (map_terms_bottom_up f) ps), map_terms_bottom_up f t0));
haftmann@27711
   451
haftmann@37423
   452
fun map_classparam_instances_as_term f =
haftmann@37423
   453
  (map o apfst o apsnd) (fn const => case f (IConst const) of IConst const' => const')
haftmann@37423
   454
haftmann@27711
   455
fun map_terms_stmt f NoStmt = NoStmt
haftmann@37412
   456
  | map_terms_stmt f (Fun (c, ((tysm, eqs), case_cong))) = Fun (c, ((tysm, (map o apfst)
haftmann@37412
   457
      (fn (ts, t) => (map f ts, f t)) eqs), case_cong))
haftmann@27711
   458
  | map_terms_stmt f (stmt as Datatype _) = stmt
haftmann@27711
   459
  | map_terms_stmt f (stmt as Datatypecons _) = stmt
haftmann@27711
   460
  | map_terms_stmt f (stmt as Class _) = stmt
haftmann@27711
   461
  | map_terms_stmt f (stmt as Classrel _) = stmt
haftmann@27711
   462
  | map_terms_stmt f (stmt as Classparam _) = stmt
haftmann@37423
   463
  | map_terms_stmt f (Classinst (arity, (super_instances, classparam_instances))) =
haftmann@37423
   464
      Classinst (arity, (super_instances, (pairself o map_classparam_instances_as_term) f classparam_instances));
haftmann@27711
   465
haftmann@27103
   466
fun is_cons program name = case Graph.get_node program name
haftmann@24219
   467
 of Datatypecons _ => true
haftmann@24219
   468
  | _ => false;
haftmann@24219
   469
haftmann@37415
   470
fun is_case (Fun (_, (_, SOME _))) = true
haftmann@37415
   471
  | is_case _ = false;
haftmann@37415
   472
wenzelm@43230
   473
fun labelled_name thy program name =
wenzelm@43232
   474
  let val ctxt = Proof_Context.init_global thy in
wenzelm@43230
   475
    case Graph.get_node program name of
wenzelm@43230
   476
      Fun (c, _) => quote (Code.string_of_const thy c)
wenzelm@43232
   477
    | Datatype (tyco, _) => "type " ^ quote (Proof_Context.extern_type ctxt tyco)
wenzelm@43230
   478
    | Datatypecons (c, _) => quote (Code.string_of_const thy c)
wenzelm@43232
   479
    | Class (class, _) => "class " ^ quote (Proof_Context.extern_class ctxt class)
wenzelm@43230
   480
    | Classrel (sub, super) =>
wenzelm@43230
   481
        let
wenzelm@43230
   482
          val Class (sub, _) = Graph.get_node program sub;
wenzelm@43230
   483
          val Class (super, _) = Graph.get_node program super;
wenzelm@43230
   484
        in
wenzelm@43232
   485
          quote (Proof_Context.extern_class ctxt sub ^ " < " ^ Proof_Context.extern_class ctxt super)
wenzelm@43230
   486
        end
wenzelm@43230
   487
    | Classparam (c, _) => quote (Code.string_of_const thy c)
wenzelm@43230
   488
    | Classinst ((class, (tyco, _)), _) =>
wenzelm@43230
   489
        let
wenzelm@43230
   490
          val Class (class, _) = Graph.get_node program class;
wenzelm@43230
   491
          val Datatype (tyco, _) = Graph.get_node program tyco;
wenzelm@43230
   492
        in
wenzelm@43232
   493
          quote (Proof_Context.extern_type ctxt tyco ^ " :: " ^ Proof_Context.extern_class ctxt class)
wenzelm@43230
   494
        end
wenzelm@43230
   495
  end;
haftmann@32895
   496
haftmann@37415
   497
fun linear_stmts program =
haftmann@37415
   498
  rev (Graph.strong_conn program)
haftmann@37415
   499
  |> map (AList.make (Graph.get_node program));
haftmann@37415
   500
haftmann@32895
   501
fun group_stmts thy program =
haftmann@32895
   502
  let
haftmann@32895
   503
    fun is_fun (_, Fun _) = true | is_fun _ = false;
haftmann@32895
   504
    fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
haftmann@32895
   505
    fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
haftmann@32895
   506
    fun is_class (_, Class _) = true | is_class _ = false;
haftmann@32895
   507
    fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
haftmann@32895
   508
    fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
haftmann@32895
   509
    fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
haftmann@32895
   510
    fun group stmts =
haftmann@32895
   511
      if forall (is_datatypecons orf is_datatype) stmts
haftmann@32895
   512
      then (filter is_datatype stmts, [], ([], []))
haftmann@32895
   513
      else if forall (is_class orf is_classrel orf is_classparam) stmts
haftmann@32895
   514
      then ([], filter is_class stmts, ([], []))
haftmann@32895
   515
      else if forall (is_fun orf is_classinst) stmts
haftmann@32895
   516
      then ([], [], List.partition is_fun stmts)
haftmann@32895
   517
      else error ("Illegal mutual dependencies: " ^
haftmann@32895
   518
        (commas o map (labelled_name thy program o fst)) stmts)
haftmann@32895
   519
  in
haftmann@37415
   520
    linear_stmts program
haftmann@32895
   521
    |> map group
haftmann@32895
   522
  end;
haftmann@32895
   523
haftmann@24219
   524
haftmann@27103
   525
(** translation kernel **)
haftmann@24219
   526
haftmann@28724
   527
(* generic mechanisms *)
haftmann@28724
   528
haftmann@28663
   529
fun ensure_stmt lookup declare generate thing (dep, (naming, program)) =
haftmann@24219
   530
  let
haftmann@28706
   531
    fun add_dep name = case dep of NONE => I
haftmann@28706
   532
      | SOME dep => Graph.add_edge (dep, name);
haftmann@28706
   533
    val (name, naming') = case lookup naming thing
haftmann@28706
   534
     of SOME name => (name, naming)
haftmann@28706
   535
      | NONE => declare thing naming;
haftmann@28706
   536
  in case try (Graph.get_node program) name
haftmann@28706
   537
   of SOME stmt => program
haftmann@28663
   538
        |> add_dep name
haftmann@28706
   539
        |> pair naming'
haftmann@28663
   540
        |> pair dep
haftmann@28663
   541
        |> pair name
haftmann@28706
   542
    | NONE => program
haftmann@28706
   543
        |> Graph.default_node (name, NoStmt)
haftmann@28706
   544
        |> add_dep name
haftmann@28706
   545
        |> pair naming'
haftmann@28706
   546
        |> curry generate (SOME name)
haftmann@28706
   547
        ||> snd
haftmann@28706
   548
        |-> (fn stmt => (apsnd o Graph.map_node name) (K stmt))
haftmann@28706
   549
        |> pair dep
haftmann@28706
   550
        |> pair name
haftmann@24219
   551
  end;
haftmann@24219
   552
haftmann@36272
   553
exception PERMISSIVE of unit;
haftmann@36272
   554
haftmann@37689
   555
fun translation_error thy permissive some_thm msg sub_msg =
haftmann@36272
   556
  if permissive
haftmann@36272
   557
  then raise PERMISSIVE ()
wenzelm@43260
   558
  else
wenzelm@43260
   559
    let
wenzelm@43260
   560
      val err_thm =
wenzelm@43260
   561
        (case some_thm of
wenzelm@43260
   562
          SOME thm => "\n(in code equation " ^ Display.string_of_thm_global thy thm ^ ")"
wenzelm@43260
   563
        | NONE => "");
wenzelm@43260
   564
    in error (msg ^ err_thm ^ ":\n" ^ sub_msg) end;
haftmann@37689
   565
haftmann@37689
   566
fun not_wellsorted thy permissive some_thm ty sort e =
haftmann@37689
   567
  let
wenzelm@47876
   568
    val err_class = Sorts.class_error (Context.pretty_global thy) e;
wenzelm@43260
   569
    val err_typ =
wenzelm@47876
   570
      "Type " ^ Syntax.string_of_typ_global thy ty ^ " not of sort " ^
wenzelm@43260
   571
        Syntax.string_of_sort_global thy sort;
wenzelm@43260
   572
  in
wenzelm@43260
   573
    translation_error thy permissive some_thm "Wellsortedness error"
wenzelm@43260
   574
      (err_typ ^ "\n" ^ err_class)
wenzelm@43260
   575
  end;
haftmann@26972
   576
haftmann@48420
   577
bulwahn@45658
   578
(* inference of type annotations for disambiguation with type classes *)
bulwahn@45658
   579
bulwahn@45862
   580
fun mk_tagged_type (true, T) = Type ("", [T])
haftmann@48420
   581
  | mk_tagged_type (false, T) = T;
bulwahn@45862
   582
bulwahn@45860
   583
fun dest_tagged_type (Type ("", [T])) = (true, T)
haftmann@48420
   584
  | dest_tagged_type T = (false, T);
bulwahn@45860
   585
haftmann@48420
   586
val untag_term = map_types (snd o dest_tagged_type);
bulwahn@45860
   587
bulwahn@45862
   588
fun tag_term (proj_sort, _) eqngr =
bulwahn@45859
   589
  let
haftmann@48420
   590
    val has_sort_constraints = exists (not o null) o map proj_sort o Code_Preproc.sortargs eqngr;
bulwahn@45862
   591
    fun tag (Const (c', T')) (Const (c, T)) =
bulwahn@45862
   592
        Const (c,
bulwahn@45862
   593
          mk_tagged_type (not (null (Term.add_tvarsT T' [])) andalso has_sort_constraints c, T))
bulwahn@45862
   594
      | tag (t1 $ u1) (t $ u) = tag t1 t $ tag u1 u
bulwahn@45862
   595
      | tag (Abs (_, _, t1)) (Abs (x, T, t)) = Abs (x, T, tag t1 t)
bulwahn@45862
   596
      | tag (Free _) (t as Free _) = t
bulwahn@45862
   597
      | tag (Var _) (t as Var _) = t
haftmann@48420
   598
      | tag (Bound _) (t as Bound _) = t;
bulwahn@45859
   599
  in
bulwahn@45862
   600
    tag
bulwahn@45859
   601
  end
bulwahn@45658
   602
bulwahn@45859
   603
fun annotate thy algbr eqngr (c, ty) args rhs =
bulwahn@45658
   604
  let
wenzelm@45999
   605
    val ctxt = Proof_Context.init_global thy |> Config.put Type_Infer_Context.const_sorts false
bulwahn@45658
   606
    val erase = map_types (fn _ => Type_Infer.anyT [])
bulwahn@45658
   607
    val reinfer = singleton (Type_Infer_Context.infer_types ctxt)
bulwahn@45858
   608
    val lhs = list_comb (Const (c, ty), map (map_types Type.strip_sorts o fst) args)
bulwahn@45858
   609
    val reinferred_rhs = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase rhs))))
bulwahn@45658
   610
  in
bulwahn@45862
   611
    tag_term algbr eqngr reinferred_rhs rhs
bulwahn@45858
   612
  end
bulwahn@45858
   613
bulwahn@45859
   614
fun annotate_eqns thy algbr eqngr (c, ty) eqns = 
bulwahn@45859
   615
  map (apfst (fn (args, (rhs, some_abs)) => (args,
bulwahn@45859
   616
    (annotate thy algbr eqngr (c, ty) args rhs, some_abs)))) eqns
haftmann@28724
   617
haftmann@48420
   618
haftmann@28724
   619
(* translation *)
haftmann@28724
   620
haftmann@36272
   621
fun ensure_tyco thy algbr eqngr permissive tyco =
haftmann@30932
   622
  let
haftmann@40969
   623
    val ((vs, cos), _) = Code.get_type thy tyco;
haftmann@30932
   624
    val stmt_datatype =
haftmann@36272
   625
      fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
haftmann@40969
   626
      ##>> fold_map (fn (c, (vs, tys)) =>
haftmann@36272
   627
        ensure_const thy algbr eqngr permissive c
haftmann@40969
   628
        ##>> pair (map (unprefix "'" o fst) vs)
haftmann@36272
   629
        ##>> fold_map (translate_typ thy algbr eqngr permissive) tys) cos
haftmann@36272
   630
      #>> (fn info => Datatype (tyco, info));
haftmann@30932
   631
  in ensure_stmt lookup_tyco (declare_tyco thy) stmt_datatype tyco end
haftmann@36272
   632
and ensure_const thy algbr eqngr permissive c =
haftmann@30932
   633
  let
haftmann@30932
   634
    fun stmt_datatypecons tyco =
haftmann@36272
   635
      ensure_tyco thy algbr eqngr permissive tyco
haftmann@30932
   636
      #>> (fn tyco => Datatypecons (c, tyco));
haftmann@30932
   637
    fun stmt_classparam class =
haftmann@36272
   638
      ensure_class thy algbr eqngr permissive class
haftmann@30932
   639
      #>> (fn class => Classparam (c, class));
haftmann@34891
   640
    fun stmt_fun cert =
haftmann@32872
   641
      let
haftmann@35226
   642
        val ((vs, ty), eqns) = Code.equations_of_cert thy cert;
bulwahn@45859
   643
        val eqns' = annotate_eqns thy algbr eqngr (c, ty) eqns
haftmann@37415
   644
        val some_case_cong = Code.get_case_cong thy c;
haftmann@32872
   645
      in
haftmann@36272
   646
        fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
haftmann@36272
   647
        ##>> translate_typ thy algbr eqngr permissive ty
bulwahn@45659
   648
        ##>> translate_eqns thy algbr eqngr permissive eqns'
haftmann@37415
   649
        #>> (fn info => Fun (c, (info, some_case_cong)))
haftmann@32872
   650
      end;
haftmann@35299
   651
    val stmt_const = case Code.get_type_of_constr_or_abstr thy c
haftmann@35226
   652
     of SOME (tyco, _) => stmt_datatypecons tyco
haftmann@30932
   653
      | NONE => (case AxClass.class_of_param thy c
haftmann@30932
   654
         of SOME class => stmt_classparam class
haftmann@34891
   655
          | NONE => stmt_fun (Code_Preproc.cert eqngr c))
haftmann@30932
   656
  in ensure_stmt lookup_const (declare_const thy) stmt_const c end
haftmann@36272
   657
and ensure_class thy (algbr as (_, algebra)) eqngr permissive class =
haftmann@24918
   658
  let
haftmann@37359
   659
    val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
wenzelm@24969
   660
    val cs = #params (AxClass.get_info thy class);
haftmann@24918
   661
    val stmt_class =
haftmann@37359
   662
      fold_map (fn super_class => ensure_class thy algbr eqngr permissive super_class
haftmann@37359
   663
        ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)) super_classes
haftmann@36272
   664
      ##>> fold_map (fn (c, ty) => ensure_const thy algbr eqngr permissive c
haftmann@36272
   665
        ##>> translate_typ thy algbr eqngr permissive ty) cs
haftmann@28663
   666
      #>> (fn info => Class (class, (unprefix "'" Name.aT, info)))
haftmann@28663
   667
  in ensure_stmt lookup_class (declare_class thy) stmt_class class end
haftmann@37359
   668
and ensure_classrel thy algbr eqngr permissive (sub_class, super_class) =
haftmann@24918
   669
  let
haftmann@24918
   670
    val stmt_classrel =
haftmann@37359
   671
      ensure_class thy algbr eqngr permissive sub_class
haftmann@37359
   672
      ##>> ensure_class thy algbr eqngr permissive super_class
haftmann@24918
   673
      #>> Classrel;
haftmann@37359
   674
  in ensure_stmt lookup_classrel (declare_classrel thy) stmt_classrel (sub_class, super_class) end
haftmann@36272
   675
and ensure_inst thy (algbr as (_, algebra)) eqngr permissive (class, tyco) =
haftmann@24918
   676
  let
haftmann@37359
   677
    val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
haftmann@37423
   678
    val these_classparams = these o try (#params o AxClass.get_info thy);
haftmann@37423
   679
    val classparams = these_classparams class;
haftmann@37423
   680
    val further_classparams = maps these_classparams
haftmann@37423
   681
      ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
wenzelm@44211
   682
    val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
haftmann@24918
   683
    val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
haftmann@24918
   684
    val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
haftmann@24918
   685
      Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
haftmann@24918
   686
    val arity_typ = Type (tyco, map TFree vs);
haftmann@24918
   687
    val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
haftmann@37359
   688
    fun translate_super_instance super_class =
haftmann@37359
   689
      ensure_class thy algbr eqngr permissive super_class
haftmann@37359
   690
      ##>> ensure_classrel thy algbr eqngr permissive (class, super_class)
haftmann@37359
   691
      ##>> translate_dicts thy algbr eqngr permissive NONE (arity_typ, [super_class])
haftmann@41366
   692
      #>> (fn ((super_class, classrel), [Dict ([], Dict_Const (inst, dss))]) =>
haftmann@37359
   693
            (super_class, (classrel, (inst, dss))));
haftmann@37359
   694
    fun translate_classparam_instance (c, ty) =
haftmann@24918
   695
      let
haftmann@37359
   696
        val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
haftmann@37359
   697
        val thm = AxClass.unoverload_conv thy (Thm.cterm_of thy raw_const);
haftmann@37359
   698
        val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
haftmann@24918
   699
          o Logic.dest_equals o Thm.prop_of) thm;
haftmann@24918
   700
      in
haftmann@36272
   701
        ensure_const thy algbr eqngr permissive c
haftmann@37359
   702
        ##>> translate_const thy algbr eqngr permissive (SOME thm) (const, NONE)
haftmann@37359
   703
        #>> (fn (c, IConst const') => ((c, const'), (thm, true)))
haftmann@24918
   704
      end;
haftmann@24918
   705
    val stmt_inst =
haftmann@36272
   706
      ensure_class thy algbr eqngr permissive class
haftmann@36272
   707
      ##>> ensure_tyco thy algbr eqngr permissive tyco
haftmann@36272
   708
      ##>> fold_map (translate_tyvar_sort thy algbr eqngr permissive) vs
haftmann@37359
   709
      ##>> fold_map translate_super_instance super_classes
haftmann@37359
   710
      ##>> fold_map translate_classparam_instance classparams
haftmann@37423
   711
      ##>> fold_map translate_classparam_instance further_classparams
haftmann@37423
   712
      #>> (fn (((((class, tyco), arity_args), super_instances),
haftmann@37423
   713
        classparam_instances), further_classparam_instances) =>
haftmann@37423
   714
          Classinst ((class, (tyco, arity_args)), (super_instances,
haftmann@37423
   715
            (classparam_instances, further_classparam_instances))));
haftmann@28663
   716
  in ensure_stmt lookup_instance (declare_instance thy) stmt_inst (class, tyco) end
haftmann@36272
   717
and translate_typ thy algbr eqngr permissive (TFree (v, _)) =
haftmann@30932
   718
      pair (ITyVar (unprefix "'" v))
haftmann@36272
   719
  | translate_typ thy algbr eqngr permissive (Type (tyco, tys)) =
haftmann@36272
   720
      ensure_tyco thy algbr eqngr permissive tyco
haftmann@36272
   721
      ##>> fold_map (translate_typ thy algbr eqngr permissive) tys
haftmann@30932
   722
      #>> (fn (tyco, tys) => tyco `%% tys)
haftmann@36272
   723
and translate_term thy algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
haftmann@36272
   724
      translate_app thy algbr eqngr permissive some_thm (((c, ty), []), some_abs)
haftmann@36272
   725
  | translate_term thy algbr eqngr permissive some_thm (Free (v, _), some_abs) =
haftmann@31889
   726
      pair (IVar (SOME v))
haftmann@36272
   727
  | translate_term thy algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
haftmann@24918
   728
      let
wenzelm@43156
   729
        val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize false v, ty, t);
haftmann@32270
   730
        val v'' = if member (op =) (Term.add_free_names t' []) v'
haftmann@32270
   731
          then SOME v' else NONE
haftmann@24918
   732
      in
haftmann@36272
   733
        translate_typ thy algbr eqngr permissive ty
haftmann@36272
   734
        ##>> translate_term thy algbr eqngr permissive some_thm (t', some_abs)
haftmann@32270
   735
        #>> (fn (ty, t) => (v'', ty) `|=> t)
haftmann@24918
   736
      end
haftmann@36272
   737
  | translate_term thy algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
haftmann@24918
   738
      case strip_comb t
haftmann@24918
   739
       of (Const (c, ty), ts) =>
haftmann@36272
   740
            translate_app thy algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
haftmann@24918
   741
        | (t', ts) =>
haftmann@36272
   742
            translate_term thy algbr eqngr permissive some_thm (t', some_abs)
haftmann@36272
   743
            ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
haftmann@24918
   744
            #>> (fn (t, ts) => t `$$ ts)
haftmann@36272
   745
and translate_eqn thy algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
haftmann@36272
   746
  fold_map (translate_term thy algbr eqngr permissive some_thm) args
haftmann@36272
   747
  ##>> translate_term thy algbr eqngr permissive some_thm (rhs, some_abs)
haftmann@35226
   748
  #>> rpair (some_thm, proper)
haftmann@37415
   749
and translate_eqns thy algbr eqngr permissive eqns prgrm =
haftmann@37415
   750
  prgrm |> fold_map (translate_eqn thy algbr eqngr permissive) eqns
haftmann@37415
   751
    handle PERMISSIVE () => ([], prgrm)
haftmann@36272
   752
and translate_const thy algbr eqngr permissive some_thm ((c, ty), some_abs) =
haftmann@30932
   753
  let
haftmann@37689
   754
    val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
haftmann@35226
   755
        andalso Code.is_abstr thy c
haftmann@37689
   756
        then translation_error thy permissive some_thm
haftmann@37689
   757
          "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
haftmann@37689
   758
      else ()
bulwahn@45862
   759
    val (annotate, ty') = dest_tagged_type ty
bulwahn@45660
   760
    val arg_typs = Sign.const_typargs thy (c, ty');
haftmann@32873
   761
    val sorts = Code_Preproc.sortargs eqngr c;
bulwahn@45660
   762
    val (function_typs, body_typ) = Term.strip_type ty';
haftmann@26972
   763
  in
haftmann@37689
   764
    ensure_const thy algbr eqngr permissive c
haftmann@37423
   765
    ##>> fold_map (translate_typ thy algbr eqngr permissive) arg_typs
haftmann@37423
   766
    ##>> fold_map (translate_dicts thy algbr eqngr permissive some_thm) (arg_typs ~~ sorts)
bulwahn@45657
   767
    ##>> fold_map (translate_typ thy algbr eqngr permissive) (body_typ :: function_typs)
bulwahn@45657
   768
    #>> (fn (((c, arg_typs), dss), body_typ :: function_typs) =>
bulwahn@45660
   769
      IConst (c, (((arg_typs, dss), (function_typs, body_typ)), annotate)))
haftmann@26972
   770
  end
haftmann@36272
   771
and translate_app_const thy algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
haftmann@36272
   772
  translate_const thy algbr eqngr permissive some_thm (c_ty, some_abs)
haftmann@36272
   773
  ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
haftmann@24918
   774
  #>> (fn (t, ts) => t `$$ ts)
haftmann@36272
   775
and translate_case thy algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
haftmann@24918
   776
  let
wenzelm@41093
   777
    fun arg_types num_args ty = fst (chop num_args (binder_types ty));
haftmann@31892
   778
    val tys = arg_types num_args (snd c_ty);
haftmann@29889
   779
    val ty = nth tys t_pos;
Andreas@48305
   780
    fun mk_constr NONE t = NONE
haftmann@48420
   781
      | mk_constr (SOME c) t =
haftmann@48420
   782
          let
haftmann@48420
   783
            val n = Code.args_number thy c;
haftmann@48420
   784
          in SOME ((c, arg_types n (fastype_of (untag_term t)) ---> ty), n) end;
haftmann@48420
   785
    val constrs =
haftmann@48420
   786
      if null case_pats then []
haftmann@48420
   787
      else map_filter I (map2 mk_constr case_pats (nth_drop t_pos ts));
haftmann@31892
   788
    fun casify naming constrs ty ts =
haftmann@24918
   789
      let
haftmann@31934
   790
        val undefineds = map_filter (lookup_const naming) (Code.undefineds thy);
haftmann@31934
   791
        fun collapse_clause vs_map ts body =
haftmann@31934
   792
          let
haftmann@31934
   793
          in case body
haftmann@31934
   794
           of IConst (c, _) => if member (op =) undefineds c
haftmann@31934
   795
                then []
haftmann@31934
   796
                else [(ts, body)]
haftmann@31934
   797
            | ICase (((IVar (SOME v), _), subclauses), _) =>
haftmann@31934
   798
                if forall (fn (pat', body') => exists_var pat' v
haftmann@31934
   799
                  orelse not (exists_var body' v)) subclauses
haftmann@31934
   800
                then case AList.lookup (op =) vs_map v
haftmann@31934
   801
                 of SOME i => maps (fn (pat', body') =>
haftmann@31934
   802
                      collapse_clause (AList.delete (op =) v vs_map)
haftmann@31934
   803
                        (nth_map i (K pat') ts) body') subclauses
haftmann@31934
   804
                  | NONE => [(ts, body)]
haftmann@31934
   805
                else [(ts, body)]
haftmann@31934
   806
            | _ => [(ts, body)]
haftmann@31934
   807
          end;
haftmann@31934
   808
        fun mk_clause mk tys t =
haftmann@31934
   809
          let
haftmann@31934
   810
            val (vs, body) = unfold_abs_eta tys t;
haftmann@31934
   811
            val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
haftmann@31934
   812
            val ts = map (IVar o fst) vs;
haftmann@31934
   813
          in map mk (collapse_clause vs_map ts body) end;
haftmann@31892
   814
        val t = nth ts t_pos;
haftmann@31892
   815
        val ts_clause = nth_drop t_pos ts;
haftmann@31934
   816
        val clauses = if null case_pats
haftmann@31934
   817
          then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
bulwahn@45657
   818
          else maps (fn ((constr as IConst (_, ((_, (tys, _)), _)), n), t) =>
haftmann@33956
   819
            mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
haftmann@48420
   820
              (constrs ~~ (map_filter (fn (NONE, _) => NONE | (SOME _, t) => SOME t)
haftmann@48420
   821
                (case_pats ~~ ts_clause)));
haftmann@31892
   822
      in ((t, ty), clauses) end;
haftmann@24918
   823
  in
haftmann@36272
   824
    translate_const thy algbr eqngr permissive some_thm (c_ty, NONE)
haftmann@36272
   825
    ##>> fold_map (fn (constr, n) => translate_const thy algbr eqngr permissive some_thm (constr, NONE)
haftmann@48420
   826
      #>> rpair n) constrs
haftmann@36272
   827
    ##>> translate_typ thy algbr eqngr permissive ty
haftmann@36272
   828
    ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) ts
haftmann@31892
   829
    #-> (fn (((t, constrs), ty), ts) =>
haftmann@31892
   830
      `(fn (_, (naming, _)) => ICase (casify naming constrs ty ts, t `$$ ts)))
haftmann@24918
   831
  end
haftmann@36272
   832
and translate_app_case thy algbr eqngr permissive some_thm (case_scheme as (num_args, _)) ((c, ty), ts) =
haftmann@29910
   833
  if length ts < num_args then
haftmann@29910
   834
    let
haftmann@29910
   835
      val k = length ts;
haftmann@33956
   836
      val tys = (take (num_args - k) o drop k o fst o strip_type) ty;
haftmann@29910
   837
      val ctxt = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
wenzelm@44211
   838
      val vs = Name.invent_names ctxt "a" tys;
haftmann@29910
   839
    in
haftmann@36272
   840
      fold_map (translate_typ thy algbr eqngr permissive) tys
haftmann@36272
   841
      ##>> translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts @ map Free vs)
haftmann@31888
   842
      #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
haftmann@29910
   843
    end
haftmann@29910
   844
  else if length ts > num_args then
haftmann@36272
   845
    translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), take num_args ts)
haftmann@36272
   846
    ##>> fold_map (translate_term thy algbr eqngr permissive some_thm o rpair NONE) (drop num_args ts)
haftmann@29910
   847
    #>> (fn (t, ts) => t `$$ ts)
haftmann@29910
   848
  else
haftmann@36272
   849
    translate_case thy algbr eqngr permissive some_thm case_scheme ((c, ty), ts)
haftmann@36272
   850
and translate_app thy algbr eqngr permissive some_thm (c_ty_ts as ((c, _), _), some_abs) =
haftmann@29910
   851
  case Code.get_case_scheme thy c
haftmann@36272
   852
   of SOME case_scheme => translate_app_case thy algbr eqngr permissive some_thm case_scheme c_ty_ts
haftmann@36272
   853
    | NONE => translate_app_const thy algbr eqngr permissive some_thm (c_ty_ts, some_abs)
haftmann@36272
   854
and translate_tyvar_sort thy (algbr as (proj_sort, _)) eqngr permissive (v, sort) =
haftmann@36272
   855
  fold_map (ensure_class thy algbr eqngr permissive) (proj_sort sort)
haftmann@30932
   856
  #>> (fn sort => (unprefix "'" v, sort))
haftmann@36272
   857
and translate_dicts thy (algbr as (proj_sort, algebra)) eqngr permissive some_thm (ty, sort) =
haftmann@30932
   858
  let
haftmann@41348
   859
    datatype typarg_witness =
haftmann@41366
   860
        Weakening of (class * class) list * plain_typarg_witness
haftmann@41366
   861
    and plain_typarg_witness =
haftmann@41366
   862
        Global of (class * string) * typarg_witness list list
haftmann@41366
   863
      | Local of string * (int * sort);
haftmann@41366
   864
    fun class_relation ((Weakening (classrels, x)), sub_class) super_class =
haftmann@41366
   865
      Weakening ((sub_class, super_class) :: classrels, x);
haftmann@41348
   866
    fun type_constructor (tyco, _) dss class =
haftmann@41366
   867
      Weakening ([], Global ((class, tyco), (map o map) fst dss));
haftmann@30932
   868
    fun type_variable (TFree (v, sort)) =
haftmann@30932
   869
      let
haftmann@30932
   870
        val sort' = proj_sort sort;
haftmann@41366
   871
      in map_index (fn (n, class) => (Weakening ([], Local (v, (n, sort'))), class)) sort' end;
haftmann@41348
   872
    val typarg_witnesses = Sorts.of_sort_derivation algebra
wenzelm@36102
   873
      {class_relation = K (Sorts.classrel_derivation algebra class_relation),
wenzelm@35972
   874
       type_constructor = type_constructor,
haftmann@37689
   875
       type_variable = type_variable} (ty, proj_sort sort)
haftmann@37689
   876
      handle Sorts.CLASS_ERROR e => not_wellsorted thy permissive some_thm ty sort e;
haftmann@41366
   877
    fun mk_dict (Weakening (classrels, x)) =
haftmann@41348
   878
          fold_map (ensure_classrel thy algbr eqngr permissive) classrels
haftmann@41366
   879
          ##>> mk_plain_dict x
haftmann@41366
   880
          #>> Dict 
haftmann@41366
   881
    and mk_plain_dict (Global (inst, dss)) =
haftmann@41366
   882
          ensure_inst thy algbr eqngr permissive inst
haftmann@41348
   883
          ##>> (fold_map o fold_map) mk_dict dss
haftmann@41366
   884
          #>> (fn (inst, dss) => Dict_Const (inst, dss))
haftmann@41366
   885
      | mk_plain_dict (Local (v, (n, sort))) =
haftmann@41366
   886
          pair (Dict_Var (unprefix "'" v, (n, length sort)))
haftmann@41348
   887
  in fold_map mk_dict typarg_witnesses end;
haftmann@24918
   888
haftmann@25969
   889
haftmann@27103
   890
(* store *)
haftmann@27103
   891
haftmann@34160
   892
structure Program = Code_Data
haftmann@27103
   893
(
haftmann@28663
   894
  type T = naming * program;
haftmann@28663
   895
  val empty = (empty_naming, Graph.empty);
haftmann@27103
   896
);
haftmann@27103
   897
haftmann@48442
   898
fun invoke_generation ignore_cache thy (algebra, eqngr) generate thing =
haftmann@39641
   899
  Program.change_yield (if ignore_cache then NONE else SOME thy)
haftmann@39641
   900
    (fn naming_program => (NONE, naming_program)
haftmann@48442
   901
      |> generate thy algebra eqngr thing
haftmann@48442
   902
      |-> (fn thing => fn (_, naming_program) => (thing, naming_program)));
haftmann@36272
   903
haftmann@27103
   904
haftmann@27103
   905
(* program generation *)
haftmann@27103
   906
haftmann@39727
   907
fun consts_program thy permissive consts =
haftmann@27103
   908
  let
haftmann@39727
   909
    fun project_consts consts (naming, program) =
haftmann@39727
   910
      if permissive then (consts, (naming, program))
wenzelm@47485
   911
      else (consts, (naming, Graph.restrict
haftmann@39727
   912
        (member (op =) (Graph.all_succs program consts)) program));
haftmann@32873
   913
    fun generate_consts thy algebra eqngr =
haftmann@36272
   914
      fold_map (ensure_const thy algebra eqngr permissive);
haftmann@27103
   915
  in
haftmann@39727
   916
    invoke_generation permissive thy (Code_Preproc.obtain false thy consts [])
haftmann@39727
   917
      generate_consts consts
haftmann@27103
   918
    |-> project_consts
haftmann@27103
   919
  end;
haftmann@27103
   920
haftmann@27103
   921
haftmann@27103
   922
(* value evaluation *)
haftmann@25969
   923
haftmann@32873
   924
fun ensure_value thy algbr eqngr t =
haftmann@24918
   925
  let
haftmann@24918
   926
    val ty = fastype_of t;
haftmann@24918
   927
    val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
haftmann@24918
   928
      o dest_TFree))) t [];
haftmann@46858
   929
    val t' = annotate thy algbr eqngr (Term.dummy_patternN, ty) [] t;
haftmann@24918
   930
    val stmt_value =
haftmann@36272
   931
      fold_map (translate_tyvar_sort thy algbr eqngr false) vs
haftmann@36272
   932
      ##>> translate_typ thy algbr eqngr false ty
bulwahn@45858
   933
      ##>> translate_term thy algbr eqngr false NONE (t', NONE)
haftmann@28663
   934
      #>> (fn ((vs, ty), t) => Fun
haftmann@37412
   935
        (Term.dummy_patternN, (((vs, ty), [(([], t), (NONE, true))]), NONE)));
haftmann@31063
   936
    fun term_value (dep, (naming, program1)) =
haftmann@26011
   937
      let
haftmann@37412
   938
        val Fun (_, ((vs_ty, [(([], t), _)]), _)) =
haftmann@28663
   939
          Graph.get_node program1 Term.dummy_patternN;
wenzelm@45218
   940
        val deps = Graph.immediate_succs program1 Term.dummy_patternN;
wenzelm@47542
   941
        val program2 = Graph.del_node Term.dummy_patternN program1;
haftmann@27103
   942
        val deps_all = Graph.all_succs program2 deps;
wenzelm@47485
   943
        val program3 = Graph.restrict (member (op =) deps_all) program2;
haftmann@31063
   944
      in (((naming, program3), ((vs_ty, t), deps)), (dep, (naming, program2))) end;
haftmann@24918
   945
  in
haftmann@28663
   946
    ensure_stmt ((K o K) NONE) pair stmt_value Term.dummy_patternN
haftmann@26011
   947
    #> snd
haftmann@31063
   948
    #> term_value
haftmann@24918
   949
  end;
haftmann@24918
   950
haftmann@39727
   951
fun original_sorts vs =
haftmann@39727
   952
  map (fn (v, _) => (v, (the o AList.lookup (op =) vs o prefix "'") v));
haftmann@39727
   953
haftmann@39727
   954
fun dynamic_evaluator thy evaluator algebra eqngr vs t =
haftmann@27103
   955
  let
haftmann@31063
   956
    val (((naming, program), (((vs', ty'), t'), deps)), _) =
haftmann@39641
   957
      invoke_generation false thy (algebra, eqngr) ensure_value t;
haftmann@39727
   958
  in evaluator naming program ((original_sorts vs vs', (vs', ty')), t') deps end;
haftmann@39715
   959
haftmann@41432
   960
fun dynamic_conv thy evaluator =
haftmann@41432
   961
  Code_Preproc.dynamic_conv thy (dynamic_evaluator thy evaluator);
haftmann@39715
   962
haftmann@41432
   963
fun dynamic_value thy postproc evaluator =
haftmann@41432
   964
  Code_Preproc.dynamic_value thy postproc (dynamic_evaluator thy evaluator);
haftmann@30942
   965
haftmann@41613
   966
fun lift_evaluation thy evaluation' algebra eqngr naming program vs t =
haftmann@41613
   967
  let
haftmann@41613
   968
    val (((_, program'), (((vs', ty'), t'), deps)), _) =
haftmann@41613
   969
      ensure_value thy algebra eqngr t (NONE, (naming, program));
haftmann@41613
   970
  in evaluation' ((original_sorts vs vs', (vs', ty')), t') deps end;
haftmann@41613
   971
haftmann@41613
   972
fun lift_evaluator thy evaluator' consts algebra eqngr =
haftmann@39727
   973
  let
haftmann@39727
   974
    fun generate_consts thy algebra eqngr =
haftmann@39727
   975
      fold_map (ensure_const thy algebra eqngr false);
haftmann@41613
   976
    val (consts', (naming, program)) =
haftmann@41613
   977
      invoke_generation true thy (algebra, eqngr) generate_consts consts;
haftmann@41613
   978
    val evaluation' = evaluator' naming program consts';
haftmann@41613
   979
  in lift_evaluation thy evaluation' algebra eqngr naming program end;
haftmann@39727
   980
haftmann@41613
   981
fun lift_evaluator_simple thy evaluator' consts algebra eqngr =
haftmann@39727
   982
  let
haftmann@41613
   983
    fun generate_consts thy algebra eqngr =
haftmann@41613
   984
      fold_map (ensure_const thy algebra eqngr false);
haftmann@41613
   985
    val (consts', (naming, program)) =
haftmann@41613
   986
      invoke_generation true thy (algebra, eqngr) generate_consts consts;
haftmann@41613
   987
  in evaluator' program end;
haftmann@39727
   988
haftmann@41432
   989
fun static_conv thy consts conv =
haftmann@41613
   990
  Code_Preproc.static_conv thy consts (lift_evaluator thy conv consts);
haftmann@38911
   991
haftmann@41432
   992
fun static_conv_simple thy consts conv =
haftmann@41613
   993
  Code_Preproc.static_conv thy consts (lift_evaluator_simple thy conv consts);
haftmann@38911
   994
haftmann@41432
   995
fun static_value thy postproc consts evaluator =
haftmann@41613
   996
  Code_Preproc.static_value thy postproc consts (lift_evaluator thy evaluator consts);
haftmann@39727
   997
haftmann@30942
   998
haftmann@30942
   999
(** diagnostic commands **)
haftmann@30942
  1000
haftmann@31036
  1001
fun read_const_exprs thy =
haftmann@31036
  1002
  let
haftmann@36272
  1003
    fun consts_of thy' = Symtab.fold (fn (c, (_, NONE)) => cons c | _ => I)
wenzelm@47876
  1004
      ((snd o #constants o Consts.dest o Sign.consts_of) thy') [];
haftmann@36272
  1005
    fun belongs_here thy' c = forall
haftmann@36272
  1006
      (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
haftmann@36272
  1007
    fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
haftmann@40959
  1008
    fun read_const_expr "_" = ([], consts_of thy)
haftmann@40959
  1009
      | read_const_expr s = if String.isSuffix "._" s
haftmann@40959
  1010
          then ([], consts_of_select (Context.this_theory thy (unsuffix "._" s)))
haftmann@31156
  1011
          else ([Code.read_const thy s], []);
haftmann@31036
  1012
  in pairself flat o split_list o map read_const_expr end;
haftmann@31036
  1013
haftmann@30942
  1014
fun code_depgr thy consts =
haftmann@30942
  1015
  let
haftmann@39641
  1016
    val (_, eqngr) = Code_Preproc.obtain true thy consts [];
haftmann@34160
  1017
    val all_consts = Graph.all_succs eqngr consts;
wenzelm@47485
  1018
  in Graph.restrict (member (op =) all_consts) eqngr end;
haftmann@30942
  1019
haftmann@31125
  1020
fun code_thms thy = Pretty.writeln o Code_Preproc.pretty thy o code_depgr thy;
haftmann@30942
  1021
haftmann@30942
  1022
fun code_deps thy consts =
haftmann@30942
  1023
  let
haftmann@30942
  1024
    val eqngr = code_depgr thy consts;
haftmann@30942
  1025
    val constss = Graph.strong_conn eqngr;
haftmann@30942
  1026
    val mapping = Symtab.empty |> fold (fn consts => fold (fn const =>
haftmann@30942
  1027
      Symtab.update (const, consts)) consts) constss;
haftmann@30942
  1028
    fun succs consts = consts
wenzelm@45218
  1029
      |> maps (Graph.immediate_succs eqngr)
haftmann@30942
  1030
      |> subtract (op =) consts
haftmann@30942
  1031
      |> map (the o Symtab.lookup mapping)
haftmann@30942
  1032
      |> distinct (op =);
haftmann@30942
  1033
    val conn = [] |> fold (fn consts => cons (consts, succs consts)) constss;
haftmann@31156
  1034
    fun namify consts = map (Code.string_of_const thy) consts
haftmann@30942
  1035
      |> commas;
haftmann@30942
  1036
    val prgr = map (fn (consts, constss) =>
haftmann@30942
  1037
      { name = namify consts, ID = namify consts, dir = "", unfold = true,
haftmann@30942
  1038
        path = "", parents = map namify constss }) conn;
haftmann@30942
  1039
  in Present.display_graph prgr end;
haftmann@30942
  1040
haftmann@30942
  1041
local
haftmann@30942
  1042
haftmann@31036
  1043
fun code_thms_cmd thy = code_thms thy o op @ o read_const_exprs thy;
haftmann@31036
  1044
fun code_deps_cmd thy = code_deps thy o op @ o read_const_exprs thy;
haftmann@30942
  1045
haftmann@30942
  1046
in
haftmann@30942
  1047
haftmann@30942
  1048
val _ =
wenzelm@47836
  1049
  Outer_Syntax.improper_command @{command_spec "code_thms"}
wenzelm@47836
  1050
    "print system of code equations for code"
wenzelm@36970
  1051
    (Scan.repeat1 Parse.term_group
haftmann@30942
  1052
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
  1053
        o Toplevel.keep ((fn thy => code_thms_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
  1054
haftmann@30942
  1055
val _ =
wenzelm@47836
  1056
  Outer_Syntax.improper_command @{command_spec "code_deps"}
wenzelm@47836
  1057
    "visualize dependencies of code equations for code"
wenzelm@36970
  1058
    (Scan.repeat1 Parse.term_group
haftmann@30942
  1059
      >> (fn cs => Toplevel.no_timing o Toplevel.unknown_theory
haftmann@30942
  1060
        o Toplevel.keep ((fn thy => code_deps_cmd thy cs) o Toplevel.theory_of)));
haftmann@30942
  1061
haftmann@30942
  1062
end;
haftmann@27103
  1063
haftmann@24219
  1064
end; (*struct*)
haftmann@24219
  1065
haftmann@24219
  1066
haftmann@28054
  1067
structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;