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