src/HOL/Library/code_lazy.ML
author Andreas Lochbihler
Tue Jan 01 17:04:53 2019 +0100 (6 months ago)
changeset 69568 de09a7261120
parent 68549 bbc742358156
child 69593 3dda49e08b9d
permissions -rw-r--r--
new implementation for case_of_simps based on Code_Lazy's pattern matching elimination algorithm
Andreas@68155
     1
(* Author: Pascal Stoop, ETH Zurich
Andreas@68155
     2
   Author: Andreas Lochbihler, Digital Asset *)
Andreas@68155
     3
Andreas@68155
     4
signature CODE_LAZY =
Andreas@68155
     5
sig
Andreas@68155
     6
  type lazy_info =
Andreas@68155
     7
    {eagerT: typ,
Andreas@68155
     8
     lazyT: typ,
Andreas@68155
     9
     ctr: term,
Andreas@68155
    10
     destr: term,
Andreas@68155
    11
     lazy_ctrs: term list,
Andreas@68155
    12
     case_lazy: term,
Andreas@68155
    13
     active: bool,
Andreas@68155
    14
     activate: theory -> theory,
Andreas@68155
    15
     deactivate: theory -> theory};
Andreas@68155
    16
  val code_lazy_type: string -> theory -> theory
Andreas@68155
    17
  val activate_lazy_type: string -> theory -> theory
Andreas@68155
    18
  val deactivate_lazy_type: string -> theory -> theory
Andreas@68155
    19
  val activate_lazy_types: theory -> theory
Andreas@68155
    20
  val deactivate_lazy_types: theory -> theory
Andreas@68155
    21
Andreas@68155
    22
  val get_lazy_types: theory -> (string * lazy_info) list
Andreas@68155
    23
Andreas@68155
    24
  val print_lazy_types: theory -> unit
Andreas@68155
    25
Andreas@68155
    26
  val transform_code_eqs: Proof.context -> (thm * bool) list -> (thm * bool) list option
Andreas@68155
    27
end;
Andreas@68155
    28
Andreas@68155
    29
structure Code_Lazy : CODE_LAZY =
Andreas@68155
    30
struct
Andreas@68155
    31
Andreas@68155
    32
type lazy_info =
Andreas@68155
    33
  {eagerT: typ,
Andreas@68155
    34
   lazyT: typ,
Andreas@68155
    35
   ctr: term,
Andreas@68155
    36
   destr: term,
Andreas@68155
    37
   lazy_ctrs: term list,
Andreas@68155
    38
   case_lazy: term,
Andreas@68155
    39
   active: bool,
Andreas@68155
    40
   activate: theory -> theory,
Andreas@68155
    41
   deactivate: theory -> theory};
Andreas@68155
    42
Andreas@68155
    43
fun map_active f {eagerT, lazyT, ctr, destr, lazy_ctrs, case_lazy, active, activate, deactivate} =
Andreas@68155
    44
  { eagerT = eagerT, 
Andreas@68155
    45
    lazyT = lazyT,
Andreas@68155
    46
    ctr = ctr,
Andreas@68155
    47
    destr = destr,
Andreas@68155
    48
    lazy_ctrs = lazy_ctrs,
Andreas@68155
    49
    case_lazy = case_lazy,
Andreas@68155
    50
    active = f active,
Andreas@68155
    51
    activate = activate,
Andreas@68155
    52
    deactivate = deactivate
Andreas@68155
    53
  }
Andreas@68155
    54
Andreas@68155
    55
structure Laziness_Data = Theory_Data(
Andreas@68155
    56
  type T = lazy_info Symtab.table;
Andreas@68155
    57
  val empty = Symtab.empty;
Andreas@68155
    58
  val merge = Symtab.join (fn _ => fn (_, record) => record);
Andreas@68155
    59
  val extend = I;
Andreas@68155
    60
);
Andreas@68155
    61
Andreas@68155
    62
fun fold_type type' tfree tvar typ =
Andreas@68155
    63
  let
Andreas@68155
    64
    fun go (Type (s, Ts)) = type' (s, map go Ts)
Andreas@68155
    65
      | go (TFree T) = tfree T
Andreas@68155
    66
      | go (TVar T) = tvar T
Andreas@68155
    67
  in
Andreas@68155
    68
    go typ
Andreas@68155
    69
  end;
Andreas@68155
    70
Andreas@68155
    71
fun read_typ lthy name =
Andreas@68155
    72
  let
Andreas@68155
    73
    val (s, Ts) = Proof_Context.read_type_name {proper = true, strict = true} lthy name |> dest_Type
Andreas@68155
    74
    val (Ts', _) = Ctr_Sugar_Util.mk_TFrees (length Ts) lthy
Andreas@68155
    75
  in 
Andreas@68155
    76
    Type (s, Ts')
Andreas@68155
    77
  end
Andreas@68155
    78
Andreas@68155
    79
fun mk_name prefix suffix name ctxt =
Andreas@68155
    80
  Ctr_Sugar_Util.mk_fresh_names ctxt 1 (prefix ^ name ^ suffix) |>> hd;
Andreas@68155
    81
fun generate_typedef_name name ctxt = mk_name "" "_lazy" name ctxt;
Andreas@68155
    82
Andreas@68155
    83
fun add_syntax_definition short_type_name eagerT lazyT lazy_ctr lthy = 
Andreas@68155
    84
  let
Andreas@68155
    85
    val (name, _) = mk_name "lazy_" "" short_type_name lthy
Andreas@68155
    86
    val freeT = HOLogic.unitT --> lazyT
Andreas@68155
    87
    val lazyT' = Type (@{type_name lazy}, [lazyT])
Andreas@68155
    88
    val def = Logic.all_const freeT $ absdummy freeT (Logic.mk_equals (
Andreas@68155
    89
      Free (name, (freeT --> eagerT)) $ Bound 0,
Andreas@68155
    90
      lazy_ctr $ (Const (@{const_name delay}, (freeT --> lazyT')) $ Bound 0)))
Andreas@68155
    91
    val (_, lthy') = Local_Theory.open_target lthy
Andreas@68155
    92
    val ((t, (_, thm)), lthy') = Specification.definition NONE [] [] 
Andreas@68155
    93
      ((Thm.def_binding (Binding.name name), []), def) lthy'
Andreas@68155
    94
    val lthy' = Specification.notation true ("", false) [(t, Mixfix.mixfix "_")] lthy'
Andreas@68155
    95
    val lthy = Local_Theory.close_target lthy'
Andreas@68155
    96
    val def_thm = singleton (Proof_Context.export lthy' lthy) thm
Andreas@68155
    97
  in
Andreas@68155
    98
    (def_thm, lthy)
Andreas@68155
    99
  end;
Andreas@68155
   100
Andreas@68155
   101
fun add_ctr_code raw_ctrs case_thms thy =
Andreas@68155
   102
  let
Andreas@68155
   103
    fun mk_case_certificate ctxt raw_thms =
Andreas@68155
   104
      let
Andreas@68155
   105
        val thms = raw_thms
Andreas@68155
   106
          |> Conjunction.intr_balanced
Andreas@68155
   107
          |> Thm.unvarify_global (Proof_Context.theory_of ctxt)
Andreas@68155
   108
          |> Conjunction.elim_balanced (length raw_thms)
Andreas@68155
   109
          |> map Simpdata.mk_meta_eq
Andreas@68155
   110
          |> map Drule.zero_var_indexes
Andreas@68155
   111
        val thm1 = case thms of
Andreas@68155
   112
          thm :: _ => thm
Andreas@68155
   113
          | _ => raise Empty
Andreas@68155
   114
        val params = Term.add_free_names (Thm.prop_of thm1) [];
Andreas@68155
   115
        val rhs = thm1
Andreas@68155
   116
          |> Thm.prop_of |> Logic.dest_equals |> fst |> strip_comb
Andreas@68155
   117
          ||> fst o split_last |> list_comb
Andreas@68155
   118
        val lhs = Free (singleton (Name.variant_list params) "case", fastype_of rhs);
Andreas@68155
   119
        val assum = Thm.cterm_of ctxt (Logic.mk_equals (lhs, rhs))
Andreas@68155
   120
      in
Andreas@68155
   121
        thms
Andreas@68155
   122
        |> Conjunction.intr_balanced
Andreas@68155
   123
        |> rewrite_rule ctxt [Thm.symmetric (Thm.assume assum)]
Andreas@68155
   124
        |> Thm.implies_intr assum
Andreas@68155
   125
        |> Thm.generalize ([], params) 0
Andreas@68155
   126
        |> Axclass.unoverload ctxt
Andreas@68155
   127
        |> Thm.varifyT_global
Andreas@68155
   128
      end
Andreas@68155
   129
    val ctrs = map (apsnd (perhaps (try Logic.unvarifyT_global))) raw_ctrs
Andreas@68155
   130
    val unover_ctrs = map (fn ctr as (_, fcT) => (Axclass.unoverload_const thy ctr, fcT)) ctrs
Andreas@68155
   131
  in
Andreas@68155
   132
    if can (Code.constrset_of_consts thy) unover_ctrs then
Andreas@68155
   133
      thy
Andreas@68155
   134
      |> Code.declare_datatype_global ctrs
Andreas@68155
   135
      |> fold_rev (Code.add_eqn_global o rpair true) case_thms
Andreas@68155
   136
      |> Code.declare_case_global (mk_case_certificate (Proof_Context.init_global thy) case_thms)
Andreas@68155
   137
    else
Andreas@68155
   138
      thy
Andreas@68155
   139
  end;
Andreas@68155
   140
Andreas@68155
   141
fun not_found s = error (s ^ " has not been added as lazy type");
Andreas@68155
   142
Andreas@68155
   143
fun validate_type_name thy type_name =
Andreas@68155
   144
  let
Andreas@68155
   145
    val lthy = Named_Target.theory_init thy
Andreas@68155
   146
    val eager_type = read_typ lthy type_name
Andreas@68155
   147
    val type_name = case eager_type of
Andreas@68155
   148
      Type (s, _) => s
Andreas@68155
   149
      | _ => raise Match
Andreas@68155
   150
  in
Andreas@68155
   151
    type_name
Andreas@68155
   152
  end;
Andreas@68155
   153
Andreas@68155
   154
fun set_active_lazy_type value eager_type_string thy =
Andreas@68155
   155
  let
Andreas@68155
   156
    val type_name = validate_type_name thy eager_type_string
Andreas@68155
   157
    val x =
Andreas@68155
   158
      case Symtab.lookup (Laziness_Data.get thy) type_name of
Andreas@68155
   159
        NONE => not_found type_name
Andreas@68155
   160
        | SOME x => x
Andreas@68155
   161
    val new_x = map_active (K value) x
Andreas@68155
   162
    val thy1 = if value = #active x
Andreas@68155
   163
      then thy
Andreas@68155
   164
      else if value
Andreas@68155
   165
        then #activate x thy
Andreas@68155
   166
        else #deactivate x thy
Andreas@68155
   167
  in
Andreas@68155
   168
    Laziness_Data.map (Symtab.update (type_name, new_x)) thy1
Andreas@68155
   169
  end;
Andreas@68155
   170
Andreas@68155
   171
fun set_active_lazy_types value thy =
Andreas@68155
   172
  let
Andreas@68155
   173
    val lazy_type_names = Symtab.keys (Laziness_Data.get thy)
Andreas@68155
   174
    fun fold_fun value type_name thy =
Andreas@68155
   175
      let
Andreas@68155
   176
        val x =
Andreas@68155
   177
          case Symtab.lookup (Laziness_Data.get thy) type_name of
Andreas@68155
   178
            SOME x => x
Andreas@68155
   179
            | NONE => raise Match
Andreas@68155
   180
        val new_x = map_active (K value) x
Andreas@68155
   181
        val thy1 = if value = #active x
Andreas@68155
   182
          then thy
Andreas@68155
   183
          else if value
Andreas@68155
   184
            then #activate x thy
Andreas@68155
   185
            else #deactivate x thy
Andreas@68155
   186
      in
Andreas@68155
   187
        Laziness_Data.map (Symtab.update (type_name, new_x)) thy1
Andreas@68155
   188
      end
Andreas@68155
   189
  in
Andreas@68155
   190
    fold (fold_fun value) lazy_type_names thy
Andreas@68155
   191
  end;
Andreas@68155
   192
Andreas@68155
   193
(* code_lazy_type : string -> theory -> theory *)
Andreas@68155
   194
fun code_lazy_type eager_type_string thy =
Andreas@68155
   195
  let
Andreas@68155
   196
    val lthy = Named_Target.theory_init thy
Andreas@68155
   197
    val eagerT = read_typ lthy eager_type_string
Andreas@68155
   198
    val (type_name, type_args) = dest_Type eagerT
Andreas@68155
   199
    val short_type_name = Long_Name.base_name type_name
Andreas@68155
   200
    val _ = if Symtab.defined (Laziness_Data.get thy) type_name
Andreas@68155
   201
      then error (type_name ^ " has already been added as lazy type.")
Andreas@68155
   202
      else ()
Andreas@68155
   203
    val {case_thms, casex, ctrs, ...} = case Ctr_Sugar.ctr_sugar_of lthy type_name of
Andreas@68155
   204
        SOME x => x
Andreas@68155
   205
      | _ => error (type_name ^ " is not registered with free constructors.")
Andreas@68155
   206
Andreas@68155
   207
    fun substitute_ctr (old_T, new_T) ctr_T lthy =
Andreas@68155
   208
      let
Andreas@68155
   209
        val old_ctr_vars = map TVar (Term.add_tvarsT ctr_T [])
Andreas@68155
   210
        val old_ctr_Ts = map TFree (Term.add_tfreesT ctr_T []) @ old_ctr_vars
Andreas@68155
   211
        val (new_ctr_Ts, lthy') = Ctr_Sugar_Util.mk_TFrees (length old_ctr_Ts) lthy
Andreas@68155
   212
Andreas@68155
   213
        fun double_type_fold Ts = case Ts of
Andreas@68155
   214
          (Type (_, Ts1), Type (_, Ts2)) => flat (map double_type_fold (Ts1 ~~ Ts2))
Andreas@68155
   215
          | (Type _, _) => raise Match
Andreas@68155
   216
          | (_, Type _) => raise Match
Andreas@68155
   217
          | Ts => [Ts]
Andreas@68155
   218
        fun map_fun1 f = List.foldr
Andreas@68155
   219
          (fn ((T1, T2), f) => fn T => if T = T1 then T2 else f T)
Andreas@68155
   220
          f
Andreas@68155
   221
          (double_type_fold (old_T, new_T))
Andreas@68155
   222
        val map_fun2 = AList.lookup (op =) (old_ctr_Ts ~~ new_ctr_Ts) #> the
Andreas@68155
   223
        val map_fun = map_fun1 map_fun2
Andreas@68155
   224
Andreas@68155
   225
        val new_ctr_type = fold_type Type (map_fun o TFree) (map_fun o TVar) ctr_T
Andreas@68155
   226
      in
Andreas@68155
   227
        (new_ctr_type, lthy')
Andreas@68155
   228
      end
Andreas@68155
   229
Andreas@68155
   230
    val (short_lazy_type_name, lthy1) = generate_typedef_name short_type_name lthy
Andreas@68155
   231
Andreas@68155
   232
    fun mk_lazy_typedef (name, eager_type) lthy =
Andreas@68155
   233
      let
Andreas@68155
   234
        val binding = Binding.name name
Andreas@68155
   235
        val (result, lthy1) = (Typedef.add_typedef
Andreas@68155
   236
            { overloaded=false }
Andreas@68155
   237
            (binding, rev (Term.add_tfreesT eager_type []), Mixfix.NoSyn)
Andreas@68155
   238
            (Const (@{const_name "top"}, Type (@{type_name set}, [eager_type])))
Andreas@68155
   239
            NONE
Andreas@68155
   240
            (fn ctxt => resolve_tac ctxt [@{thm UNIV_witness}] 1)
Andreas@68155
   241
          o (Local_Theory.open_target #> snd)) lthy
Andreas@68155
   242
      in
Andreas@68155
   243
         (binding, result, Local_Theory.close_target lthy1)
Andreas@68155
   244
      end;
Andreas@68155
   245
Andreas@68155
   246
    val (typedef_binding, (_, info), lthy2) = mk_lazy_typedef (short_lazy_type_name, eagerT) lthy1
Andreas@68155
   247
Andreas@68155
   248
    val lazy_type = Type (Local_Theory.full_name lthy2 typedef_binding, type_args)
Andreas@68155
   249
    val (Abs_lazy, Rep_lazy) =
Andreas@68155
   250
      let
Andreas@68155
   251
        val info = fst info
Andreas@68155
   252
        val Abs_name = #Abs_name info
Andreas@68155
   253
        val Rep_name = #Rep_name info
Andreas@68155
   254
        val Abs_type = eagerT --> lazy_type
Andreas@68155
   255
        val Rep_type = lazy_type --> eagerT
Andreas@68155
   256
      in
Andreas@68155
   257
        (Const (Abs_name, Abs_type), Const (Rep_name, Rep_type))
Andreas@68155
   258
      end
Andreas@68155
   259
    val Abs_inverse = #Abs_inverse (snd info)
Andreas@68155
   260
    val Rep_inverse = #Rep_inverse (snd info)
Andreas@68155
   261
Andreas@68155
   262
    val (ctrs', lthy3) = List.foldr
Andreas@68155
   263
      (fn (Const (s, T), (ctrs, lthy)) => let
Andreas@68155
   264
            val (T', lthy') = substitute_ctr (body_type T, eagerT) T lthy
Andreas@68155
   265
          in
Andreas@68155
   266
            ((Const (s, T')) :: ctrs, lthy')
Andreas@68155
   267
          end
Andreas@68155
   268
      )
Andreas@68155
   269
      ([], lthy2)
Andreas@68155
   270
      ctrs
Andreas@68155
   271
Andreas@68155
   272
    fun to_destr_eagerT typ = case typ of
Andreas@68155
   273
          Type (@{type_name "fun"}, [_, Type (@{type_name "fun"}, Ts)]) => 
Andreas@68155
   274
          to_destr_eagerT (Type (@{type_name "fun"}, Ts))
Andreas@68155
   275
        | Type (@{type_name "fun"}, [T, _]) => T
Andreas@68155
   276
        | _ => raise Match
Andreas@68155
   277
    val (case', lthy4) = 
Andreas@68155
   278
      let
Andreas@68155
   279
        val (eager_case, caseT) = dest_Const casex
Andreas@68155
   280
        val (caseT', lthy') = substitute_ctr (to_destr_eagerT caseT, eagerT) caseT lthy3
Andreas@68155
   281
      in (Const (eager_case, caseT'), lthy') end
Andreas@68155
   282
Andreas@68155
   283
    val ctr_names = map (Long_Name.base_name o fst o dest_Const) ctrs
Andreas@68155
   284
    val ((((lazy_ctr_name, lazy_sel_name), lazy_ctrs_name), lazy_case_name), ctxt) = lthy4
Andreas@68155
   285
      |> mk_name "Lazy_" "" short_type_name
Andreas@68155
   286
      ||>> mk_name "unlazy_" "" short_type_name
Andreas@68155
   287
      ||>> fold_map (mk_name "" "_Lazy") ctr_names
Andreas@68155
   288
      ||>> mk_name "case_" "_lazy" short_type_name
Andreas@68155
   289
Andreas@68155
   290
    fun mk_def (name, T, rhs) lthy =
Andreas@68155
   291
      let
Andreas@68155
   292
        val binding = Binding.name name
Andreas@68155
   293
        val ((_, (_, thm)), lthy1) = 
Andreas@68155
   294
          Local_Theory.open_target lthy |> snd
Andreas@68155
   295
          |> Specification.definition NONE [] [] ((Thm.def_binding binding, []), rhs)
Andreas@68155
   296
        val lthy2 = Local_Theory.close_target lthy1
Andreas@68155
   297
        val def_thm = hd (Proof_Context.export lthy1 lthy2 [thm])
Andreas@68155
   298
      in
Andreas@68155
   299
        ({binding = binding, const = Const (Local_Theory.full_name lthy2 binding, T), thm = def_thm}, lthy2)
Andreas@68155
   300
      end;
Andreas@68155
   301
    
Andreas@68155
   302
    val lazy_datatype = Type (@{type_name lazy}, [lazy_type])
Andreas@68155
   303
    val Lazy_type = lazy_datatype --> eagerT
Andreas@68155
   304
    val unstr_type = eagerT --> lazy_datatype
Andreas@68155
   305
    
Andreas@68155
   306
    fun apply_bounds i n term =
Andreas@68155
   307
      if n > i then apply_bounds i (n-1) (term $ Bound (n-1))
Andreas@68155
   308
      else term
Andreas@68155
   309
    fun all_abs Ts t = Logic.list_all (map (pair Name.uu) Ts, t)
Andreas@68155
   310
    fun mk_force t = Const (@{const_name force}, lazy_datatype --> lazy_type) $ t
Andreas@68155
   311
    fun mk_delay t = Const (@{const_name delay}, (@{typ unit} --> lazy_type) --> lazy_datatype) $ t
Andreas@68155
   312
Andreas@68155
   313
    val lazy_ctr = all_abs [lazy_datatype]
Andreas@68155
   314
      (Logic.mk_equals (Free (lazy_ctr_name, Lazy_type) $ Bound 0, Rep_lazy $ mk_force (Bound 0)))
Andreas@68155
   315
    val (lazy_ctr_def, lthy5) = mk_def (lazy_ctr_name, Lazy_type, lazy_ctr) lthy4
Andreas@68155
   316
Andreas@68155
   317
    val lazy_sel = all_abs [eagerT]
Andreas@68155
   318
      (Logic.mk_equals (Free (lazy_sel_name, unstr_type) $ Bound 0, 
Andreas@68155
   319
        mk_delay (Abs (Name.uu, @{typ unit}, Abs_lazy $ Bound 1))))
Andreas@68155
   320
    val (lazy_sel_def, lthy6) = mk_def (lazy_sel_name, unstr_type, lazy_sel) lthy5
Andreas@68155
   321
Andreas@68155
   322
    fun mk_lazy_ctr (name, eager_ctr) =
Andreas@68155
   323
      let
Andreas@68155
   324
        val (_, ctrT) = dest_Const eager_ctr
Andreas@68155
   325
        fun to_lazy_ctrT (Type (@{type_name fun}, [T1, T2])) = T1 --> to_lazy_ctrT T2
Andreas@68155
   326
          | to_lazy_ctrT T = if T = eagerT then lazy_type else raise Match
Andreas@68155
   327
        val lazy_ctrT = to_lazy_ctrT ctrT
Andreas@68155
   328
        val argsT = binder_types ctrT
Andreas@68155
   329
        val lhs = apply_bounds 0 (length argsT) (Free (name, lazy_ctrT))
Andreas@68155
   330
        val rhs = Abs_lazy $ apply_bounds 0 (length argsT) eager_ctr
Andreas@68155
   331
      in
Andreas@68155
   332
        mk_def (name, lazy_ctrT, all_abs argsT (Logic.mk_equals (lhs, rhs)))
Andreas@68155
   333
      end
Andreas@68155
   334
    val (lazy_ctrs_def, lthy7) = fold_map mk_lazy_ctr (lazy_ctrs_name ~~ ctrs') lthy6
Andreas@68155
   335
Andreas@68155
   336
    val (lazy_case_def, lthy8) =
Andreas@68155
   337
      let
Andreas@68155
   338
        val (_, caseT) = dest_Const case'
Andreas@68155
   339
        fun to_lazy_caseT (Type (@{type_name fun}, [T1, T2])) =
Andreas@68155
   340
            if T1 = eagerT then lazy_type --> T2 else T1 --> to_lazy_caseT T2
Andreas@68155
   341
        val lazy_caseT = to_lazy_caseT caseT
Andreas@68155
   342
        val argsT = binder_types lazy_caseT
Andreas@68155
   343
        val n = length argsT
Andreas@68155
   344
        val lhs = apply_bounds 0 n (Free (lazy_case_name, lazy_caseT)) 
Andreas@68155
   345
        val rhs = apply_bounds 1 n case' $ (Rep_lazy $ Bound 0)
Andreas@68155
   346
      in
Andreas@68155
   347
        mk_def (lazy_case_name, lazy_caseT, all_abs argsT (Logic.mk_equals (lhs, rhs))) lthy7
Andreas@68155
   348
      end
Andreas@68155
   349
Andreas@68155
   350
    fun mk_thm ((name, term), thms) lthy =
Andreas@68155
   351
      let
Andreas@68155
   352
        val binding = Binding.name name
Andreas@68155
   353
        fun tac {context, ...} = Simplifier.simp_tac
Andreas@68155
   354
          (put_simpset HOL_basic_ss context addsimps thms)
Andreas@68155
   355
          1
Andreas@68155
   356
        val thm = Goal.prove lthy [] [] term tac
Andreas@68155
   357
        val (_, lthy1) = lthy
Andreas@68155
   358
          |> Local_Theory.open_target |> snd
Andreas@68155
   359
          |> Local_Theory.note ((binding, []), [thm])
Andreas@68155
   360
      in
Andreas@68155
   361
        (thm, Local_Theory.close_target lthy1)
Andreas@68155
   362
      end
Andreas@68155
   363
    fun mk_thms exec_list lthy = fold_map mk_thm exec_list lthy
Andreas@68155
   364
Andreas@68155
   365
    val mk_eq = HOLogic.mk_Trueprop o HOLogic.mk_eq
Andreas@68155
   366
Andreas@68155
   367
    val lazy_ctrs = map #const lazy_ctrs_def
Andreas@68155
   368
    val eager_lazy_ctrs = ctrs' ~~ lazy_ctrs
Andreas@68155
   369
Andreas@68155
   370
    val (((((((Lazy_delay_eq_name, Rep_ctr_names), ctrs_lazy_names), force_sel_name), case_lazy_name),
Andreas@68155
   371
      sel_lazy_name), case_ctrs_name), _) = lthy5
Andreas@68155
   372
      |> mk_name "Lazy_" "_delay" short_type_name
Andreas@68155
   373
      ||>> fold_map (mk_name "Rep_" "_Lazy") ctr_names
Andreas@68155
   374
      ||>> fold_map (mk_name "" "_conv_lazy") ctr_names
Andreas@68155
   375
      ||>> mk_name "force_unlazy_" "" short_type_name
Andreas@68155
   376
      ||>> mk_name "case_" "_conv_lazy" short_type_name
Andreas@68155
   377
      ||>> mk_name "Lazy_" "_inverse" short_type_name
Andreas@68155
   378
      ||>> fold_map (mk_name ("case_" ^ short_type_name ^ "_lazy_") "") ctr_names
Andreas@68155
   379
Andreas@68155
   380
    val mk_Lazy_delay_eq =
Andreas@68155
   381
      (#const lazy_ctr_def $ mk_delay (Bound 0), Rep_lazy $ (Bound 0 $ @{const Unity}))
Andreas@68155
   382
      |> mk_eq |> all_abs [@{typ unit} --> lazy_type]
Andreas@68155
   383
    val (Lazy_delay_thm, lthy8a) = mk_thm 
Andreas@68155
   384
      ((Lazy_delay_eq_name, mk_Lazy_delay_eq), [#thm lazy_ctr_def, @{thm force_delay}])
Andreas@68155
   385
      lthy8
Andreas@68155
   386
Andreas@68155
   387
    fun mk_lazy_ctr_eq (eager_ctr, lazy_ctr) =
Andreas@68155
   388
      let
Andreas@68155
   389
        val (_, ctrT) = dest_Const eager_ctr
Andreas@68155
   390
        val argsT = binder_types ctrT
Andreas@68155
   391
        val args = length argsT
Andreas@68155
   392
      in
Andreas@68155
   393
        (Rep_lazy $ apply_bounds 0 args lazy_ctr, apply_bounds 0 args eager_ctr)
Andreas@68155
   394
        |> mk_eq |> all_abs argsT
Andreas@68155
   395
      end
Andreas@68155
   396
    val Rep_ctr_eqs = map mk_lazy_ctr_eq eager_lazy_ctrs
Andreas@68155
   397
    val (Rep_ctr_thms, lthy8b) = mk_thms
Andreas@68155
   398
        ((Rep_ctr_names ~~ Rep_ctr_eqs) ~~
Andreas@68155
   399
          (map (fn def => [#thm def, Abs_inverse, @{thm UNIV_I}]) lazy_ctrs_def)
Andreas@68155
   400
        )
Andreas@68155
   401
        lthy8a
Andreas@68155
   402
Andreas@68155
   403
    fun mk_ctrs_lazy_eq (eager_ctr, lazy_ctr) =
Andreas@68155
   404
      let
Andreas@68155
   405
        val argsT = dest_Const eager_ctr |> snd |> binder_types
Andreas@68155
   406
        val n = length argsT
Andreas@68155
   407
        val lhs = apply_bounds 0 n eager_ctr
Andreas@68155
   408
        val rhs = #const lazy_ctr_def $ 
Andreas@68155
   409
          (mk_delay (Abs (Name.uu, @{typ unit}, apply_bounds 1 (n + 1) lazy_ctr)))
Andreas@68155
   410
      in
Andreas@68155
   411
        (lhs, rhs) |> mk_eq |> all_abs argsT
Andreas@68155
   412
      end
Andreas@68155
   413
    val ctrs_lazy_eq = map mk_ctrs_lazy_eq eager_lazy_ctrs 
Andreas@68155
   414
    val (ctrs_lazy_thms, lthy8c) = mk_thms
Andreas@68155
   415
      ((ctrs_lazy_names ~~ ctrs_lazy_eq) ~~ map (fn thm => [Lazy_delay_thm, thm]) Rep_ctr_thms)
Andreas@68155
   416
      lthy8b
Andreas@68155
   417
Andreas@68155
   418
    val force_sel_eq = 
Andreas@68155
   419
      (mk_force (#const lazy_sel_def $ Bound 0), Abs_lazy $ Bound 0)
Andreas@68155
   420
      |> mk_eq |> all_abs [eagerT]
Andreas@68155
   421
    val (force_sel_thm, lthy8d) = mk_thm
Andreas@68155
   422
        ((force_sel_name, force_sel_eq), [#thm lazy_sel_def, @{thm force_delay}])
Andreas@68155
   423
        lthy8c
Andreas@68155
   424
Andreas@68155
   425
    val case_lazy_eq = 
Andreas@68155
   426
      let
Andreas@68155
   427
        val (_, caseT) = case' |> dest_Const
Andreas@68155
   428
        val argsT = binder_types caseT
Andreas@68155
   429
        val n = length argsT
Andreas@68155
   430
        val lhs = apply_bounds 0 n case'
Andreas@68155
   431
        val rhs = apply_bounds 1 n (#const lazy_case_def) $ (mk_force (#const lazy_sel_def $ Bound 0))
Andreas@68155
   432
      in
Andreas@68155
   433
        (lhs, rhs) |> mk_eq |> all_abs argsT
Andreas@68155
   434
      end
Andreas@68155
   435
    val (case_lazy_thm, lthy8e) = mk_thm
Andreas@68155
   436
        ((case_lazy_name, case_lazy_eq), 
Andreas@68155
   437
        [#thm lazy_case_def, force_sel_thm, Abs_inverse, @{thm UNIV_I}])
Andreas@68155
   438
        lthy8d
Andreas@68155
   439
Andreas@68155
   440
    val sel_lazy_eq =
Andreas@68155
   441
      (#const lazy_sel_def $ (#const lazy_ctr_def $ Bound 0), Bound 0)
Andreas@68155
   442
      |> mk_eq |> all_abs [lazy_datatype]
Andreas@68155
   443
    val (sel_lazy_thm, lthy8f) = mk_thm
Andreas@68155
   444
      ((sel_lazy_name, sel_lazy_eq),
Andreas@68155
   445
      [#thm lazy_sel_def, #thm lazy_ctr_def, Rep_inverse, @{thm delay_force}])
Andreas@68155
   446
      lthy8e
Andreas@68155
   447
Andreas@68155
   448
    fun mk_case_ctrs_eq (i, lazy_ctr) =
Andreas@68155
   449
      let
Andreas@68155
   450
        val lazy_case = #const lazy_case_def
Andreas@68155
   451
        val (_, ctrT) = dest_Const lazy_ctr
Andreas@68155
   452
        val ctr_argsT = binder_types ctrT
Andreas@68155
   453
        val ctr_args_n = length ctr_argsT
Andreas@68155
   454
        val (_, caseT) = dest_Const lazy_case
Andreas@68155
   455
        val case_argsT = binder_types caseT
Andreas@68155
   456
Andreas@68155
   457
        fun n_bounds_from m n t =
Andreas@68155
   458
          if n > 0 then n_bounds_from (m - 1) (n - 1) (t $ Bound (m - 1)) else t
Andreas@68155
   459
Andreas@68155
   460
        val case_argsT' = take (length case_argsT - 1) case_argsT
Andreas@68155
   461
        val Ts = case_argsT' @ ctr_argsT
Andreas@68155
   462
        val num_abs_types = length Ts
Andreas@68155
   463
        val lhs = n_bounds_from num_abs_types (length case_argsT') lazy_case $
Andreas@68155
   464
          apply_bounds 0 ctr_args_n lazy_ctr
Andreas@68155
   465
        val rhs = apply_bounds 0 ctr_args_n (Bound (num_abs_types - i - 1))
Andreas@68155
   466
      in
Andreas@68155
   467
        (lhs, rhs) |> mk_eq |> all_abs Ts
Andreas@68155
   468
      end
Andreas@68155
   469
    val case_ctrs_eq = map_index mk_case_ctrs_eq lazy_ctrs
Andreas@68155
   470
    val (case_ctrs_thms, lthy9) = mk_thms
Andreas@68155
   471
        ((case_ctrs_name ~~ case_ctrs_eq) ~~
Andreas@68155
   472
         map2 (fn thm1 => fn thm2 => [#thm lazy_case_def, thm1, thm2]) Rep_ctr_thms case_thms
Andreas@68155
   473
        )
Andreas@68155
   474
        lthy8f
Andreas@68155
   475
Andreas@68155
   476
    val (pat_def_thm, lthy10) = 
Andreas@68155
   477
      add_syntax_definition short_type_name eagerT lazy_type (#const lazy_ctr_def) lthy9
Andreas@68155
   478
Andreas@68155
   479
    val add_lazy_ctrs =
Andreas@68155
   480
      Code.declare_datatype_global [dest_Const (#const lazy_ctr_def)]
Andreas@68155
   481
    val eager_ctrs = map (apsnd (perhaps (try Logic.unvarifyT_global)) o dest_Const) ctrs
Andreas@68155
   482
    val add_eager_ctrs =
Andreas@68155
   483
      fold Code.del_eqn_global ctrs_lazy_thms
Andreas@68155
   484
      #> Code.declare_datatype_global eager_ctrs
Andreas@68155
   485
    val add_code_eqs = fold (Code.add_eqn_global o rpair true) 
Andreas@68155
   486
      ([case_lazy_thm, sel_lazy_thm])
Andreas@68155
   487
    val add_lazy_ctr_thms = fold (Code.add_eqn_global o rpair true) ctrs_lazy_thms
Andreas@68155
   488
    val add_lazy_case_thms =
Andreas@68155
   489
      fold Code.del_eqn_global case_thms
Andreas@68549
   490
      #> Code.add_eqn_global (case_lazy_thm, true)
Andreas@68155
   491
    val add_eager_case_thms = Code.del_eqn_global case_lazy_thm
Andreas@68549
   492
      #> fold (Code.add_eqn_global o rpair true) case_thms
Andreas@68155
   493
Andreas@68155
   494
    val delay_dummy_thm = (pat_def_thm RS @{thm symmetric})
Andreas@68155
   495
      |> Drule.infer_instantiate' lthy10
Andreas@68155
   496
         [SOME (Thm.cterm_of lthy10 (Const (@{const_name "Pure.dummy_pattern"}, HOLogic.unitT --> lazy_type)))]
Andreas@68155
   497
      |> Thm.generalize (map (fst o dest_TFree) type_args, []) (Variable.maxidx_of lthy10 + 1);
Andreas@68155
   498
Andreas@68155
   499
    val ctr_post = delay_dummy_thm :: map (fn thm => thm RS @{thm sym}) ctrs_lazy_thms
Andreas@68155
   500
    val ctr_thms_abs = map (fn thm => Drule.abs_def (thm RS @{thm eq_reflection})) ctrs_lazy_thms
Andreas@68155
   501
    val case_thm_abs = Drule.abs_def (case_lazy_thm RS @{thm eq_reflection})
Andreas@68155
   502
    val add_simps = Code_Preproc.map_pre
Andreas@68155
   503
      (fn ctxt => ctxt addsimps (case_thm_abs :: ctr_thms_abs))
Andreas@68155
   504
    val del_simps = Code_Preproc.map_pre
Andreas@68155
   505
      (fn ctxt => ctxt delsimps (case_thm_abs :: ctr_thms_abs))
Andreas@68155
   506
    val add_post = Code_Preproc.map_post
Andreas@68155
   507
      (fn ctxt => ctxt addsimps ctr_post)
Andreas@68155
   508
    val del_post = Code_Preproc.map_post
Andreas@68155
   509
      (fn ctxt => ctxt delsimps ctr_post)
Andreas@68155
   510
  in
Andreas@68155
   511
    Local_Theory.exit_global lthy10
Andreas@68155
   512
    |> Laziness_Data.map (Symtab.update (type_name,
Andreas@68155
   513
      {eagerT = eagerT, 
Andreas@68155
   514
       lazyT = lazy_type,
Andreas@68155
   515
       ctr = #const lazy_ctr_def,
Andreas@68155
   516
       destr = #const lazy_sel_def,
Andreas@68155
   517
       lazy_ctrs = map #const lazy_ctrs_def,
Andreas@68155
   518
       case_lazy = #const lazy_case_def,
Andreas@68155
   519
       active = true,
Andreas@68155
   520
       activate = add_lazy_ctrs #> add_lazy_ctr_thms #> add_lazy_case_thms #> add_simps #> add_post,
Andreas@68155
   521
       deactivate = add_eager_ctrs #> add_eager_case_thms #> del_simps #> del_post}))
Andreas@68155
   522
    |> add_lazy_ctrs
Andreas@68155
   523
    |> add_ctr_code (map (dest_Const o #const) lazy_ctrs_def) case_ctrs_thms
Andreas@68155
   524
    |> add_code_eqs
Andreas@68155
   525
    |> add_lazy_ctr_thms
Andreas@68155
   526
    |> add_simps
Andreas@68155
   527
    |> add_post
Andreas@68155
   528
  end;
Andreas@68155
   529
Andreas@68155
   530
fun transform_code_eqs _ [] = NONE
Andreas@68155
   531
  | transform_code_eqs ctxt eqs =
Andreas@68155
   532
    let
Andreas@69568
   533
      fun replace_ctr ctxt =
Andreas@69568
   534
        let 
Andreas@69568
   535
          val thy = Proof_Context.theory_of ctxt
Andreas@69568
   536
          val table = Laziness_Data.get thy
Andreas@69568
   537
        in fn (s1, s2) => case Symtab.lookup table s1 of
Andreas@69568
   538
            NONE => false
Andreas@69568
   539
          | SOME x => #active x andalso s2 <> (#ctr x |> dest_Const |> fst)
Andreas@69568
   540
        end
Andreas@68155
   541
      val thy = Proof_Context.theory_of ctxt
Andreas@68155
   542
      val table = Laziness_Data.get thy
Andreas@68155
   543
      fun num_consts_fun (_, T) =
Andreas@68155
   544
        let
Andreas@68155
   545
          val s = body_type T |> dest_Type |> fst
Andreas@68155
   546
        in
Andreas@68155
   547
          if Symtab.defined table s
Andreas@69568
   548
          then Ctr_Sugar.ctr_sugar_of ctxt s |> the |> #ctrs |> length
Andreas@69568
   549
          else Code.get_type thy s |> fst |> snd |> length
Andreas@68155
   550
        end
Andreas@68155
   551
      val eqs = map (apfst (Thm.transfer thy)) eqs;
Andreas@68155
   552
Andreas@68155
   553
      val ((code_eqs, nbe_eqs), pure) =
Andreas@68155
   554
        ((case hd eqs |> fst |> Thm.prop_of of
Andreas@68155
   555
            Const (@{const_name Pure.eq}, _) $ _ $ _ =>
Andreas@68155
   556
              (map (apfst (fn x => x RS @{thm meta_eq_to_obj_eq})) eqs, true)
Andreas@68155
   557
         | _ => (eqs, false))
Andreas@68155
   558
        |> apfst (List.partition snd))
Andreas@68155
   559
        handle THM _ => (([], eqs), false)
Andreas@68155
   560
      val to_original_eq = if pure then map (apfst (fn x => x RS @{thm eq_reflection})) else I
Andreas@68155
   561
    in
Andreas@69568
   562
      case Case_Converter.to_case ctxt (Case_Converter.replace_by_type replace_ctr) num_consts_fun (map fst code_eqs) of
Andreas@68155
   563
          NONE => NONE
Andreas@68155
   564
        | SOME thms => SOME (nbe_eqs @ map (rpair true) thms |> to_original_eq)
Andreas@69568
   565
    end
Andreas@68155
   566
Andreas@68155
   567
val activate_lazy_type = set_active_lazy_type true;
Andreas@68155
   568
val deactivate_lazy_type = set_active_lazy_type false;
Andreas@68155
   569
val activate_lazy_types = set_active_lazy_types true;
Andreas@68155
   570
val deactivate_lazy_types = set_active_lazy_types false;
Andreas@68155
   571
Andreas@68155
   572
fun get_lazy_types thy = Symtab.dest (Laziness_Data.get thy) 
Andreas@68155
   573
Andreas@68155
   574
fun print_lazy_type thy (name, info : lazy_info) = 
Andreas@68155
   575
  let
Andreas@68155
   576
    val ctxt = Proof_Context.init_global thy
Andreas@68155
   577
    fun pretty_ctr ctr = 
Andreas@68155
   578
      let
Andreas@68155
   579
        val argsT = dest_Const ctr |> snd |> binder_types
Andreas@68155
   580
      in
Andreas@68155
   581
        Pretty.block [
Andreas@68155
   582
          Syntax.pretty_term ctxt ctr,
Andreas@68155
   583
          Pretty.brk 1,
Andreas@68155
   584
          Pretty.block (Pretty.separate "" (map (Pretty.quote o Syntax.pretty_typ ctxt) argsT))
Andreas@68155
   585
        ]
Andreas@68155
   586
      end
Andreas@68155
   587
  in
Andreas@68155
   588
    Pretty.block [
Andreas@68155
   589
      Pretty.str (name ^ (if #active info then "" else " (inactive)") ^ ":"),
Andreas@68155
   590
      Pretty.brk 1,
Andreas@68155
   591
      Pretty.block [
Andreas@68155
   592
        Syntax.pretty_typ ctxt (#eagerT info),
Andreas@68155
   593
        Pretty.brk 1,
Andreas@68155
   594
        Pretty.str "=",
Andreas@68155
   595
        Pretty.brk 1,
Andreas@68155
   596
        Syntax.pretty_term ctxt (#ctr info),
Andreas@68155
   597
        Pretty.brk 1,
Andreas@68155
   598
        Pretty.block [
Andreas@68155
   599
          Pretty.str "(",
Andreas@68155
   600
          Syntax.pretty_term ctxt (#destr info),
Andreas@68155
   601
          Pretty.str ":",
Andreas@68155
   602
          Pretty.brk 1,
Andreas@68155
   603
          Syntax.pretty_typ ctxt (Type (@{type_name lazy}, [#lazyT info])),
Andreas@68155
   604
          Pretty.str ")"
Andreas@68155
   605
        ]
Andreas@68155
   606
      ],
Andreas@68155
   607
      Pretty.fbrk,
Andreas@68155
   608
      Pretty.keyword2 "and",
Andreas@68155
   609
      Pretty.brk 1,
Andreas@68155
   610
      Pretty.block ([
Andreas@68155
   611
        Syntax.pretty_typ ctxt (#lazyT info),
Andreas@68155
   612
        Pretty.brk 1,
Andreas@68155
   613
        Pretty.str "=",
Andreas@68155
   614
        Pretty.brk 1] @
Andreas@68155
   615
        Pretty.separate " |" (map pretty_ctr (#lazy_ctrs info)) @ [
Andreas@68155
   616
        Pretty.fbrk,
Andreas@68155
   617
        Pretty.keyword2 "for",
Andreas@68155
   618
        Pretty.brk 1, 
Andreas@68155
   619
        Pretty.str "case:",
Andreas@68155
   620
        Pretty.brk 1,
Andreas@68155
   621
        Syntax.pretty_term ctxt (#case_lazy info)
Andreas@68155
   622
      ])
Andreas@68155
   623
    ]
Andreas@68155
   624
  end;
Andreas@68155
   625
Andreas@68155
   626
fun print_lazy_types thy = 
Andreas@68155
   627
  let
Andreas@68155
   628
    fun cmp ((name1, _), (name2, _)) = string_ord (name1, name2)
Andreas@68155
   629
    val infos = Laziness_Data.get thy |> Symtab.dest |> map (apfst Long_Name.base_name) |> sort cmp
Andreas@68155
   630
  in
Andreas@68155
   631
    Pretty.writeln_chunks (map (print_lazy_type thy) infos)
Andreas@68155
   632
  end;
Andreas@68155
   633
Andreas@68155
   634
Andreas@68155
   635
val _ =
Andreas@68155
   636
  Outer_Syntax.command @{command_keyword code_lazy_type}
Andreas@68155
   637
    "make a lazy copy of the datatype and activate substitution"
Andreas@68155
   638
    (Parse.binding >> (fn b => Toplevel.theory (Binding.name_of b |> code_lazy_type)));
Andreas@68155
   639
val _ =
Andreas@68155
   640
  Outer_Syntax.command @{command_keyword activate_lazy_type}
Andreas@68155
   641
    "activate substitution on a specific (lazy) type"
Andreas@68155
   642
    (Parse.binding >> (fn b => Toplevel.theory (Binding.name_of b |> activate_lazy_type)));
Andreas@68155
   643
val _ =
Andreas@68155
   644
  Outer_Syntax.command @{command_keyword deactivate_lazy_type}
Andreas@68155
   645
    "deactivate substitution on a specific (lazy) type"
Andreas@68155
   646
    (Parse.binding >> (fn b => Toplevel.theory (Binding.name_of b |> deactivate_lazy_type)));
Andreas@68155
   647
val _ =
Andreas@68155
   648
  Outer_Syntax.command @{command_keyword activate_lazy_types}
Andreas@68155
   649
    "activate substitution on all (lazy) types"
Andreas@68155
   650
    (pair (Toplevel.theory activate_lazy_types));
Andreas@68155
   651
val _ =
Andreas@68155
   652
  Outer_Syntax.command @{command_keyword deactivate_lazy_types}
Andreas@68155
   653
    "deactivate substitution on all (lazy) type"
Andreas@68155
   654
    (pair (Toplevel.theory deactivate_lazy_types));
Andreas@68155
   655
val _ =
Andreas@68155
   656
  Outer_Syntax.command @{command_keyword print_lazy_types}
Andreas@68155
   657
    "print the types that have been declared as lazy and their substitution state"
Andreas@68155
   658
    (pair (Toplevel.theory (tap print_lazy_types)));
Andreas@68155
   659
Andreas@68155
   660
end