src/Tools/Code/code_thingol.ML
author wenzelm
Mon Mar 25 17:21:26 2019 +0100 (3 months ago)
changeset 69981 3dced198b9ec
parent 69645 e4e5bc6ac214
permissions -rw-r--r--
more strict AFP properties;
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@55147
    11
infixr 3 `->;
haftmann@31724
    12
infixr 3 `|=>;
haftmann@31724
    13
infixr 3 `|==>;
haftmann@24219
    14
haftmann@24219
    15
signature BASIC_CODE_THINGOL =
haftmann@24219
    16
sig
haftmann@24219
    17
  type vname = string;
haftmann@24219
    18
  datatype dict =
haftmann@55147
    19
      Dict of (class * class) list * plain_dict
haftmann@41118
    20
  and plain_dict = 
haftmann@55147
    21
      Dict_Const of (string * class) * dict list list
haftmann@63303
    22
    | Dict_Var of { var: vname, index: int, length: int, class: class, unique: bool };
haftmann@24219
    23
  datatype itype =
haftmann@24219
    24
      `%% of string * itype list
haftmann@24219
    25
    | ITyVar of vname;
haftmann@55150
    26
  type const = { sym: Code_Symbol.T, typargs: itype list, dicts: dict list list,
haftmann@58397
    27
    dom: itype list, annotation: itype option };
haftmann@24219
    28
  datatype iterm =
haftmann@24591
    29
      IConst of const
haftmann@31889
    30
    | IVar of vname option
haftmann@24219
    31
    | `$ of iterm * iterm
haftmann@31888
    32
    | `|=> of (vname option * itype) * iterm
haftmann@48072
    33
    | ICase of { term: iterm, typ: itype, clauses: (iterm * iterm) list, primitive: iterm };
haftmann@55147
    34
  val `-> : itype * itype -> itype;
haftmann@24219
    35
  val `$$ : iterm * iterm list -> iterm;
haftmann@31888
    36
  val `|==> : (vname option * itype) list * iterm -> iterm;
haftmann@24219
    37
  type typscheme = (vname * sort) list * itype;
haftmann@24219
    38
end;
haftmann@24219
    39
haftmann@24219
    40
signature CODE_THINGOL =
haftmann@24219
    41
sig
haftmann@28663
    42
  include BASIC_CODE_THINGOL
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@65483
    50
  val split_let_no_pat: iterm -> (((string option * itype) * iterm) * iterm) option
haftmann@28663
    51
  val unfold_let: iterm -> ((iterm * itype) * iterm) list * iterm
haftmann@65483
    52
  val unfold_let_no_pat: iterm -> ((string option * itype) * iterm) list * iterm
haftmann@31889
    53
  val split_pat_abs: iterm -> ((iterm * itype) * iterm) option
haftmann@31889
    54
  val unfold_pat_abs: iterm -> (iterm * itype) list * iterm
haftmann@31049
    55
  val unfold_const_app: iterm -> (const * iterm list) option
haftmann@32909
    56
  val is_IVar: iterm -> bool
haftmann@41782
    57
  val is_IAbs: iterm -> bool
haftmann@31049
    58
  val eta_expand: int -> const * iterm list -> iterm
haftmann@41100
    59
  val contains_dict_var: iterm -> bool
haftmann@63303
    60
  val unambiguous_dictss: dict list list -> bool
haftmann@55150
    61
  val add_constsyms: iterm -> Code_Symbol.T list -> Code_Symbol.T list
haftmann@32917
    62
  val add_tyconames: iterm -> string list -> string list
haftmann@28663
    63
  val fold_varnames: (string -> 'a -> 'a) -> iterm -> 'a -> 'a
haftmann@28663
    64
haftmann@24918
    65
  datatype stmt =
haftmann@55147
    66
      NoStmt
haftmann@55147
    67
    | Fun of (typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option
haftmann@55147
    68
    | Datatype of vname list *
haftmann@55147
    69
        ((string * vname list (*type argument wrt. canonical order*)) * itype list) list
haftmann@55147
    70
    | Datatypecons of string
haftmann@55147
    71
    | Class of vname * ((class * class) list * (string * itype) list)
haftmann@24219
    72
    | Classrel of class * class
haftmann@55147
    73
    | Classparam of class
haftmann@48072
    74
    | Classinst of { class: string, tyco: string, vs: (vname * sort) list,
haftmann@55147
    75
        superinsts: (class * dict list list) list,
haftmann@52519
    76
        inst_params: ((string * (const * int)) * (thm * bool)) list,
haftmann@52519
    77
        superinst_params: ((string * (const * int)) * (thm * bool)) list };
haftmann@55147
    78
  type program = stmt Code_Symbol.Graph.T
haftmann@54889
    79
  val unimplemented: program -> string list
haftmann@55147
    80
  val implemented_deps: program -> string list
haftmann@28663
    81
  val map_terms_bottom_up: (iterm -> iterm) -> iterm -> iterm
haftmann@28663
    82
  val map_terms_stmt: (iterm -> iterm) -> stmt -> stmt
haftmann@55150
    83
  val is_constr: program -> Code_Symbol.T -> bool
haftmann@37440
    84
  val is_case: stmt -> bool
haftmann@55757
    85
  val group_stmts: Proof.context -> program
haftmann@55150
    86
    -> ((Code_Symbol.T * stmt) list * (Code_Symbol.T * stmt) list
haftmann@55150
    87
      * ((Code_Symbol.T * stmt) list * (Code_Symbol.T * stmt) list)) list
haftmann@24219
    88
haftmann@55757
    89
  val read_const_exprs: Proof.context -> string list -> string list
haftmann@63159
    90
  val consts_program: Proof.context -> string list -> program
haftmann@55757
    91
  val dynamic_conv: Proof.context -> (program
haftmann@56969
    92
    -> typscheme * iterm -> Code_Symbol.T list -> conv)
haftmann@38672
    93
    -> conv
haftmann@55757
    94
  val dynamic_value: Proof.context -> ((term -> term) -> 'a -> 'a) -> (program
haftmann@56969
    95
    -> term -> typscheme * iterm -> Code_Symbol.T list -> 'a)
haftmann@28663
    96
    -> term -> 'a
haftmann@63156
    97
  val static_conv_thingol: { ctxt: Proof.context, consts: string list }
haftmann@56973
    98
    -> ({ program: program, deps: string list }
haftmann@56973
    99
      -> Proof.context -> typscheme * iterm -> Code_Symbol.T list -> conv)
haftmann@55757
   100
    -> Proof.context -> conv
haftmann@63156
   101
  val static_conv_isa: { ctxt: Proof.context, consts: string list }
haftmann@56920
   102
    -> (program -> Proof.context -> term -> conv)
haftmann@55757
   103
    -> Proof.context -> conv
haftmann@56973
   104
  val static_value: { ctxt: Proof.context, lift_postproc: ((term -> term) -> 'a -> 'a), consts: string list }
haftmann@56973
   105
    -> ({ program: program, deps: string list }
haftmann@56969
   106
      -> Proof.context -> term -> typscheme * iterm -> Code_Symbol.T list -> 'a)
haftmann@55757
   107
    -> Proof.context -> term -> 'a
haftmann@24219
   108
end;
haftmann@24219
   109
haftmann@63160
   110
structure Code_Thingol : CODE_THINGOL =
haftmann@24219
   111
struct
haftmann@24219
   112
haftmann@55150
   113
open Basic_Code_Symbol;
haftmann@55150
   114
haftmann@24219
   115
(** auxiliary **)
haftmann@24219
   116
haftmann@24219
   117
fun unfoldl dest x =
haftmann@24219
   118
  case dest x
haftmann@24219
   119
   of NONE => (x, [])
haftmann@24219
   120
    | SOME (x1, x2) =>
haftmann@24219
   121
        let val (x', xs') = unfoldl dest x1 in (x', xs' @ [x2]) end;
haftmann@24219
   122
haftmann@24219
   123
fun unfoldr dest x =
haftmann@24219
   124
  case dest x
haftmann@24219
   125
   of NONE => ([], x)
haftmann@24219
   126
    | SOME (x1, x2) =>
haftmann@48072
   127
        let val (xs', x') = unfoldr dest x2 in (x1 :: xs', x') end;
haftmann@24219
   128
haftmann@24219
   129
haftmann@29962
   130
(** language core - types, terms **)
haftmann@24219
   131
haftmann@24219
   132
type vname = string;
haftmann@24219
   133
haftmann@24219
   134
datatype dict =
haftmann@55147
   135
    Dict of (class * class) list * plain_dict
haftmann@41118
   136
and plain_dict = 
haftmann@55147
   137
    Dict_Const of (string * class) * dict list list
haftmann@63303
   138
  | Dict_Var of { var: vname, index: int, length: int, class: class, unique: bool };
haftmann@24219
   139
haftmann@24219
   140
datatype itype =
haftmann@24219
   141
    `%% of string * itype list
haftmann@24219
   142
  | ITyVar of vname;
haftmann@24219
   143
haftmann@55147
   144
fun ty1 `-> ty2 = "fun" `%% [ty1, ty2];
haftmann@55147
   145
haftmann@55147
   146
val unfold_fun = unfoldr
haftmann@55147
   147
  (fn "fun" `%% [ty1, ty2] => SOME (ty1, ty2)
haftmann@55147
   148
    | _ => NONE);
haftmann@55147
   149
haftmann@55147
   150
fun unfold_fun_n n ty =
haftmann@55147
   151
  let
haftmann@55147
   152
    val (tys1, ty1) = unfold_fun ty;
haftmann@55147
   153
    val (tys3, tys2) = chop n tys1;
haftmann@55147
   154
    val ty3 = Library.foldr (op `->) (tys2, ty1);
haftmann@55147
   155
  in (tys3, ty3) end;
haftmann@55147
   156
haftmann@55150
   157
type const = { sym: Code_Symbol.T, typargs: itype list, dicts: dict list list,
haftmann@58397
   158
  dom: itype list, annotation: itype option };
haftmann@24591
   159
haftmann@24219
   160
datatype iterm =
haftmann@24591
   161
    IConst of const
haftmann@31889
   162
  | IVar of vname option
haftmann@24219
   163
  | `$ of iterm * iterm
haftmann@31888
   164
  | `|=> of (vname option * itype) * iterm
haftmann@48072
   165
  | ICase of { term: iterm, typ: itype, clauses: (iterm * iterm) list, primitive: iterm };
haftmann@24219
   166
    (*see also signature*)
haftmann@24219
   167
haftmann@32909
   168
fun is_IVar (IVar _) = true
haftmann@32909
   169
  | is_IVar _ = false;
haftmann@32909
   170
haftmann@41782
   171
fun is_IAbs (_ `|=> _) = true
haftmann@41782
   172
  | is_IAbs _ = false;
haftmann@41782
   173
haftmann@24219
   174
val op `$$ = Library.foldl (op `$);
haftmann@31724
   175
val op `|==> = Library.foldr (op `|=>);
haftmann@24219
   176
haftmann@24219
   177
val unfold_app = unfoldl
haftmann@24219
   178
  (fn op `$ t => SOME t
haftmann@24219
   179
    | _ => NONE);
haftmann@24219
   180
haftmann@31874
   181
val unfold_abs = unfoldr
haftmann@31874
   182
  (fn op `|=> t => SOME t
haftmann@24219
   183
    | _ => NONE);
haftmann@24219
   184
haftmann@24219
   185
val split_let = 
haftmann@48072
   186
  (fn ICase { term = t, typ = ty, clauses = [(p, body)], ... } => SOME (((p, ty), t), body)
haftmann@24219
   187
    | _ => NONE);
haftmann@24219
   188
haftmann@65483
   189
val split_let_no_pat = 
haftmann@65483
   190
  (fn ICase { term = t, typ = ty, clauses = [(IVar v, body)], ... } => SOME (((v, ty), t), body)
haftmann@65483
   191
    | _ => NONE);
haftmann@65483
   192
haftmann@24219
   193
val unfold_let = unfoldr split_let;
haftmann@24219
   194
haftmann@65483
   195
val unfold_let_no_pat = unfoldr split_let_no_pat;
haftmann@65483
   196
haftmann@24219
   197
fun unfold_const_app t =
haftmann@24219
   198
 case unfold_app t
haftmann@24219
   199
  of (IConst c, ts) => SOME (c, ts)
haftmann@24219
   200
   | _ => NONE;
haftmann@24219
   201
haftmann@32917
   202
fun fold_constexprs f =
haftmann@32917
   203
  let
haftmann@32917
   204
    fun fold' (IConst c) = f c
haftmann@32917
   205
      | fold' (IVar _) = I
haftmann@32917
   206
      | fold' (t1 `$ t2) = fold' t1 #> fold' t2
haftmann@32917
   207
      | fold' (_ `|=> t) = fold' t
haftmann@48072
   208
      | fold' (ICase { term = t, clauses = clauses, ... }) = fold' t
haftmann@48072
   209
          #> fold (fn (p, body) => fold' p #> fold' body) clauses
haftmann@32917
   210
  in fold' end;
haftmann@32917
   211
haftmann@55147
   212
val add_constsyms = fold_constexprs (fn { sym, ... } => insert (op =) sym);
haftmann@32917
   213
haftmann@32917
   214
fun add_tycos (tyco `%% tys) = insert (op =) tyco #> fold add_tycos tys
haftmann@32917
   215
  | add_tycos (ITyVar _) = I;
haftmann@32917
   216
haftmann@48072
   217
val add_tyconames = fold_constexprs (fn { typargs = tys, ... } => fold add_tycos tys);
haftmann@24219
   218
haftmann@24219
   219
fun fold_varnames f =
haftmann@24219
   220
  let
haftmann@59541
   221
    fun fold_aux add_vars f =
haftmann@31935
   222
      let
haftmann@31935
   223
        fun fold_term _ (IConst _) = I
haftmann@31935
   224
          | fold_term vs (IVar (SOME v)) = if member (op =) vs v then I else f v
haftmann@31935
   225
          | fold_term _ (IVar NONE) = I
haftmann@31935
   226
          | fold_term vs (t1 `$ t2) = fold_term vs t1 #> fold_term vs t2
haftmann@31935
   227
          | fold_term vs ((SOME v, _) `|=> t) = fold_term (insert (op =) v vs) t
haftmann@31935
   228
          | fold_term vs ((NONE, _) `|=> t) = fold_term vs t
haftmann@59541
   229
          | fold_term vs (ICase { term = t, clauses = clauses, ... }) =
haftmann@59541
   230
              fold_term vs t #> fold (fold_clause vs) clauses
haftmann@59541
   231
        and fold_clause vs (p, t) = fold_term (add_vars p vs) t;
haftmann@59541
   232
      in fold_term [] end
haftmann@59541
   233
    fun add_vars t = fold_aux add_vars (insert (op =)) t;
haftmann@59541
   234
  in fold_aux add_vars f end;
haftmann@24219
   235
haftmann@31935
   236
fun exists_var t v = fold_varnames (fn w => fn b => v = w orelse b) t false;
haftmann@31874
   237
haftmann@31889
   238
fun split_pat_abs ((NONE, ty) `|=> t) = SOME ((IVar NONE, ty), t)
haftmann@31888
   239
  | split_pat_abs ((SOME v, ty) `|=> t) = SOME (case t
haftmann@48072
   240
     of ICase { term = IVar (SOME w), clauses = [(p, body)], ... } =>
haftmann@48072
   241
          if v = w andalso (exists_var p v orelse not (exists_var body v))
haftmann@48072
   242
          then ((p, ty), body)
haftmann@31889
   243
          else ((IVar (SOME v), ty), t)
haftmann@31889
   244
      | _ => ((IVar (SOME v), ty), t))
haftmann@31888
   245
  | split_pat_abs _ = NONE;
haftmann@31874
   246
haftmann@31874
   247
val unfold_pat_abs = unfoldr split_pat_abs;
haftmann@24219
   248
haftmann@31890
   249
fun unfold_abs_eta [] t = ([], t)
haftmann@31890
   250
  | unfold_abs_eta (_ :: tys) (v_ty `|=> t) =
haftmann@31890
   251
      let
haftmann@31890
   252
        val (vs_tys, t') = unfold_abs_eta tys t;
haftmann@31890
   253
      in (v_ty :: vs_tys, t') end
haftmann@31892
   254
  | unfold_abs_eta tys t =
haftmann@31890
   255
      let
haftmann@31890
   256
        val ctxt = fold_varnames Name.declare t Name.context;
wenzelm@43329
   257
        val vs_tys = (map o apfst) SOME (Name.invent_names ctxt "a" tys);
haftmann@31890
   258
      in (vs_tys, t `$$ map (IVar o fst) vs_tys) end;
haftmann@31890
   259
haftmann@55147
   260
fun eta_expand k (const as { dom = tys, ... }, ts) =
haftmann@24219
   261
  let
haftmann@24219
   262
    val j = length ts;
haftmann@24219
   263
    val l = k - j;
haftmann@37841
   264
    val _ = if l > length tys
haftmann@55147
   265
      then error "Impossible eta-expansion" else ();
haftmann@55147
   266
    val vars = (fold o fold_varnames) Name.declare ts Name.context;
haftmann@31889
   267
    val vs_tys = (map o apfst) SOME
haftmann@55147
   268
      (Name.invent_names vars "a" ((take l o drop j) tys));
haftmann@48072
   269
  in vs_tys `|==> IConst const `$$ ts @ map (IVar o fst) vs_tys end;
haftmann@24219
   270
haftmann@63303
   271
fun exists_dict_var f (Dict (_, d)) = exists_plain_dict_var_pred f d
haftmann@63303
   272
and exists_plain_dict_var_pred f (Dict_Const (_, dss)) = exists_dictss_var f dss
haftmann@63303
   273
  | exists_plain_dict_var_pred f (Dict_Var x) = f x
haftmann@63303
   274
and exists_dictss_var f dss = (exists o exists) (exists_dict_var f) dss;
haftmann@63303
   275
haftmann@63303
   276
fun contains_dict_var (IConst { dicts = dss, ... }) = exists_dictss_var (K true) dss
haftmann@63303
   277
  | contains_dict_var (IVar _) = false
haftmann@63303
   278
  | contains_dict_var (t1 `$ t2) = contains_dict_var t1 orelse contains_dict_var t2
haftmann@63303
   279
  | contains_dict_var (_ `|=> t) = contains_dict_var t
haftmann@63303
   280
  | contains_dict_var (ICase { primitive = t, ... }) = contains_dict_var t;
haftmann@63303
   281
haftmann@63303
   282
val unambiguous_dictss = not o exists_dictss_var (fn { unique, ... } => not unique);
haftmann@25621
   283
haftmann@25621
   284
haftmann@27103
   285
(** statements, abstract programs **)
haftmann@24219
   286
haftmann@24219
   287
type typscheme = (vname * sort) list * itype;
haftmann@37447
   288
datatype stmt =
haftmann@55147
   289
    NoStmt
haftmann@55147
   290
  | Fun of (typscheme * ((iterm list * iterm) * (thm option * bool)) list) * thm option
haftmann@55147
   291
  | Datatype of vname list * ((string * vname list) * itype list) list
haftmann@55147
   292
  | Datatypecons of string
haftmann@55147
   293
  | Class of vname * ((class * class) list * (string * itype) list)
haftmann@24219
   294
  | Classrel of class * class
haftmann@55147
   295
  | Classparam of class
haftmann@48072
   296
  | Classinst of { class: string, tyco: string, vs: (vname * sort) list,
haftmann@55147
   297
      superinsts: (class * dict list list) list,
haftmann@52519
   298
      inst_params: ((string * (const * int)) * (thm * bool)) list,
haftmann@52519
   299
      superinst_params: ((string * (const * int)) * (thm * bool)) list };
haftmann@24219
   300
haftmann@55147
   301
type program = stmt Code_Symbol.Graph.T;
haftmann@24219
   302
haftmann@54889
   303
fun unimplemented program =
haftmann@55150
   304
  Code_Symbol.Graph.fold (fn (Constant c, (NoStmt, _)) => cons c | _ => I) program [];
haftmann@55147
   305
haftmann@55147
   306
fun implemented_deps program =
haftmann@55147
   307
  Code_Symbol.Graph.keys program
haftmann@55150
   308
  |> subtract (op =) (Code_Symbol.Graph.all_preds program (map Constant (unimplemented program)))
haftmann@55150
   309
  |> map_filter (fn Constant c => SOME c | _ => NONE);
haftmann@24219
   310
haftmann@27711
   311
fun map_terms_bottom_up f (t as IConst _) = f t
haftmann@27711
   312
  | map_terms_bottom_up f (t as IVar _) = f t
haftmann@27711
   313
  | map_terms_bottom_up f (t1 `$ t2) = f
haftmann@27711
   314
      (map_terms_bottom_up f t1 `$ map_terms_bottom_up f t2)
haftmann@31724
   315
  | map_terms_bottom_up f ((v, ty) `|=> t) = f
haftmann@31724
   316
      ((v, ty) `|=> map_terms_bottom_up f t)
haftmann@48072
   317
  | map_terms_bottom_up f (ICase { term = t, typ = ty, clauses = clauses, primitive = t0 }) = f
haftmann@48072
   318
      (ICase { term = map_terms_bottom_up f t, typ = ty,
wenzelm@59058
   319
        clauses = (map o apply2) (map_terms_bottom_up f) clauses,
haftmann@48072
   320
        primitive = map_terms_bottom_up f t0 });
haftmann@27711
   321
haftmann@37448
   322
fun map_classparam_instances_as_term f =
haftmann@52519
   323
  (map o apfst o apsnd o apfst) (fn const => case f (IConst const) of IConst const' => const')
haftmann@37448
   324
haftmann@55147
   325
fun map_terms_stmt f NoStmt = NoStmt
haftmann@55147
   326
  | map_terms_stmt f (Fun ((tysm, eqs), case_cong)) = Fun ((tysm, (map o apfst)
haftmann@55147
   327
      (fn (ts, t) => (map f ts, f t)) eqs), case_cong)
haftmann@27711
   328
  | map_terms_stmt f (stmt as Datatype _) = stmt
haftmann@27711
   329
  | map_terms_stmt f (stmt as Datatypecons _) = stmt
haftmann@27711
   330
  | map_terms_stmt f (stmt as Class _) = stmt
haftmann@27711
   331
  | map_terms_stmt f (stmt as Classrel _) = stmt
haftmann@27711
   332
  | map_terms_stmt f (stmt as Classparam _) = stmt
haftmann@48072
   333
  | map_terms_stmt f (Classinst { class, tyco, vs, superinsts,
haftmann@48072
   334
      inst_params, superinst_params }) =
haftmann@48072
   335
        Classinst { class = class, tyco = tyco, vs = vs, superinsts = superinsts,
haftmann@48072
   336
          inst_params = map_classparam_instances_as_term f inst_params,
haftmann@48072
   337
          superinst_params = map_classparam_instances_as_term f superinst_params };
haftmann@27711
   338
haftmann@55147
   339
fun is_constr program sym = case Code_Symbol.Graph.get_node program sym
haftmann@24219
   340
 of Datatypecons _ => true
haftmann@24219
   341
  | _ => false;
haftmann@24219
   342
haftmann@55147
   343
fun is_case (Fun (_, SOME _)) = true
haftmann@37440
   344
  | is_case _ = false;
haftmann@37440
   345
haftmann@37440
   346
fun linear_stmts program =
haftmann@55147
   347
  rev (Code_Symbol.Graph.strong_conn program)
haftmann@55147
   348
  |> map (AList.make (Code_Symbol.Graph.get_node program));
haftmann@37440
   349
haftmann@55757
   350
fun group_stmts ctxt program =
haftmann@32895
   351
  let
haftmann@32895
   352
    fun is_fun (_, Fun _) = true | is_fun _ = false;
haftmann@32895
   353
    fun is_datatypecons (_, Datatypecons _) = true | is_datatypecons _ = false;
haftmann@32895
   354
    fun is_datatype (_, Datatype _) = true | is_datatype _ = false;
haftmann@32895
   355
    fun is_class (_, Class _) = true | is_class _ = false;
haftmann@32895
   356
    fun is_classrel (_, Classrel _) = true | is_classrel _ = false;
haftmann@32895
   357
    fun is_classparam (_, Classparam _) = true | is_classparam _ = false;
haftmann@32895
   358
    fun is_classinst (_, Classinst _) = true | is_classinst _ = false;
haftmann@32895
   359
    fun group stmts =
haftmann@32895
   360
      if forall (is_datatypecons orf is_datatype) stmts
haftmann@32895
   361
      then (filter is_datatype stmts, [], ([], []))
haftmann@32895
   362
      else if forall (is_class orf is_classrel orf is_classparam) stmts
haftmann@32895
   363
      then ([], filter is_class stmts, ([], []))
haftmann@32895
   364
      else if forall (is_fun orf is_classinst) stmts
haftmann@32895
   365
      then ([], [], List.partition is_fun stmts)
haftmann@52138
   366
      else error ("Illegal mutual dependencies: " ^ (commas
haftmann@55757
   367
        o map (Code_Symbol.quote ctxt o fst)) stmts);
haftmann@32895
   368
  in
haftmann@37440
   369
    linear_stmts program
haftmann@32895
   370
    |> map group
haftmann@32895
   371
  end;
haftmann@32895
   372
haftmann@24219
   373
haftmann@27103
   374
(** translation kernel **)
haftmann@24219
   375
haftmann@28724
   376
(* generic mechanisms *)
haftmann@28724
   377
haftmann@55190
   378
fun ensure_stmt symbolize generate x (deps, program) =
haftmann@24219
   379
  let
haftmann@55147
   380
    val sym = symbolize x;
haftmann@55190
   381
    val add_dep = case deps of [] => I
haftmann@55190
   382
      | dep :: _ => Code_Symbol.Graph.add_edge (dep, sym);
haftmann@47576
   383
  in
haftmann@55147
   384
    if can (Code_Symbol.Graph.get_node program) sym
haftmann@47576
   385
    then
haftmann@47576
   386
      program
haftmann@55147
   387
      |> add_dep
haftmann@55190
   388
      |> pair deps
haftmann@55147
   389
      |> pair x
haftmann@47576
   390
    else
haftmann@47576
   391
      program
haftmann@55147
   392
      |> Code_Symbol.Graph.default_node (sym, NoStmt)
haftmann@55147
   393
      |> add_dep
haftmann@55190
   394
      |> curry generate (sym :: deps)
haftmann@47576
   395
      ||> snd
haftmann@55147
   396
      |-> (fn stmt => (Code_Symbol.Graph.map_node sym) (K stmt))
haftmann@55190
   397
      |> pair deps
haftmann@55147
   398
      |> pair x
haftmann@24219
   399
  end;
haftmann@24219
   400
haftmann@36272
   401
exception PERMISSIVE of unit;
haftmann@36272
   402
haftmann@56920
   403
fun translation_error ctxt permissive some_thm deps msg sub_msg =
haftmann@36272
   404
  if permissive
haftmann@36272
   405
  then raise PERMISSIVE ()
wenzelm@42385
   406
  else
wenzelm@42385
   407
    let
haftmann@55190
   408
      val thm_msg =
wenzelm@61268
   409
        Option.map (fn thm => "in code equation " ^ Thm.string_of_thm ctxt thm) some_thm;
haftmann@55190
   410
      val dep_msg = if null (tl deps) then NONE
haftmann@55190
   411
        else SOME ("with dependency "
haftmann@55190
   412
          ^ space_implode " -> " (map (Code_Symbol.quote ctxt) (rev deps)));
haftmann@55190
   413
      val thm_dep_msg = case (thm_msg, dep_msg)
haftmann@55190
   414
       of (SOME thm_msg, SOME dep_msg) => "\n(" ^ thm_msg ^ ",\n" ^ dep_msg ^ ")"
haftmann@55190
   415
        | (SOME thm_msg, NONE) => "\n(" ^ thm_msg ^ ")"
haftmann@55190
   416
        | (NONE, SOME dep_msg) => "\n(" ^ dep_msg ^ ")"
haftmann@55190
   417
        | (NONE, NONE) => ""
haftmann@55190
   418
    in error (msg ^ thm_dep_msg ^ ":\n" ^ sub_msg) end;
haftmann@37698
   419
haftmann@48074
   420
fun maybe_permissive f prgrm =
haftmann@48074
   421
  f prgrm |>> SOME handle PERMISSIVE () => (NONE, prgrm);
haftmann@48074
   422
haftmann@56920
   423
fun not_wellsorted ctxt permissive some_thm deps ty sort e =
haftmann@37698
   424
  let
wenzelm@61262
   425
    val err_class = Sorts.class_error (Context.Proof ctxt) e;
wenzelm@42385
   426
    val err_typ =
haftmann@55757
   427
      "Type " ^ Syntax.string_of_typ ctxt ty ^ " not of sort " ^
haftmann@55757
   428
        Syntax.string_of_sort ctxt sort;
wenzelm@42385
   429
  in
haftmann@56920
   430
    translation_error ctxt permissive some_thm deps
haftmann@55190
   431
      "Wellsortedness error" (err_typ ^ "\n" ^ err_class)
wenzelm@42385
   432
  end;
haftmann@26972
   433
haftmann@47555
   434
bulwahn@44790
   435
(* inference of type annotations for disambiguation with type classes *)
bulwahn@44790
   436
bulwahn@45000
   437
fun mk_tagged_type (true, T) = Type ("", [T])
haftmann@47555
   438
  | mk_tagged_type (false, T) = T;
bulwahn@45000
   439
bulwahn@44998
   440
fun dest_tagged_type (Type ("", [T])) = (true, T)
haftmann@47555
   441
  | dest_tagged_type T = (false, T);
bulwahn@44998
   442
haftmann@47555
   443
val untag_term = map_types (snd o dest_tagged_type);
bulwahn@44998
   444
bulwahn@45000
   445
fun tag_term (proj_sort, _) eqngr =
bulwahn@44997
   446
  let
haftmann@47555
   447
    val has_sort_constraints = exists (not o null) o map proj_sort o Code_Preproc.sortargs eqngr;
haftmann@47576
   448
    fun tag (Const (_, T')) (Const (c, T)) =
bulwahn@45000
   449
        Const (c,
bulwahn@45000
   450
          mk_tagged_type (not (null (Term.add_tvarsT T' [])) andalso has_sort_constraints c, T))
bulwahn@45000
   451
      | tag (t1 $ u1) (t $ u) = tag t1 t $ tag u1 u
bulwahn@45000
   452
      | tag (Abs (_, _, t1)) (Abs (x, T, t)) = Abs (x, T, tag t1 t)
bulwahn@45000
   453
      | tag (Free _) (t as Free _) = t
bulwahn@45000
   454
      | tag (Var _) (t as Var _) = t
haftmann@47555
   455
      | tag (Bound _) (t as Bound _) = t;
haftmann@55757
   456
  in tag end
bulwahn@44790
   457
haftmann@55757
   458
fun annotate ctxt algbr eqngr (c, ty) args rhs =
bulwahn@44790
   459
  let
haftmann@55757
   460
    val erase = map_types (fn _ => Type_Infer.anyT []);
haftmann@55757
   461
    val reinfer = singleton (Type_Infer_Context.infer_types ctxt);
haftmann@55757
   462
    val lhs = list_comb (Const (c, ty), map (map_types Type.strip_sorts o fst) args);
haftmann@55757
   463
    val reinferred_rhs = snd (Logic.dest_equals (reinfer (Logic.mk_equals (lhs, erase rhs))));
haftmann@55757
   464
  in tag_term algbr eqngr reinferred_rhs rhs end
haftmann@55757
   465
haftmann@55757
   466
fun annotate_eqns ctxt algbr eqngr (c, ty) eqns =
haftmann@55757
   467
  let
haftmann@55757
   468
    val ctxt' = ctxt |> Proof_Context.theory_of |> Proof_Context.init_global
haftmann@55757
   469
      |> Config.put Type_Infer_Context.const_sorts false;
haftmann@55757
   470
      (*avoid spurious fixed variables: there is no eigen context for equations*)
bulwahn@44790
   471
  in
haftmann@55757
   472
    map (apfst (fn (args, (rhs, some_abs)) => (args,
haftmann@55757
   473
      (annotate ctxt' algbr eqngr (c, ty) args rhs, some_abs)))) eqns
haftmann@55757
   474
  end;
haftmann@47555
   475
haftmann@55189
   476
(* abstract dictionary construction *)
haftmann@55189
   477
haftmann@55189
   478
datatype typarg_witness =
haftmann@55189
   479
    Weakening of (class * class) list * plain_typarg_witness
haftmann@55189
   480
and plain_typarg_witness =
haftmann@55189
   481
    Global of (string * class) * typarg_witness list list
haftmann@63303
   482
  | Local of { var: string, index: int, sort: sort, unique: bool };
haftmann@63303
   483
haftmann@63303
   484
fun brand_unique unique (w as Global _) = w
haftmann@63303
   485
  | brand_unique unique (Local { var, index, sort, unique = _ }) =
haftmann@63303
   486
      Local { var = var, index = index, sort = sort, unique = unique };
haftmann@55189
   487
haftmann@55757
   488
fun construct_dictionaries ctxt (proj_sort, algebra) permissive some_thm (ty, sort) (deps, program) =
haftmann@55189
   489
  let
haftmann@63303
   490
    fun class_relation unique (Weakening (classrels, x), sub_class) super_class =
haftmann@63303
   491
      Weakening ((sub_class, super_class) :: classrels, brand_unique unique x);
haftmann@55189
   492
    fun type_constructor (tyco, _) dss class =
haftmann@55189
   493
      Weakening ([], Global ((tyco, class), (map o map) fst dss));
haftmann@55189
   494
    fun type_variable (TFree (v, sort)) =
haftmann@55189
   495
      let
haftmann@55189
   496
        val sort' = proj_sort sort;
haftmann@63303
   497
      in map_index (fn (n, class) => (Weakening ([], Local
haftmann@63303
   498
        { var = v, index = n, sort = sort', unique = true }), class)) sort'
haftmann@63303
   499
      end;
haftmann@55189
   500
    val typarg_witnesses = Sorts.of_sort_derivation algebra
haftmann@63303
   501
      {class_relation = fn _ => fn unique =>
haftmann@63303
   502
         Sorts.classrel_derivation algebra (class_relation unique),
haftmann@55189
   503
       type_constructor = type_constructor,
haftmann@55189
   504
       type_variable = type_variable} (ty, proj_sort sort)
haftmann@56920
   505
      handle Sorts.CLASS_ERROR e => not_wellsorted ctxt permissive some_thm deps ty sort e;
haftmann@55190
   506
  in (typarg_witnesses, (deps, program)) end;
haftmann@55189
   507
haftmann@55189
   508
haftmann@28724
   509
(* translation *)
haftmann@28724
   510
haftmann@55757
   511
fun ensure_tyco ctxt algbr eqngr permissive tyco =
haftmann@30932
   512
  let
haftmann@55757
   513
    val thy = Proof_Context.theory_of ctxt;
haftmann@40726
   514
    val ((vs, cos), _) = Code.get_type thy tyco;
haftmann@30932
   515
    val stmt_datatype =
haftmann@55757
   516
      fold_map (translate_tyvar_sort ctxt algbr eqngr permissive) vs
haftmann@48003
   517
      #>> map fst
haftmann@40726
   518
      ##>> fold_map (fn (c, (vs, tys)) =>
haftmann@55757
   519
        ensure_const ctxt algbr eqngr permissive c
haftmann@40726
   520
        ##>> pair (map (unprefix "'" o fst) vs)
haftmann@55757
   521
        ##>> fold_map (translate_typ ctxt algbr eqngr permissive) tys) cos
haftmann@55147
   522
      #>> Datatype;
haftmann@55150
   523
  in ensure_stmt Type_Constructor stmt_datatype tyco end
haftmann@55757
   524
and ensure_const ctxt algbr eqngr permissive c =
haftmann@30932
   525
  let
haftmann@55757
   526
    val thy = Proof_Context.theory_of ctxt;
haftmann@30932
   527
    fun stmt_datatypecons tyco =
haftmann@55757
   528
      ensure_tyco ctxt algbr eqngr permissive tyco
haftmann@55147
   529
      #>> Datatypecons;
haftmann@30932
   530
    fun stmt_classparam class =
haftmann@55757
   531
      ensure_class ctxt algbr eqngr permissive class
haftmann@55147
   532
      #>> Classparam;
haftmann@54889
   533
    fun stmt_fun cert = case Code.equations_of_cert thy cert
haftmann@55147
   534
     of (_, NONE) => pair NoStmt
haftmann@54889
   535
      | ((vs, ty), SOME eqns) =>
haftmann@54889
   536
          let
haftmann@55757
   537
            val eqns' = annotate_eqns ctxt algbr eqngr (c, ty) eqns
haftmann@54889
   538
            val some_case_cong = Code.get_case_cong thy c;
haftmann@54889
   539
          in
haftmann@55757
   540
            fold_map (translate_tyvar_sort ctxt algbr eqngr permissive) vs
haftmann@55757
   541
            ##>> translate_typ ctxt algbr eqngr permissive ty
haftmann@55757
   542
            ##>> translate_eqns ctxt algbr eqngr permissive eqns'
haftmann@54889
   543
            #>>
haftmann@55147
   544
             (fn (_, NONE) => NoStmt
haftmann@55147
   545
               | (tyscm, SOME eqns) => Fun ((tyscm, eqns), some_case_cong))
haftmann@54889
   546
          end;
haftmann@35299
   547
    val stmt_const = case Code.get_type_of_constr_or_abstr thy c
haftmann@35226
   548
     of SOME (tyco, _) => stmt_datatypecons tyco
wenzelm@51685
   549
      | NONE => (case Axclass.class_of_param thy c
haftmann@30932
   550
         of SOME class => stmt_classparam class
haftmann@34891
   551
          | NONE => stmt_fun (Code_Preproc.cert eqngr c))
haftmann@55150
   552
  in ensure_stmt Constant stmt_const c end
haftmann@55757
   553
and ensure_class ctxt (algbr as (_, algebra)) eqngr permissive class =
haftmann@24918
   554
  let
haftmann@55757
   555
    val thy = Proof_Context.theory_of ctxt;
haftmann@37384
   556
    val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
wenzelm@51685
   557
    val cs = #params (Axclass.get_info thy class);
haftmann@24918
   558
    val stmt_class =
haftmann@55147
   559
      fold_map (fn super_class =>
haftmann@55757
   560
        ensure_classrel ctxt algbr eqngr permissive (class, super_class)) super_classes
haftmann@55757
   561
      ##>> fold_map (fn (c, ty) => ensure_const ctxt algbr eqngr permissive c
haftmann@55757
   562
        ##>> translate_typ ctxt algbr eqngr permissive ty) cs
haftmann@55147
   563
      #>> (fn info => Class (unprefix "'" Name.aT, info))
haftmann@55150
   564
  in ensure_stmt Type_Class stmt_class class end
haftmann@55757
   565
and ensure_classrel ctxt algbr eqngr permissive (sub_class, super_class) =
haftmann@24918
   566
  let
haftmann@24918
   567
    val stmt_classrel =
haftmann@55757
   568
      ensure_class ctxt algbr eqngr permissive sub_class
haftmann@55757
   569
      ##>> ensure_class ctxt algbr eqngr permissive super_class
haftmann@24918
   570
      #>> Classrel;
haftmann@55150
   571
  in ensure_stmt Class_Relation stmt_classrel (sub_class, super_class) end
haftmann@55757
   572
and ensure_inst ctxt (algbr as (_, algebra)) eqngr permissive (tyco, class) =
haftmann@24918
   573
  let
haftmann@55757
   574
    val thy = Proof_Context.theory_of ctxt;
haftmann@37384
   575
    val super_classes = (Sorts.minimize_sort algebra o Sorts.super_classes algebra) class;
wenzelm@51685
   576
    val these_class_params = these o try (#params o Axclass.get_info thy);
haftmann@48072
   577
    val class_params = these_class_params class;
haftmann@48072
   578
    val superclass_params = maps these_class_params
haftmann@37448
   579
      ((Sorts.complete_sort algebra o Sorts.super_classes algebra) class);
wenzelm@43329
   580
    val vs = Name.invent_names Name.context "'a" (Sorts.mg_domain algebra tyco [class]);
haftmann@24918
   581
    val sorts' = Sorts.mg_domain (Sign.classes_of thy) tyco [class];
haftmann@24918
   582
    val vs' = map2 (fn (v, sort1) => fn sort2 => (v,
haftmann@24918
   583
      Sorts.inter_sort (Sign.classes_of thy) (sort1, sort2))) vs sorts';
haftmann@24918
   584
    val arity_typ = Type (tyco, map TFree vs);
haftmann@24918
   585
    val arity_typ' = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) vs');
haftmann@37384
   586
    fun translate_super_instance super_class =
haftmann@55757
   587
      ensure_class ctxt algbr eqngr permissive super_class
haftmann@55757
   588
      ##>> translate_dicts ctxt algbr eqngr permissive NONE (arity_typ, [super_class])
haftmann@55147
   589
      #>> (fn (super_class, [Dict ([], Dict_Const (_, dss))]) => (super_class, dss));
haftmann@37384
   590
    fun translate_classparam_instance (c, ty) =
haftmann@24918
   591
      let
haftmann@37384
   592
        val raw_const = Const (c, map_type_tfree (K arity_typ') ty);
haftmann@52519
   593
        val dom_length = length (fst (strip_type ty))
wenzelm@63073
   594
        val thm = Axclass.unoverload_conv ctxt (Thm.cterm_of ctxt raw_const);
haftmann@37384
   595
        val const = (apsnd Logic.unvarifyT_global o dest_Const o snd
haftmann@24918
   596
          o Logic.dest_equals o Thm.prop_of) thm;
haftmann@24918
   597
      in
haftmann@55757
   598
        ensure_const ctxt algbr eqngr permissive c
haftmann@55757
   599
        ##>> translate_const ctxt algbr eqngr permissive (SOME thm) (const, NONE)
haftmann@52519
   600
        #>> (fn (c, IConst const') => ((c, (const', dom_length)), (thm, true)))
haftmann@24918
   601
      end;
haftmann@24918
   602
    val stmt_inst =
haftmann@55757
   603
      ensure_class ctxt algbr eqngr permissive class
haftmann@55757
   604
      ##>> ensure_tyco ctxt algbr eqngr permissive tyco
haftmann@55757
   605
      ##>> fold_map (translate_tyvar_sort ctxt algbr eqngr permissive) vs
haftmann@37384
   606
      ##>> fold_map translate_super_instance super_classes
haftmann@48072
   607
      ##>> fold_map translate_classparam_instance class_params
haftmann@48072
   608
      ##>> fold_map translate_classparam_instance superclass_params
haftmann@48072
   609
      #>> (fn (((((class, tyco), vs), superinsts), inst_params), superinst_params) =>
haftmann@48072
   610
          Classinst { class = class, tyco = tyco, vs = vs,
haftmann@48072
   611
            superinsts = superinsts, inst_params = inst_params, superinst_params = superinst_params });
haftmann@55150
   612
  in ensure_stmt Class_Instance stmt_inst (tyco, class) end
haftmann@55757
   613
and translate_typ ctxt algbr eqngr permissive (TFree (v, _)) =
haftmann@30932
   614
      pair (ITyVar (unprefix "'" v))
haftmann@55757
   615
  | translate_typ ctxt algbr eqngr permissive (Type (tyco, tys)) =
haftmann@55757
   616
      ensure_tyco ctxt algbr eqngr permissive tyco
haftmann@55757
   617
      ##>> fold_map (translate_typ ctxt algbr eqngr permissive) tys
haftmann@30932
   618
      #>> (fn (tyco, tys) => tyco `%% tys)
haftmann@55757
   619
and translate_term ctxt algbr eqngr permissive some_thm (Const (c, ty), some_abs) =
haftmann@55757
   620
      translate_app ctxt algbr eqngr permissive some_thm (((c, ty), []), some_abs)
haftmann@55757
   621
  | translate_term ctxt algbr eqngr permissive some_thm (Free (v, _), some_abs) =
haftmann@31889
   622
      pair (IVar (SOME v))
haftmann@55757
   623
  | translate_term ctxt algbr eqngr permissive some_thm (Abs (v, ty, t), some_abs) =
haftmann@24918
   624
      let
haftmann@56811
   625
        val (v', t') = Syntax_Trans.variant_abs (Name.desymbolize (SOME false) v, ty, t);
haftmann@32273
   626
        val v'' = if member (op =) (Term.add_free_names t' []) v'
haftmann@32273
   627
          then SOME v' else NONE
haftmann@24918
   628
      in
haftmann@55757
   629
        translate_typ ctxt algbr eqngr permissive ty
haftmann@55757
   630
        ##>> translate_term ctxt algbr eqngr permissive some_thm (t', some_abs)
haftmann@32273
   631
        #>> (fn (ty, t) => (v'', ty) `|=> t)
haftmann@24918
   632
      end
haftmann@55757
   633
  | translate_term ctxt algbr eqngr permissive some_thm (t as _ $ _, some_abs) =
haftmann@24918
   634
      case strip_comb t
haftmann@24918
   635
       of (Const (c, ty), ts) =>
haftmann@55757
   636
            translate_app ctxt algbr eqngr permissive some_thm (((c, ty), ts), some_abs)
haftmann@24918
   637
        | (t', ts) =>
haftmann@55757
   638
            translate_term ctxt algbr eqngr permissive some_thm (t', some_abs)
haftmann@55757
   639
            ##>> fold_map (translate_term ctxt algbr eqngr permissive some_thm o rpair NONE) ts
haftmann@24918
   640
            #>> (fn (t, ts) => t `$$ ts)
haftmann@55757
   641
and translate_eqn ctxt algbr eqngr permissive ((args, (rhs, some_abs)), (some_thm, proper)) =
haftmann@55757
   642
  fold_map (translate_term ctxt algbr eqngr permissive some_thm) args
haftmann@55757
   643
  ##>> translate_term ctxt algbr eqngr permissive some_thm (rhs, some_abs)
haftmann@35226
   644
  #>> rpair (some_thm, proper)
haftmann@55757
   645
and translate_eqns ctxt algbr eqngr permissive eqns =
haftmann@55757
   646
  maybe_permissive (fold_map (translate_eqn ctxt algbr eqngr permissive) eqns)
haftmann@55757
   647
and translate_const ctxt algbr eqngr permissive some_thm ((c, ty), some_abs) (deps, program) =
haftmann@30932
   648
  let
haftmann@55757
   649
    val thy = Proof_Context.theory_of ctxt;
haftmann@37698
   650
    val _ = if (case some_abs of NONE => true | SOME abs => not (c = abs))
haftmann@35226
   651
        andalso Code.is_abstr thy c
haftmann@56920
   652
        then translation_error ctxt permissive some_thm deps
haftmann@37698
   653
          "Abstraction violation" ("constant " ^ Code.string_of_const thy c)
haftmann@37698
   654
      else ()
haftmann@55757
   655
  in translate_const_proper ctxt algbr eqngr permissive some_thm (c, ty) (deps, program) end
haftmann@55757
   656
and translate_const_proper ctxt algbr eqngr permissive some_thm (c, ty) =
haftmann@55190
   657
  let
haftmann@55757
   658
    val thy = Proof_Context.theory_of ctxt;
haftmann@48072
   659
    val (annotate, ty') = dest_tagged_type ty;
haftmann@48072
   660
    val typargs = Sign.const_typargs thy (c, ty');
haftmann@32873
   661
    val sorts = Code_Preproc.sortargs eqngr c;
haftmann@48072
   662
    val (dom, range) = Term.strip_type ty';
haftmann@26972
   663
  in
haftmann@55757
   664
    ensure_const ctxt algbr eqngr permissive c
haftmann@55757
   665
    ##>> fold_map (translate_typ ctxt algbr eqngr permissive) typargs
haftmann@55757
   666
    ##>> fold_map (translate_dicts ctxt algbr eqngr permissive some_thm) (typargs ~~ sorts)
haftmann@58397
   667
    ##>> fold_map (translate_typ ctxt algbr eqngr permissive) (ty' :: dom)
haftmann@58397
   668
    #>> (fn (((c, typargs), dss), annotation :: dom) =>
haftmann@55150
   669
      IConst { sym = Constant c, typargs = typargs, dicts = dss,
haftmann@58397
   670
        dom = dom, annotation =
haftmann@58397
   671
          if annotate then SOME annotation else NONE })
haftmann@26972
   672
  end
haftmann@55757
   673
and translate_app_const ctxt algbr eqngr permissive some_thm ((c_ty, ts), some_abs) =
haftmann@55757
   674
  translate_const ctxt algbr eqngr permissive some_thm (c_ty, some_abs)
haftmann@55757
   675
  ##>> fold_map (translate_term ctxt algbr eqngr permissive some_thm o rpair NONE) ts
haftmann@24918
   676
  #>> (fn (t, ts) => t `$$ ts)
haftmann@55757
   677
and translate_case ctxt algbr eqngr permissive some_thm (num_args, (t_pos, case_pats)) (c_ty, ts) =
haftmann@24918
   678
  let
haftmann@55757
   679
    val thy = Proof_Context.theory_of ctxt;
wenzelm@40844
   680
    fun arg_types num_args ty = fst (chop num_args (binder_types ty));
haftmann@31892
   681
    val tys = arg_types num_args (snd c_ty);
haftmann@29952
   682
    val ty = nth tys t_pos;
Andreas@47437
   683
    fun mk_constr NONE t = NONE
haftmann@47555
   684
      | mk_constr (SOME c) t =
haftmann@47555
   685
          let
haftmann@47555
   686
            val n = Code.args_number thy c;
haftmann@47555
   687
          in SOME ((c, arg_types n (fastype_of (untag_term t)) ---> ty), n) end;
haftmann@47555
   688
    val constrs =
haftmann@47555
   689
      if null case_pats then []
haftmann@47555
   690
      else map_filter I (map2 mk_constr case_pats (nth_drop t_pos ts));
haftmann@59544
   691
    fun disjunctive_varnames ts =
haftmann@59544
   692
      let
haftmann@59544
   693
        val vs = (fold o fold_varnames) (insert (op =)) ts [];
haftmann@59544
   694
      in fn pat => null (inter (op =) vs (fold_varnames (insert (op =)) pat [])) end;
haftmann@59544
   695
    fun purge_unused_vars_in t =
haftmann@59544
   696
      let
haftmann@59544
   697
        val vs = fold_varnames (insert (op =)) t [];
haftmann@59544
   698
      in
haftmann@59544
   699
        map_terms_bottom_up (fn IVar (SOME v) =>
haftmann@59544
   700
          IVar (if member (op =) vs v then SOME v else NONE) | t => t)
haftmann@59544
   701
      end;
haftmann@59544
   702
    fun collapse_clause vs_map ts body =
haftmann@59544
   703
      case body
haftmann@66189
   704
       of IConst { sym = Constant c, ... } => if Code.is_undefined thy c
haftmann@59544
   705
            then []
haftmann@59544
   706
            else [(ts, body)]
haftmann@59544
   707
        | ICase { term = IVar (SOME v), clauses = clauses, ... } =>
haftmann@59544
   708
            if forall (fn (pat', body') => exists_var pat' v
haftmann@59544
   709
              orelse not (exists_var body' v)) clauses
haftmann@59544
   710
              andalso forall (disjunctive_varnames ts o fst) clauses
haftmann@59544
   711
            then case AList.lookup (op =) vs_map v
haftmann@59544
   712
             of SOME i => maps (fn (pat', body') =>
haftmann@59544
   713
                  collapse_clause (AList.delete (op =) v vs_map)
haftmann@59544
   714
                    (nth_map i (K pat') ts |> map (purge_unused_vars_in body')) body') clauses
haftmann@59544
   715
              | NONE => [(ts, body)]
haftmann@59544
   716
            else [(ts, body)]
haftmann@59544
   717
        | _ => [(ts, body)];
haftmann@59544
   718
    fun mk_clause mk tys t =
haftmann@59544
   719
      let
haftmann@59544
   720
        val (vs, body) = unfold_abs_eta tys t;
haftmann@59544
   721
        val vs_map = fold_index (fn (i, (SOME v, _)) => cons (v, i) | _ => I) vs [];
haftmann@59544
   722
        val ts = map (IVar o fst) vs;
haftmann@59544
   723
      in map mk (collapse_clause vs_map ts body) end;
haftmann@55147
   724
    fun casify constrs ty t_app ts =
haftmann@24918
   725
      let
haftmann@31892
   726
        val t = nth ts t_pos;
haftmann@31892
   727
        val ts_clause = nth_drop t_pos ts;
haftmann@31935
   728
        val clauses = if null case_pats
haftmann@31935
   729
          then mk_clause (fn ([t], body) => (t, body)) [ty] (the_single ts_clause)
haftmann@48072
   730
          else maps (fn ((constr as IConst { dom = tys, ... }, n), t) =>
haftmann@33957
   731
            mk_clause (fn (ts, body) => (constr `$$ ts, body)) (take n tys) t)
haftmann@47555
   732
              (constrs ~~ (map_filter (fn (NONE, _) => NONE | (SOME _, t) => SOME t)
haftmann@47555
   733
                (case_pats ~~ ts_clause)));
haftmann@48072
   734
      in ICase { term = t, typ = ty, clauses = clauses, primitive = t_app `$$ ts } end;
haftmann@24918
   735
  in
haftmann@55757
   736
    translate_const ctxt algbr eqngr permissive some_thm (c_ty, NONE)
haftmann@55757
   737
    ##>> fold_map (fn (constr, n) => translate_const ctxt algbr eqngr permissive some_thm (constr, NONE)
haftmann@47555
   738
      #>> rpair n) constrs
haftmann@55757
   739
    ##>> translate_typ ctxt algbr eqngr permissive ty
haftmann@55757
   740
    ##>> fold_map (translate_term ctxt algbr eqngr permissive some_thm o rpair NONE) ts
haftmann@55147
   741
    #>> (fn (((t, constrs), ty), ts) =>
haftmann@55147
   742
      casify constrs ty t ts)
haftmann@24918
   743
  end
haftmann@66189
   744
and translate_app_case ctxt algbr eqngr permissive some_thm (case_schema as (num_args, _)) ((c, ty), ts) =
haftmann@29973
   745
  if length ts < num_args then
haftmann@29973
   746
    let
haftmann@29973
   747
      val k = length ts;
haftmann@33957
   748
      val tys = (take (num_args - k) o drop k o fst o strip_type) ty;
haftmann@55757
   749
      val names = (fold o fold_aterms) Term.declare_term_frees ts Name.context;
haftmann@55757
   750
      val vs = Name.invent_names names "a" tys;
haftmann@29973
   751
    in
haftmann@55757
   752
      fold_map (translate_typ ctxt algbr eqngr permissive) tys
haftmann@66189
   753
      ##>> translate_case ctxt algbr eqngr permissive some_thm case_schema ((c, ty), ts @ map Free vs)
haftmann@31888
   754
      #>> (fn (tys, t) => map2 (fn (v, _) => pair (SOME v)) vs tys `|==> t)
haftmann@29973
   755
    end
haftmann@29973
   756
  else if length ts > num_args then
haftmann@66189
   757
    translate_case ctxt algbr eqngr permissive some_thm case_schema ((c, ty), take num_args ts)
haftmann@55757
   758
    ##>> fold_map (translate_term ctxt algbr eqngr permissive some_thm o rpair NONE) (drop num_args ts)
haftmann@29973
   759
    #>> (fn (t, ts) => t `$$ ts)
haftmann@29973
   760
  else
haftmann@66189
   761
    translate_case ctxt algbr eqngr permissive some_thm case_schema ((c, ty), ts)
haftmann@55757
   762
and translate_app ctxt algbr eqngr permissive some_thm (c_ty_ts as ((c, _), _), some_abs) =
haftmann@66189
   763
  case Code.get_case_schema (Proof_Context.theory_of ctxt) c
haftmann@66189
   764
   of SOME case_schema => translate_app_case ctxt algbr eqngr permissive some_thm case_schema c_ty_ts
haftmann@55757
   765
    | NONE => translate_app_const ctxt algbr eqngr permissive some_thm (c_ty_ts, some_abs)
haftmann@55757
   766
and translate_tyvar_sort ctxt (algbr as (proj_sort, _)) eqngr permissive (v, sort) =
haftmann@55757
   767
  fold_map (ensure_class ctxt algbr eqngr permissive) (proj_sort sort)
haftmann@30932
   768
  #>> (fn sort => (unprefix "'" v, sort))
haftmann@55757
   769
and translate_dicts ctxt algbr eqngr permissive some_thm (ty, sort) =
haftmann@30932
   770
  let
haftmann@63303
   771
    fun mk_dict (Weakening (classrels, d)) =
haftmann@55757
   772
          fold_map (ensure_classrel ctxt algbr eqngr permissive) classrels
haftmann@63303
   773
          ##>> mk_plain_dict d
haftmann@41118
   774
          #>> Dict 
haftmann@41118
   775
    and mk_plain_dict (Global (inst, dss)) =
haftmann@55757
   776
          ensure_inst ctxt algbr eqngr permissive inst
haftmann@41100
   777
          ##>> (fold_map o fold_map) mk_dict dss
haftmann@63303
   778
          #>> Dict_Const
haftmann@63303
   779
      | mk_plain_dict (Local { var, index, sort, unique }) =
haftmann@63303
   780
          ensure_class ctxt algbr eqngr permissive (nth sort index)
haftmann@63303
   781
          #>> (fn class => Dict_Var { var = unprefix "'" var, index = index,
haftmann@63303
   782
            length = length sort, class = class, unique = unique })
haftmann@55189
   783
  in
haftmann@55757
   784
    construct_dictionaries ctxt algbr permissive some_thm (ty, sort)
haftmann@55189
   785
    #-> (fn typarg_witnesses => fold_map mk_dict typarg_witnesses)
haftmann@55189
   786
  end;
haftmann@24918
   787
haftmann@25969
   788
haftmann@27103
   789
(* store *)
haftmann@27103
   790
haftmann@34173
   791
structure Program = Code_Data
haftmann@27103
   792
(
haftmann@55147
   793
  type T = program;
haftmann@55147
   794
  val empty = Code_Symbol.Graph.empty;
haftmann@27103
   795
);
haftmann@27103
   796
haftmann@63160
   797
fun invoke_generation ignore_cache ctxt generate thing =
haftmann@63159
   798
  Program.change_yield
haftmann@63159
   799
    (if ignore_cache then NONE else SOME (Proof_Context.theory_of ctxt))
haftmann@55190
   800
    (fn program => ([], program)
haftmann@63160
   801
      |> generate thing
haftmann@55147
   802
      |-> (fn thing => fn (_, program) => (thing, program)));
haftmann@36272
   803
haftmann@27103
   804
haftmann@27103
   805
(* program generation *)
haftmann@27103
   806
haftmann@63175
   807
fun check_abstract_constructors thy consts =
haftmann@63175
   808
  case filter (Code.is_abstr thy) consts of
haftmann@63175
   809
    [] => ()
haftmann@63175
   810
  | abstrs => error ("Cannot export abstract constructor(s): "
haftmann@63175
   811
      ^ commas (map (Code.string_of_const thy) abstrs));
haftmann@63175
   812
haftmann@63164
   813
fun invoke_generation_for_consts ctxt { ignore_cache, permissive } { algebra, eqngr } consts =
haftmann@63175
   814
  let
haftmann@63175
   815
    val thy = Proof_Context.theory_of ctxt;
haftmann@63175
   816
    val _ = if permissive then ()
haftmann@63175
   817
      else check_abstract_constructors thy consts;
haftmann@63175
   818
  in
haftmann@63175
   819
    Code_Preproc.timed "translating program" #ctxt
haftmann@63175
   820
    (fn { ctxt, algebra, eqngr, consts } => invoke_generation ignore_cache ctxt
haftmann@63175
   821
      (fold_map (ensure_const ctxt algebra eqngr permissive)) consts)
haftmann@63175
   822
      { ctxt = ctxt, algebra = algebra, eqngr = eqngr, consts = consts }
haftmann@63175
   823
  end;
haftmann@63160
   824
haftmann@63160
   825
fun invoke_generation_for_consts' ctxt ignore_cache_and_permissive consts =
haftmann@63160
   826
  invoke_generation_for_consts ctxt
haftmann@63160
   827
    { ignore_cache = ignore_cache_and_permissive, permissive = ignore_cache_and_permissive }
haftmann@63164
   828
    (Code_Preproc.obtain ignore_cache_and_permissive
haftmann@63164
   829
      { ctxt = ctxt, consts = consts, terms = []}) consts
haftmann@63160
   830
  |> snd;
haftmann@55188
   831
haftmann@63160
   832
fun invoke_generation_for_consts'' ctxt algebra_eqngr =
haftmann@63160
   833
  invoke_generation_for_consts ctxt
haftmann@63160
   834
    { ignore_cache = true, permissive = false }
haftmann@63160
   835
    algebra_eqngr
haftmann@63160
   836
  #> (fn (deps, program) => { deps = deps, program = program });
haftmann@55188
   837
haftmann@63160
   838
fun consts_program_permissive ctxt =
haftmann@63160
   839
  invoke_generation_for_consts' ctxt true;
haftmann@63160
   840
haftmann@63160
   841
fun consts_program ctxt consts =
haftmann@55188
   842
  let
haftmann@55188
   843
    fun project program = Code_Symbol.Graph.restrict
haftmann@55188
   844
      (member (op =) (Code_Symbol.Graph.all_succs program
haftmann@55188
   845
        (map Constant consts))) program;
haftmann@55188
   846
  in
haftmann@63160
   847
    invoke_generation_for_consts' ctxt false consts
haftmann@55147
   848
    |> project
haftmann@27103
   849
  end;
haftmann@27103
   850
haftmann@27103
   851
haftmann@27103
   852
(* value evaluation *)
haftmann@25969
   853
haftmann@56969
   854
fun ensure_value ctxt algbr eqngr t =
haftmann@24918
   855
  let
haftmann@24918
   856
    val ty = fastype_of t;
haftmann@56969
   857
    val vs = fold_term_types (K (fold_atyps (insert (eq_fst op =)
haftmann@24918
   858
      o dest_TFree))) t [];
wenzelm@69593
   859
    val t' = annotate ctxt algbr eqngr (\<^const_name>\<open>Pure.dummy_pattern\<close>, ty) [] t;
wenzelm@69593
   860
    val dummy_constant = Constant \<^const_name>\<open>Pure.dummy_pattern\<close>;
haftmann@24918
   861
    val stmt_value =
haftmann@55757
   862
      fold_map (translate_tyvar_sort ctxt algbr eqngr false) vs
haftmann@55757
   863
      ##>> translate_typ ctxt algbr eqngr false ty
haftmann@55757
   864
      ##>> translate_term ctxt algbr eqngr false NONE (t', NONE)
haftmann@28663
   865
      #>> (fn ((vs, ty), t) => Fun
haftmann@55147
   866
        (((vs, ty), [(([], t), (NONE, true))]), NONE));
haftmann@56920
   867
    fun term_value (_, program1) =
haftmann@25969
   868
      let
haftmann@56969
   869
        val Fun ((vs_ty, [(([], t), _)]), _) =
haftmann@55147
   870
          Code_Symbol.Graph.get_node program1 dummy_constant;
haftmann@55190
   871
        val deps' = Code_Symbol.Graph.immediate_succs program1 dummy_constant;
haftmann@55147
   872
        val program2 = Code_Symbol.Graph.del_node dummy_constant program1;
haftmann@55190
   873
        val deps_all = Code_Symbol.Graph.all_succs program2 deps';
haftmann@55147
   874
        val program3 = Code_Symbol.Graph.restrict (member (op =) deps_all) program2;
haftmann@56969
   875
       in ((program3, ((vs_ty, t), deps')), (deps', program2)) end;
haftmann@26011
   876
  in
wenzelm@69593
   877
    ensure_stmt Constant stmt_value \<^const_name>\<open>Pure.dummy_pattern\<close>
haftmann@26011
   878
    #> snd
haftmann@31063
   879
    #> term_value
haftmann@26011
   880
  end;
haftmann@24219
   881
haftmann@64957
   882
fun dynamic_evaluation comp ctxt algebra eqngr t =
haftmann@30942
   883
  let
haftmann@56969
   884
    val ((program, (vs_ty_t', deps)), _) =
haftmann@63164
   885
      Code_Preproc.timed "translating term" #ctxt
haftmann@63164
   886
      (fn { ctxt, algebra, eqngr, t } =>
haftmann@63164
   887
        invoke_generation false ctxt (ensure_value ctxt algebra eqngr) t)
haftmann@63164
   888
        { ctxt = ctxt, algebra = algebra, eqngr = eqngr, t = t };
haftmann@64957
   889
  in comp program t vs_ty_t' deps end;
haftmann@30942
   890
haftmann@55757
   891
fun dynamic_conv ctxt conv =
haftmann@63157
   892
  Code_Preproc.dynamic_conv ctxt
haftmann@63157
   893
    (dynamic_evaluation (fn program => fn _ => conv program) ctxt);
haftmann@30942
   894
haftmann@63157
   895
fun dynamic_value ctxt postproc comp =
haftmann@63157
   896
  Code_Preproc.dynamic_value ctxt postproc
haftmann@63157
   897
    (dynamic_evaluation comp ctxt);
haftmann@41365
   898
haftmann@63160
   899
fun static_evaluation ctxt consts algebra_eqngr static_eval =
haftmann@63160
   900
  static_eval (invoke_generation_for_consts'' ctxt algebra_eqngr consts);
haftmann@63160
   901
haftmann@63160
   902
fun static_evaluation_thingol ctxt consts (algebra_eqngr as { algebra, eqngr }) static_eval =
haftmann@41365
   903
  let
haftmann@63160
   904
    fun evaluation program dynamic_eval ctxt t =
haftmann@63157
   905
      let
haftmann@63157
   906
        val ((_, ((vs_ty', t'), deps)), _) =
haftmann@63164
   907
          Code_Preproc.timed "translating term" #ctxt
haftmann@63164
   908
          (fn { ctxt, t } =>
haftmann@63164
   909
            ensure_value ctxt algebra eqngr t ([], program))
haftmann@63164
   910
            { ctxt = ctxt, t = t };
haftmann@63157
   911
      in dynamic_eval ctxt t (vs_ty', t') deps end;
haftmann@63157
   912
  in
haftmann@63160
   913
    static_evaluation ctxt consts algebra_eqngr (fn program_deps =>
haftmann@63160
   914
      evaluation (#program program_deps) (static_eval program_deps))
haftmann@63157
   915
  end;
haftmann@63157
   916
haftmann@63160
   917
fun static_evaluation_isa ctxt consts algebra_eqngr static_eval =
haftmann@63160
   918
  static_evaluation ctxt consts algebra_eqngr (fn program_deps =>
haftmann@63160
   919
    (static_eval (#program program_deps)));
haftmann@39487
   920
haftmann@63156
   921
fun static_conv_thingol (ctxt_consts as { ctxt, consts }) conv =
haftmann@63160
   922
  Code_Preproc.static_conv ctxt_consts (fn algebra_eqngr =>
haftmann@63160
   923
    static_evaluation_thingol ctxt consts algebra_eqngr
haftmann@63160
   924
      (fn program_deps =>
haftmann@63160
   925
        let
haftmann@63160
   926
          val static_conv = conv program_deps;
haftmann@63160
   927
        in 
haftmann@63160
   928
          fn ctxt => fn _ => fn vs_ty => fn deps => static_conv ctxt vs_ty deps
haftmann@63160
   929
        end));
haftmann@38672
   930
haftmann@63156
   931
fun static_conv_isa (ctxt_consts as { ctxt, consts }) conv =
haftmann@63160
   932
  Code_Preproc.static_conv ctxt_consts (fn algebra_eqngr =>
haftmann@63160
   933
    static_evaluation_isa ctxt consts algebra_eqngr conv);
haftmann@38672
   934
haftmann@63157
   935
fun static_value (ctxt_postproc_consts as { ctxt, consts, ... }) comp =
haftmann@63160
   936
  Code_Preproc.static_value ctxt_postproc_consts (fn algebra_eqngr =>
haftmann@63160
   937
    static_evaluation_thingol ctxt consts algebra_eqngr comp);
haftmann@39487
   938
haftmann@30942
   939
haftmann@55188
   940
(** constant expressions **)
haftmann@30942
   941
haftmann@55757
   942
fun read_const_exprs_internal ctxt =
haftmann@31036
   943
  let
haftmann@55757
   944
    val thy = Proof_Context.theory_of ctxt;
wenzelm@68482
   945
    fun this_theory name =
wenzelm@68482
   946
      if Context.theory_name thy = name then thy
wenzelm@68482
   947
      else Context.get_theory {long = false} thy name;
wenzelm@68482
   948
wenzelm@56062
   949
    fun consts_of thy' =
wenzelm@56062
   950
      fold (fn (c, (_, NONE)) => cons c | _ => I)
haftmann@63175
   951
        (#constants (Consts.dest (Sign.consts_of thy'))) []
haftmann@63175
   952
      |> filter_out (Code.is_abstr thy);
haftmann@36272
   953
    fun belongs_here thy' c = forall
haftmann@36272
   954
      (fn thy'' => not (Sign.declared_const thy'' c)) (Theory.parents_of thy');
haftmann@36272
   955
    fun consts_of_select thy' = filter (belongs_here thy') (consts_of thy');
wenzelm@52801
   956
    fun read_const_expr str =
wenzelm@59795
   957
      (case Syntax.parse_input ctxt (K NONE) (K Markup.empty) (SOME o Symbol_Pos.implode o #1) str of
wenzelm@52801
   958
        SOME "_" => ([], consts_of thy)
wenzelm@52801
   959
      | SOME s =>
wenzelm@69645
   960
          (case try (unsuffix "._") s of
wenzelm@69645
   961
            SOME name => ([], consts_of_select (this_theory name))
wenzelm@69645
   962
          | NONE => ([Code.read_const thy str], []))
wenzelm@52801
   963
      | NONE => ([Code.read_const thy str], []));
wenzelm@59058
   964
  in apply2 flat o split_list o map read_const_expr end;
haftmann@31036
   965
haftmann@55757
   966
fun read_const_exprs_all ctxt = op @ o read_const_exprs_internal ctxt;
haftmann@55188
   967
haftmann@55757
   968
fun read_const_exprs ctxt const_exprs =
haftmann@55188
   969
  let
haftmann@63159
   970
    val (consts, consts_permissive) =
haftmann@63159
   971
      read_const_exprs_internal ctxt const_exprs;
haftmann@63175
   972
    val consts' = 
haftmann@63175
   973
      consts_program_permissive ctxt consts_permissive
haftmann@63175
   974
      |> implemented_deps
haftmann@63175
   975
      |> filter_out (Code.is_abstr (Proof_Context.theory_of ctxt));
haftmann@55188
   976
  in union (op =) consts' consts end;
haftmann@55188
   977
haftmann@55188
   978
haftmann@55188
   979
(** diagnostic commands **)
haftmann@55188
   980
haftmann@55757
   981
fun code_depgr ctxt consts =
haftmann@30942
   982
  let
haftmann@63164
   983
    val { eqngr, ... } = Code_Preproc.obtain true
haftmann@63164
   984
      { ctxt = ctxt, consts = consts, terms = [] };
haftmann@34173
   985
    val all_consts = Graph.all_succs eqngr consts;
wenzelm@46614
   986
  in Graph.restrict (member (op =) all_consts) eqngr end;
haftmann@30942
   987
haftmann@55757
   988
fun code_thms ctxt = Pretty.writeln o Code_Preproc.pretty ctxt o code_depgr ctxt;
haftmann@30942
   989
wenzelm@60203
   990
fun coalesce_strong_conn gr =
wenzelm@59208
   991
  let
wenzelm@59208
   992
    val xss = Graph.strong_conn gr;
wenzelm@60203
   993
    val xss_ys = map (fn xs => (xs, commas xs)) xss;
wenzelm@60203
   994
    val y_for = the o AList.lookup (op =) (maps (fn (xs, y) => map (fn x => (x, y)) xs) xss_ys);
wenzelm@60203
   995
    fun coalesced_succs_for xs = maps (Graph.immediate_succs gr) xs
wenzelm@60203
   996
      |> subtract (op =) xs
wenzelm@60203
   997
      |> map y_for
wenzelm@60203
   998
      |> distinct (op =);
wenzelm@60203
   999
    val succs = map (fn (xs, _) => (xs, coalesced_succs_for xs)) xss_ys;
wenzelm@59208
  1000
  in
wenzelm@60204
  1001
    map (fn (xs, y) => ((y, xs), (maps (Graph.get_node gr) xs, (the o AList.lookup (op =) succs) xs))) xss_ys
wenzelm@59208
  1002
  end;
wenzelm@59208
  1003
haftmann@55757
  1004
fun code_deps ctxt consts =
haftmann@27103
  1005
  let
haftmann@55757
  1006
    val thy = Proof_Context.theory_of ctxt;
wenzelm@60204
  1007
    fun mk_entry ((name, consts), (ps, deps)) =
wenzelm@60204
  1008
      let
wenzelm@60204
  1009
        val label = commas (map (Code.string_of_const thy) consts);
wenzelm@60204
  1010
      in ((name, Graph_Display.content_node label (Pretty.str label :: ps)), deps) end;
wenzelm@59210
  1011
  in
wenzelm@59210
  1012
    code_depgr ctxt consts
wenzelm@60204
  1013
    |> Graph.map (K (Code.pretty_cert thy o snd))
wenzelm@60203
  1014
    |> coalesce_strong_conn
wenzelm@60204
  1015
    |> map mk_entry
wenzelm@60203
  1016
    |> Graph_Display.display_graph
wenzelm@59210
  1017
  end;
haftmann@30942
  1018
haftmann@30942
  1019
local
haftmann@27103
  1020
haftmann@55757
  1021
fun code_thms_cmd ctxt = code_thms ctxt o read_const_exprs_all ctxt;
haftmann@55757
  1022
fun code_deps_cmd ctxt = code_deps ctxt o read_const_exprs_all ctxt;
haftmann@30942
  1023
haftmann@30942
  1024
in
haftmann@30942
  1025
haftmann@30942
  1026
val _ =
wenzelm@69593
  1027
  Outer_Syntax.command \<^command_keyword>\<open>code_thms\<close>
wenzelm@46961
  1028
    "print system of code equations for code"
wenzelm@52801
  1029
    (Scan.repeat1 Parse.term >> (fn cs =>
wenzelm@60097
  1030
      Toplevel.keep (fn st => code_thms_cmd (Toplevel.context_of st) cs)));
haftmann@30942
  1031
haftmann@30942
  1032
val _ =
wenzelm@69593
  1033
  Outer_Syntax.command \<^command_keyword>\<open>code_deps\<close>
wenzelm@46961
  1034
    "visualize dependencies of code equations for code"
wenzelm@52801
  1035
    (Scan.repeat1 Parse.term >> (fn cs =>
wenzelm@59210
  1036
      Toplevel.keep (fn st => code_deps_cmd (Toplevel.context_of st) cs)));
haftmann@30942
  1037
haftmann@30942
  1038
end;
haftmann@27103
  1039
haftmann@24219
  1040
end; (*struct*)
haftmann@24219
  1041
haftmann@24219
  1042
haftmann@28054
  1043
structure Basic_Code_Thingol: BASIC_CODE_THINGOL = Code_Thingol;