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