src/HOL/Imperative_HOL/Heap_Monad.thy
author haftmann
Fri Jul 09 16:58:44 2010 +0200 (2010-07-09)
changeset 37758 bf86a65403a8
parent 37756 59caa6180fff
child 37771 1bec64044b5e
permissions -rw-r--r--
pervasive success combinator
haftmann@26170
     1
(*  Title:      HOL/Library/Heap_Monad.thy
haftmann@26170
     2
    Author:     John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen
haftmann@26170
     3
*)
haftmann@26170
     4
haftmann@26170
     5
header {* A monad with a polymorphic heap *}
haftmann@26170
     6
haftmann@26170
     7
theory Heap_Monad
haftmann@26170
     8
imports Heap
haftmann@26170
     9
begin
haftmann@26170
    10
haftmann@26170
    11
subsection {* The monad *}
haftmann@26170
    12
haftmann@37758
    13
subsubsection {* Monad construction *}
haftmann@26170
    14
haftmann@26170
    15
text {* Monadic heap actions either produce values
haftmann@26170
    16
  and transform the heap, or fail *}
haftmann@37709
    17
datatype 'a Heap = Heap "heap \<Rightarrow> ('a \<times> heap) option"
haftmann@26170
    18
haftmann@37709
    19
primrec execute :: "'a Heap \<Rightarrow> heap \<Rightarrow> ('a \<times> heap) option" where
haftmann@37709
    20
  [code del]: "execute (Heap f) = f"
haftmann@26170
    21
haftmann@37758
    22
lemma Heap_cases [case_names succeed fail]:
haftmann@37758
    23
  fixes f and h
haftmann@37758
    24
  assumes succeed: "\<And>x h'. execute f h = Some (x, h') \<Longrightarrow> P"
haftmann@37758
    25
  assumes fail: "execute f h = None \<Longrightarrow> P"
haftmann@37758
    26
  shows P
haftmann@37758
    27
  using assms by (cases "execute f h") auto
haftmann@37758
    28
haftmann@26170
    29
lemma Heap_execute [simp]:
haftmann@26170
    30
  "Heap (execute f) = f" by (cases f) simp_all
haftmann@26170
    31
haftmann@26170
    32
lemma Heap_eqI:
haftmann@26170
    33
  "(\<And>h. execute f h = execute g h) \<Longrightarrow> f = g"
haftmann@26170
    34
    by (cases f, cases g) (auto simp: expand_fun_eq)
haftmann@26170
    35
haftmann@37758
    36
ML {* structure Execute_Simps = Named_Thms(
haftmann@37758
    37
  val name = "execute_simps"
haftmann@37758
    38
  val description = "simplification rules for execute"
haftmann@37758
    39
) *}
haftmann@37758
    40
haftmann@37758
    41
setup Execute_Simps.setup
haftmann@37758
    42
haftmann@37758
    43
lemma execute_Let [simp, execute_simps]:
haftmann@37758
    44
  "execute (let x = t in f x) = (let x = t in execute (f x))"
haftmann@37758
    45
  by (simp add: Let_def)
haftmann@37758
    46
haftmann@37758
    47
haftmann@37758
    48
subsubsection {* Specialised lifters *}
haftmann@37758
    49
haftmann@37758
    50
definition tap :: "(heap \<Rightarrow> 'a) \<Rightarrow> 'a Heap" where
haftmann@37758
    51
  [code del]: "tap f = Heap (\<lambda>h. Some (f h, h))"
haftmann@37758
    52
haftmann@37758
    53
lemma execute_tap [simp, execute_simps]:
haftmann@37758
    54
  "execute (tap f) h = Some (f h, h)"
haftmann@37758
    55
  by (simp add: tap_def)
haftmann@26170
    56
haftmann@37709
    57
definition heap :: "(heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
haftmann@37709
    58
  [code del]: "heap f = Heap (Some \<circ> f)"
haftmann@26170
    59
haftmann@37758
    60
lemma execute_heap [simp, execute_simps]:
haftmann@37709
    61
  "execute (heap f) = Some \<circ> f"
haftmann@26170
    62
  by (simp add: heap_def)
haftmann@26170
    63
haftmann@37754
    64
definition guard :: "(heap \<Rightarrow> bool) \<Rightarrow> (heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
haftmann@37754
    65
  [code del]: "guard P f = Heap (\<lambda>h. if P h then Some (f h) else None)"
haftmann@37754
    66
haftmann@37758
    67
lemma execute_guard [execute_simps]:
haftmann@37754
    68
  "\<not> P h \<Longrightarrow> execute (guard P f) h = None"
haftmann@37754
    69
  "P h \<Longrightarrow> execute (guard P f) h = Some (f h)"
haftmann@37754
    70
  by (simp_all add: guard_def)
haftmann@37754
    71
haftmann@37758
    72
haftmann@37758
    73
subsubsection {* Predicate classifying successful computations *}
haftmann@37758
    74
haftmann@37758
    75
definition success :: "'a Heap \<Rightarrow> heap \<Rightarrow> bool" where
haftmann@37758
    76
  "success f h \<longleftrightarrow> execute f h \<noteq> None"
haftmann@37758
    77
haftmann@37758
    78
lemma successI:
haftmann@37758
    79
  "execute f h \<noteq> None \<Longrightarrow> success f h"
haftmann@37758
    80
  by (simp add: success_def)
haftmann@37758
    81
haftmann@37758
    82
lemma successE:
haftmann@37758
    83
  assumes "success f h"
haftmann@37758
    84
  obtains r h' where "execute f h = Some (r, h')"
haftmann@37758
    85
  using assms by (auto simp add: success_def)
haftmann@37758
    86
haftmann@37758
    87
ML {* structure Success_Intros = Named_Thms(
haftmann@37758
    88
  val name = "success_intros"
haftmann@37758
    89
  val description = "introduction rules for success"
haftmann@37758
    90
) *}
haftmann@37758
    91
haftmann@37758
    92
setup Success_Intros.setup
haftmann@37758
    93
haftmann@37758
    94
lemma success_tapI [iff, success_intros]:
haftmann@37758
    95
  "success (tap f) h"
haftmann@37758
    96
  by (rule successI) simp
haftmann@37758
    97
haftmann@37758
    98
lemma success_heapI [iff, success_intros]:
haftmann@37758
    99
  "success (heap f) h"
haftmann@37758
   100
  by (rule successI) simp
haftmann@37758
   101
haftmann@37758
   102
lemma success_guardI [success_intros]:
haftmann@37758
   103
  "P h \<Longrightarrow> success (guard P f) h"
haftmann@37758
   104
  by (rule successI) (simp add: execute_guard)
haftmann@37758
   105
haftmann@37758
   106
lemma success_LetI [success_intros]:
haftmann@37758
   107
  "x = t \<Longrightarrow> success (f x) h \<Longrightarrow> success (let x = t in f x) h"
haftmann@37758
   108
  by (simp add: Let_def)
haftmann@37758
   109
haftmann@37758
   110
haftmann@37758
   111
subsubsection {* Monad combinators *}
haftmann@26170
   112
haftmann@37709
   113
definition return :: "'a \<Rightarrow> 'a Heap" where
haftmann@26170
   114
  [code del]: "return x = heap (Pair x)"
haftmann@26170
   115
haftmann@37758
   116
lemma execute_return [simp, execute_simps]:
haftmann@37709
   117
  "execute (return x) = Some \<circ> Pair x"
haftmann@26170
   118
  by (simp add: return_def)
haftmann@26170
   119
haftmann@37758
   120
lemma success_returnI [iff, success_intros]:
haftmann@37758
   121
  "success (return x) h"
haftmann@37758
   122
  by (rule successI) simp
haftmann@37758
   123
haftmann@37709
   124
definition raise :: "string \<Rightarrow> 'a Heap" where -- {* the string is just decoration *}
haftmann@37709
   125
  [code del]: "raise s = Heap (\<lambda>_. None)"
haftmann@26170
   126
haftmann@37758
   127
lemma execute_raise [simp, execute_simps]:
haftmann@37709
   128
  "execute (raise s) = (\<lambda>_. None)"
haftmann@26170
   129
  by (simp add: raise_def)
haftmann@26170
   130
haftmann@37756
   131
definition bind :: "'a Heap \<Rightarrow> ('a \<Rightarrow> 'b Heap) \<Rightarrow> 'b Heap" (infixl ">>=" 54) where
haftmann@37709
   132
  [code del]: "f >>= g = Heap (\<lambda>h. case execute f h of
haftmann@37709
   133
                  Some (x, h') \<Rightarrow> execute (g x) h'
haftmann@37709
   134
                | None \<Rightarrow> None)"
haftmann@37709
   135
haftmann@37756
   136
notation bind (infixl "\<guillemotright>=" 54)
haftmann@37709
   137
haftmann@37758
   138
lemma execute_bind [execute_simps]:
haftmann@37709
   139
  "execute f h = Some (x, h') \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g x) h'"
haftmann@37709
   140
  "execute f h = None \<Longrightarrow> execute (f \<guillemotright>= g) h = None"
haftmann@37756
   141
  by (simp_all add: bind_def)
haftmann@37709
   142
haftmann@37758
   143
lemma success_bindI [success_intros]:
haftmann@37758
   144
  "success f h \<Longrightarrow> success (g (fst (the (execute f h)))) (snd (the (execute f h))) \<Longrightarrow> success (f \<guillemotright>= g) h"
haftmann@37758
   145
  by (auto intro!: successI elim!: successE simp add: bind_def)
haftmann@37758
   146
haftmann@37758
   147
lemma execute_bind_successI [execute_simps]:
haftmann@37758
   148
  "success f h \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g (fst (the (execute f h)))) (snd (the (execute f h)))"
haftmann@37758
   149
  by (cases f h rule: Heap_cases) (auto elim!: successE simp add: bind_def)
haftmann@37709
   150
  
haftmann@37754
   151
lemma execute_eq_SomeI:
haftmann@37754
   152
  assumes "Heap_Monad.execute f h = Some (x, h')"
haftmann@37754
   153
    and "Heap_Monad.execute (g x) h' = Some (y, h'')"
haftmann@37754
   154
  shows "Heap_Monad.execute (f \<guillemotright>= g) h = Some (y, h'')"
haftmann@37756
   155
  using assms by (simp add: bind_def)
haftmann@37754
   156
haftmann@37709
   157
lemma return_bind [simp]: "return x \<guillemotright>= f = f x"
haftmann@37758
   158
  by (rule Heap_eqI) (simp add: execute_bind)
haftmann@37709
   159
haftmann@37709
   160
lemma bind_return [simp]: "f \<guillemotright>= return = f"
haftmann@37756
   161
  by (rule Heap_eqI) (simp add: bind_def split: option.splits)
haftmann@37709
   162
haftmann@37709
   163
lemma bind_bind [simp]: "(f \<guillemotright>= g) \<guillemotright>= k = f \<guillemotright>= (\<lambda>x. g x \<guillemotright>= k)"
haftmann@37756
   164
  by (rule Heap_eqI) (simp add: bind_def split: option.splits)
haftmann@37709
   165
haftmann@37709
   166
lemma raise_bind [simp]: "raise e \<guillemotright>= f = raise e"
haftmann@37758
   167
  by (rule Heap_eqI) (simp add: execute_bind)
haftmann@37709
   168
haftmann@37754
   169
abbreviation chain :: "'a Heap \<Rightarrow> 'b Heap \<Rightarrow> 'b Heap"  (infixl ">>" 54) where
haftmann@37709
   170
  "f >> g \<equiv> f >>= (\<lambda>_. g)"
haftmann@37709
   171
haftmann@37754
   172
notation chain (infixl "\<guillemotright>" 54)
haftmann@37709
   173
haftmann@26170
   174
haftmann@26170
   175
subsubsection {* do-syntax *}
haftmann@26170
   176
haftmann@26170
   177
text {*
haftmann@26170
   178
  We provide a convenient do-notation for monadic expressions
haftmann@26170
   179
  well-known from Haskell.  @{const Let} is printed
haftmann@26170
   180
  specially in do-expressions.
haftmann@26170
   181
*}
haftmann@26170
   182
haftmann@26170
   183
nonterminals do_expr
haftmann@26170
   184
haftmann@26170
   185
syntax
haftmann@26170
   186
  "_do" :: "do_expr \<Rightarrow> 'a"
haftmann@26170
   187
    ("(do (_)//done)" [12] 100)
haftmann@37754
   188
  "_bind" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@26170
   189
    ("_ <- _;//_" [1000, 13, 12] 12)
haftmann@37754
   190
  "_chain" :: "'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@26170
   191
    ("_;//_" [13, 12] 12)
haftmann@26170
   192
  "_let" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@26170
   193
    ("let _ = _;//_" [1000, 13, 12] 12)
haftmann@26170
   194
  "_nil" :: "'a \<Rightarrow> do_expr"
haftmann@26170
   195
    ("_" [12] 12)
haftmann@26170
   196
haftmann@26170
   197
syntax (xsymbols)
haftmann@37754
   198
  "_bind" :: "pttrn \<Rightarrow> 'a \<Rightarrow> do_expr \<Rightarrow> do_expr"
haftmann@26170
   199
    ("_ \<leftarrow> _;//_" [1000, 13, 12] 12)
haftmann@26170
   200
haftmann@26170
   201
translations
haftmann@28145
   202
  "_do f" => "f"
haftmann@37754
   203
  "_bind x f g" => "f \<guillemotright>= (\<lambda>x. g)"
haftmann@37754
   204
  "_chain f g" => "f \<guillemotright> g"
haftmann@26170
   205
  "_let x t f" => "CONST Let t (\<lambda>x. f)"
haftmann@26170
   206
  "_nil f" => "f"
haftmann@26170
   207
haftmann@26170
   208
print_translation {*
haftmann@26170
   209
let
haftmann@26170
   210
  fun dest_abs_eta (Abs (abs as (_, ty, _))) =
haftmann@26170
   211
        let
haftmann@26170
   212
          val (v, t) = Syntax.variant_abs abs;
haftmann@28145
   213
        in (Free (v, ty), t) end
haftmann@26170
   214
    | dest_abs_eta t =
haftmann@26170
   215
        let
haftmann@26170
   216
          val (v, t) = Syntax.variant_abs ("", dummyT, t $ Bound 0);
haftmann@28145
   217
        in (Free (v, dummyT), t) end;
haftmann@37756
   218
  fun unfold_monad (Const (@{const_syntax bind}, _) $ f $ g) =
haftmann@26170
   219
        let
haftmann@28145
   220
          val (v, g') = dest_abs_eta g;
haftmann@28145
   221
          val vs = fold_aterms (fn Free (v, _) => insert (op =) v | _ => I) v [];
haftmann@26170
   222
          val v_used = fold_aterms
haftmann@28145
   223
            (fn Free (w, _) => (fn s => s orelse member (op =) vs w) | _ => I) g' false;
haftmann@26170
   224
        in if v_used then
haftmann@37754
   225
          Const (@{syntax_const "_bind"}, dummyT) $ v $ f $ unfold_monad g'
haftmann@26170
   226
        else
haftmann@37754
   227
          Const (@{syntax_const "_chain"}, dummyT) $ f $ unfold_monad g'
haftmann@26170
   228
        end
haftmann@37754
   229
    | unfold_monad (Const (@{const_syntax chain}, _) $ f $ g) =
haftmann@37754
   230
        Const (@{syntax_const "_chain"}, dummyT) $ f $ unfold_monad g
haftmann@26170
   231
    | unfold_monad (Const (@{const_syntax Let}, _) $ f $ g) =
haftmann@26170
   232
        let
haftmann@28145
   233
          val (v, g') = dest_abs_eta g;
wenzelm@35113
   234
        in Const (@{syntax_const "_let"}, dummyT) $ v $ f $ unfold_monad g' end
haftmann@26170
   235
    | unfold_monad (Const (@{const_syntax Pair}, _) $ f) =
haftmann@28145
   236
        Const (@{const_syntax return}, dummyT) $ f
haftmann@26170
   237
    | unfold_monad f = f;
haftmann@37756
   238
  fun contains_bind (Const (@{const_syntax bind}, _) $ _ $ _) = true
haftmann@37754
   239
    | contains_bind (Const (@{const_syntax Let}, _) $ _ $ Abs (_, _, t)) =
haftmann@37754
   240
        contains_bind t;
haftmann@37756
   241
  fun bind_monad_tr' (f::g::ts) = list_comb
wenzelm@35113
   242
    (Const (@{syntax_const "_do"}, dummyT) $
haftmann@37756
   243
      unfold_monad (Const (@{const_syntax bind}, dummyT) $ f $ g), ts);
wenzelm@35113
   244
  fun Let_monad_tr' (f :: (g as Abs (_, _, g')) :: ts) =
haftmann@37754
   245
    if contains_bind g' then list_comb
wenzelm@35113
   246
      (Const (@{syntax_const "_do"}, dummyT) $
wenzelm@35113
   247
        unfold_monad (Const (@{const_syntax Let}, dummyT) $ f $ g), ts)
haftmann@28145
   248
    else raise Match;
wenzelm@35113
   249
in
haftmann@37756
   250
 [(@{const_syntax bind}, bind_monad_tr'),
wenzelm@35113
   251
  (@{const_syntax Let}, Let_monad_tr')]
wenzelm@35113
   252
end;
haftmann@26170
   253
*}
haftmann@26170
   254
haftmann@26170
   255
haftmann@37758
   256
subsection {* Generic combinators *}
haftmann@26170
   257
haftmann@37758
   258
subsubsection {* Assertions *}
haftmann@26170
   259
haftmann@37709
   260
definition assert :: "('a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a Heap" where
haftmann@37709
   261
  "assert P x = (if P x then return x else raise ''assert'')"
haftmann@28742
   262
haftmann@37758
   263
lemma execute_assert [execute_simps]:
haftmann@37754
   264
  "P x \<Longrightarrow> execute (assert P x) h = Some (x, h)"
haftmann@37754
   265
  "\<not> P x \<Longrightarrow> execute (assert P x) h = None"
haftmann@37754
   266
  by (simp_all add: assert_def)
haftmann@37754
   267
haftmann@37758
   268
lemma success_assertI [success_intros]:
haftmann@37758
   269
  "P x \<Longrightarrow> success (assert P x) h"
haftmann@37758
   270
  by (rule successI) (simp add: execute_assert)
haftmann@37758
   271
haftmann@28742
   272
lemma assert_cong [fundef_cong]:
haftmann@28742
   273
  assumes "P = P'"
haftmann@28742
   274
  assumes "\<And>x. P' x \<Longrightarrow> f x = f' x"
haftmann@28742
   275
  shows "(assert P x >>= f) = (assert P' x >>= f')"
haftmann@37754
   276
  by (rule Heap_eqI) (insert assms, simp add: assert_def)
haftmann@28742
   277
haftmann@37758
   278
haftmann@37758
   279
subsubsection {* Plain lifting *}
haftmann@37758
   280
haftmann@37754
   281
definition lift :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b Heap" where
haftmann@37754
   282
  "lift f = return o f"
haftmann@37709
   283
haftmann@37754
   284
lemma lift_collapse [simp]:
haftmann@37754
   285
  "lift f x = return (f x)"
haftmann@37754
   286
  by (simp add: lift_def)
haftmann@37709
   287
haftmann@37754
   288
lemma bind_lift:
haftmann@37754
   289
  "(f \<guillemotright>= lift g) = (f \<guillemotright>= (\<lambda>x. return (g x)))"
haftmann@37754
   290
  by (simp add: lift_def comp_def)
haftmann@37709
   291
haftmann@37758
   292
haftmann@37758
   293
subsubsection {* Iteration -- warning: this is rarely useful! *}
haftmann@37758
   294
haftmann@37756
   295
primrec fold_map :: "('a \<Rightarrow> 'b Heap) \<Rightarrow> 'a list \<Rightarrow> 'b list Heap" where
haftmann@37756
   296
  "fold_map f [] = return []"
haftmann@37756
   297
| "fold_map f (x # xs) = do
haftmann@37709
   298
     y \<leftarrow> f x;
haftmann@37756
   299
     ys \<leftarrow> fold_map f xs;
haftmann@37709
   300
     return (y # ys)
haftmann@37709
   301
   done"
haftmann@37709
   302
haftmann@37756
   303
lemma fold_map_append:
haftmann@37756
   304
  "fold_map f (xs @ ys) = fold_map f xs \<guillemotright>= (\<lambda>xs. fold_map f ys \<guillemotright>= (\<lambda>ys. return (xs @ ys)))"
haftmann@37754
   305
  by (induct xs) simp_all
haftmann@37754
   306
haftmann@37758
   307
lemma execute_fold_map_unchanged_heap [execute_simps]:
haftmann@37754
   308
  assumes "\<And>x. x \<in> set xs \<Longrightarrow> \<exists>y. execute (f x) h = Some (y, h)"
haftmann@37756
   309
  shows "execute (fold_map f xs) h =
haftmann@37754
   310
    Some (List.map (\<lambda>x. fst (the (execute (f x) h))) xs, h)"
haftmann@37754
   311
using assms proof (induct xs)
haftmann@37754
   312
  case Nil show ?case by simp
haftmann@37754
   313
next
haftmann@37754
   314
  case (Cons x xs)
haftmann@37754
   315
  from Cons.prems obtain y
haftmann@37754
   316
    where y: "execute (f x) h = Some (y, h)" by auto
haftmann@37756
   317
  moreover from Cons.prems Cons.hyps have "execute (fold_map f xs) h =
haftmann@37754
   318
    Some (map (\<lambda>x. fst (the (execute (f x) h))) xs, h)" by auto
haftmann@37754
   319
  ultimately show ?case by (simp, simp only: execute_bind(1), simp)
haftmann@37754
   320
qed
haftmann@37754
   321
haftmann@37709
   322
bulwahn@34051
   323
subsubsection {* A monadic combinator for simple recursive functions *}
bulwahn@36057
   324
bulwahn@36057
   325
text {* Using a locale to fix arguments f and g of MREC *}
bulwahn@36057
   326
bulwahn@36057
   327
locale mrec =
haftmann@37709
   328
  fixes f :: "'a \<Rightarrow> ('b + 'a) Heap"
haftmann@37709
   329
  and g :: "'a \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> 'b Heap"
bulwahn@36057
   330
begin
bulwahn@36057
   331
haftmann@37709
   332
function (default "\<lambda>(x, h). None") mrec :: "'a \<Rightarrow> heap \<Rightarrow> ('b \<times> heap) option" where
haftmann@37709
   333
  "mrec x h = (case execute (f x) h of
haftmann@37709
   334
     Some (Inl r, h') \<Rightarrow> Some (r, h')
haftmann@37709
   335
   | Some (Inr s, h') \<Rightarrow> (case mrec s h' of
haftmann@37709
   336
             Some (z, h'') \<Rightarrow> execute (g x s z) h''
haftmann@37709
   337
           | None \<Rightarrow> None)
haftmann@37709
   338
   | None \<Rightarrow> None)"
bulwahn@34051
   339
by auto
bulwahn@34051
   340
bulwahn@34051
   341
lemma graph_implies_dom:
wenzelm@35423
   342
  "mrec_graph x y \<Longrightarrow> mrec_dom x"
bulwahn@34051
   343
apply (induct rule:mrec_graph.induct) 
bulwahn@34051
   344
apply (rule accpI)
bulwahn@34051
   345
apply (erule mrec_rel.cases)
bulwahn@34051
   346
by simp
bulwahn@34051
   347
haftmann@37709
   348
lemma mrec_default: "\<not> mrec_dom (x, h) \<Longrightarrow> mrec x h = None"
wenzelm@35423
   349
  unfolding mrec_def 
bulwahn@36057
   350
  by (rule fundef_default_value[OF mrec_sumC_def graph_implies_dom, of _ _ "(x, h)", simplified])
bulwahn@34051
   351
bulwahn@36057
   352
lemma mrec_di_reverse: 
bulwahn@36057
   353
  assumes "\<not> mrec_dom (x, h)"
bulwahn@34051
   354
  shows "
haftmann@37709
   355
   (case execute (f x) h of
haftmann@37709
   356
     Some (Inl r, h') \<Rightarrow> False
haftmann@37709
   357
   | Some (Inr s, h') \<Rightarrow> \<not> mrec_dom (s, h')
haftmann@37709
   358
   | None \<Rightarrow> False
bulwahn@34051
   359
   )" 
haftmann@37709
   360
using assms apply (auto split: option.split sum.split)
haftmann@37709
   361
apply (rule ccontr)
haftmann@37709
   362
apply (erule notE, rule accpI, elim mrec_rel.cases, auto)+
haftmann@37709
   363
done
bulwahn@34051
   364
bulwahn@34051
   365
lemma mrec_rule:
bulwahn@36057
   366
  "mrec x h = 
haftmann@37709
   367
   (case execute (f x) h of
haftmann@37709
   368
     Some (Inl r, h') \<Rightarrow> Some (r, h')
haftmann@37709
   369
   | Some (Inr s, h') \<Rightarrow> 
bulwahn@36057
   370
          (case mrec s h' of
haftmann@37709
   371
             Some (z, h'') \<Rightarrow> execute (g x s z) h''
haftmann@37709
   372
           | None \<Rightarrow> None)
haftmann@37709
   373
   | None \<Rightarrow> None
bulwahn@34051
   374
   )"
bulwahn@36057
   375
apply (cases "mrec_dom (x,h)", simp)
bulwahn@36057
   376
apply (frule mrec_default)
bulwahn@36057
   377
apply (frule mrec_di_reverse, simp)
haftmann@37709
   378
by (auto split: sum.split option.split simp: mrec_default)
bulwahn@34051
   379
bulwahn@34051
   380
definition
bulwahn@36057
   381
  "MREC x = Heap (mrec x)"
bulwahn@34051
   382
bulwahn@34051
   383
lemma MREC_rule:
bulwahn@36057
   384
  "MREC x = 
bulwahn@34051
   385
  (do y \<leftarrow> f x;
bulwahn@34051
   386
                (case y of 
bulwahn@34051
   387
                Inl r \<Rightarrow> return r
bulwahn@34051
   388
              | Inr s \<Rightarrow> 
bulwahn@36057
   389
                do z \<leftarrow> MREC s ;
bulwahn@34051
   390
                   g x s z
bulwahn@34051
   391
                done) done)"
bulwahn@34051
   392
  unfolding MREC_def
haftmann@37756
   393
  unfolding bind_def return_def
bulwahn@34051
   394
  apply simp
bulwahn@34051
   395
  apply (rule ext)
bulwahn@36057
   396
  apply (unfold mrec_rule[of x])
haftmann@37709
   397
  by (auto split: option.splits prod.splits sum.splits)
bulwahn@36057
   398
bulwahn@36057
   399
lemma MREC_pinduct:
haftmann@37709
   400
  assumes "execute (MREC x) h = Some (r, h')"
haftmann@37709
   401
  assumes non_rec_case: "\<And> x h h' r. execute (f x) h = Some (Inl r, h') \<Longrightarrow> P x h h' r"
haftmann@37709
   402
  assumes rec_case: "\<And> x h h1 h2 h' s z r. execute (f x) h = Some (Inr s, h1) \<Longrightarrow> execute (MREC s) h1 = Some (z, h2) \<Longrightarrow> P s h1 h2 z
haftmann@37709
   403
    \<Longrightarrow> execute (g x s z) h2 = Some (r, h') \<Longrightarrow> P x h h' r"
bulwahn@36057
   404
  shows "P x h h' r"
bulwahn@36057
   405
proof -
haftmann@37709
   406
  from assms(1) have mrec: "mrec x h = Some (r, h')"
bulwahn@36057
   407
    unfolding MREC_def execute.simps .
bulwahn@36057
   408
  from mrec have dom: "mrec_dom (x, h)"
bulwahn@36057
   409
    apply -
bulwahn@36057
   410
    apply (rule ccontr)
bulwahn@36057
   411
    apply (drule mrec_default) by auto
haftmann@37709
   412
  from mrec have h'_r: "h' = snd (the (mrec x h))" "r = fst (the (mrec x h))"
bulwahn@36057
   413
    by auto
haftmann@37709
   414
  from mrec have "P x h (snd (the (mrec x h))) (fst (the (mrec x h)))"
bulwahn@36057
   415
  proof (induct arbitrary: r h' rule: mrec.pinduct[OF dom])
bulwahn@36057
   416
    case (1 x h)
haftmann@37709
   417
    obtain rr h' where "the (mrec x h) = (rr, h')" by fastsimp
bulwahn@36057
   418
    show ?case
haftmann@37709
   419
    proof (cases "execute (f x) h")
haftmann@37709
   420
      case (Some result)
haftmann@37709
   421
      then obtain a h1 where exec_f: "execute (f x) h = Some (a, h1)" by fastsimp
bulwahn@36057
   422
      note Inl' = this
bulwahn@36057
   423
      show ?thesis
bulwahn@36057
   424
      proof (cases a)
bulwahn@36057
   425
        case (Inl aa)
bulwahn@36057
   426
        from this Inl' 1(1) exec_f mrec non_rec_case show ?thesis
bulwahn@36057
   427
          by auto
bulwahn@36057
   428
      next
bulwahn@36057
   429
        case (Inr b)
bulwahn@36057
   430
        note Inr' = this
haftmann@37709
   431
        show ?thesis
haftmann@37709
   432
        proof (cases "mrec b h1")
haftmann@37709
   433
          case (Some result)
haftmann@37709
   434
          then obtain aaa h2 where mrec_rec: "mrec b h1 = Some (aaa, h2)" by fastsimp
haftmann@37709
   435
          moreover from this have "P b h1 (snd (the (mrec b h1))) (fst (the (mrec b h1)))"
haftmann@37709
   436
            apply (intro 1(2))
haftmann@37709
   437
            apply (auto simp add: Inr Inl')
haftmann@37709
   438
            done
haftmann@37709
   439
          moreover note mrec mrec_rec exec_f Inl' Inr' 1(1) 1(3)
haftmann@37709
   440
          ultimately show ?thesis
haftmann@37709
   441
            apply auto
haftmann@37709
   442
            apply (rule rec_case)
haftmann@37709
   443
            apply auto
haftmann@37709
   444
            unfolding MREC_def by auto
bulwahn@36057
   445
        next
haftmann@37709
   446
          case None
haftmann@37709
   447
          from this 1(1) exec_f mrec Inr' 1(3) show ?thesis by auto
bulwahn@36057
   448
        qed
bulwahn@36057
   449
      qed
bulwahn@36057
   450
    next
haftmann@37709
   451
      case None
haftmann@37709
   452
      from this 1(1) mrec 1(3) show ?thesis by simp
bulwahn@36057
   453
    qed
bulwahn@36057
   454
  qed
bulwahn@36057
   455
  from this h'_r show ?thesis by simp
bulwahn@36057
   456
qed
bulwahn@36057
   457
bulwahn@36057
   458
end
bulwahn@36057
   459
bulwahn@36057
   460
text {* Providing global versions of the constant and the theorems *}
bulwahn@36057
   461
bulwahn@36057
   462
abbreviation "MREC == mrec.MREC"
bulwahn@36057
   463
lemmas MREC_rule = mrec.MREC_rule
bulwahn@36057
   464
lemmas MREC_pinduct = mrec.MREC_pinduct
bulwahn@36057
   465
haftmann@26182
   466
haftmann@26182
   467
subsection {* Code generator setup *}
haftmann@26182
   468
haftmann@26182
   469
subsubsection {* Logical intermediate layer *}
haftmann@26182
   470
haftmann@37709
   471
primrec raise' :: "String.literal \<Rightarrow> 'a Heap" where
haftmann@37709
   472
  [code del, code_post]: "raise' (STR s) = raise s"
haftmann@26182
   473
haftmann@37709
   474
lemma raise_raise' [code_inline]:
haftmann@37709
   475
  "raise s = raise' (STR s)"
haftmann@37709
   476
  by simp
haftmann@26182
   477
haftmann@37709
   478
code_datatype raise' -- {* avoid @{const "Heap"} formally *}
haftmann@26182
   479
haftmann@26182
   480
haftmann@27707
   481
subsubsection {* SML and OCaml *}
haftmann@26182
   482
haftmann@26752
   483
code_type Heap (SML "unit/ ->/ _")
haftmann@27826
   484
code_const "op \<guillemotright>=" (SML "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())")
haftmann@27707
   485
code_const return (SML "!(fn/ ()/ =>/ _)")
haftmann@37709
   486
code_const Heap_Monad.raise' (SML "!(raise/ Fail/ _)")
haftmann@26182
   487
haftmann@37754
   488
code_type Heap (OCaml "unit/ ->/ _")
haftmann@27826
   489
code_const "op \<guillemotright>=" (OCaml "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())")
haftmann@27707
   490
code_const return (OCaml "!(fun/ ()/ ->/ _)")
haftmann@37709
   491
code_const Heap_Monad.raise' (OCaml "failwith/ _")
haftmann@27707
   492
haftmann@31871
   493
setup {*
haftmann@31871
   494
haftmann@31871
   495
let
haftmann@27707
   496
haftmann@31871
   497
open Code_Thingol;
haftmann@31871
   498
haftmann@31871
   499
fun imp_program naming =
haftmann@27707
   500
haftmann@31871
   501
  let
haftmann@31871
   502
    fun is_const c = case lookup_const naming c
haftmann@31871
   503
     of SOME c' => (fn c'' => c' = c'')
haftmann@31871
   504
      | NONE => K false;
haftmann@37756
   505
    val is_bind = is_const @{const_name bind};
haftmann@31871
   506
    val is_return = is_const @{const_name return};
haftmann@31893
   507
    val dummy_name = "";
haftmann@31871
   508
    val dummy_type = ITyVar dummy_name;
haftmann@31893
   509
    val dummy_case_term = IVar NONE;
haftmann@31871
   510
    (*assumption: dummy values are not relevant for serialization*)
haftmann@31871
   511
    val unitt = case lookup_const naming @{const_name Unity}
haftmann@31871
   512
     of SOME unit' => IConst (unit', (([], []), []))
haftmann@31871
   513
      | NONE => error ("Must include " ^ @{const_name Unity} ^ " in generated constants.");
haftmann@31871
   514
    fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t)
haftmann@31871
   515
      | dest_abs (t, ty) =
haftmann@31871
   516
          let
haftmann@31871
   517
            val vs = fold_varnames cons t [];
haftmann@31871
   518
            val v = Name.variant vs "x";
haftmann@31871
   519
            val ty' = (hd o fst o unfold_fun) ty;
haftmann@31893
   520
          in ((SOME v, ty'), t `$ IVar (SOME v)) end;
haftmann@31871
   521
    fun force (t as IConst (c, _) `$ t') = if is_return c
haftmann@31871
   522
          then t' else t `$ unitt
haftmann@31871
   523
      | force t = t `$ unitt;
haftmann@31871
   524
    fun tr_bind' [(t1, _), (t2, ty2)] =
haftmann@31871
   525
      let
haftmann@31871
   526
        val ((v, ty), t) = dest_abs (t2, ty2);
haftmann@31871
   527
      in ICase (((force t1, ty), [(IVar v, tr_bind'' t)]), dummy_case_term) end
haftmann@31871
   528
    and tr_bind'' t = case unfold_app t
haftmann@37754
   529
         of (IConst (c, (_, ty1 :: ty2 :: _)), [x1, x2]) => if is_bind c
haftmann@31871
   530
              then tr_bind' [(x1, ty1), (x2, ty2)]
haftmann@31871
   531
              else force t
haftmann@31871
   532
          | _ => force t;
haftmann@31893
   533
    fun imp_monad_bind'' ts = (SOME dummy_name, dummy_type) `|=> ICase (((IVar (SOME dummy_name), dummy_type),
haftmann@31871
   534
      [(unitt, tr_bind' ts)]), dummy_case_term)
haftmann@37754
   535
    and imp_monad_bind' (const as (c, (_, tys))) ts = if is_bind c then case (ts, tys)
haftmann@31871
   536
       of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)]
haftmann@31871
   537
        | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3
haftmann@31871
   538
        | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts))
haftmann@31871
   539
      else IConst const `$$ map imp_monad_bind ts
haftmann@31871
   540
    and imp_monad_bind (IConst const) = imp_monad_bind' const []
haftmann@31871
   541
      | imp_monad_bind (t as IVar _) = t
haftmann@31871
   542
      | imp_monad_bind (t as _ `$ _) = (case unfold_app t
haftmann@31871
   543
         of (IConst const, ts) => imp_monad_bind' const ts
haftmann@31871
   544
          | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts)
haftmann@31871
   545
      | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t
haftmann@31871
   546
      | imp_monad_bind (ICase (((t, ty), pats), t0)) = ICase
haftmann@31871
   547
          (((imp_monad_bind t, ty),
haftmann@31871
   548
            (map o pairself) imp_monad_bind pats),
haftmann@31871
   549
              imp_monad_bind t0);
haftmann@28663
   550
haftmann@31871
   551
  in (Graph.map_nodes o map_terms_stmt) imp_monad_bind end;
haftmann@27707
   552
haftmann@27707
   553
in
haftmann@27707
   554
haftmann@31871
   555
Code_Target.extend_target ("SML_imp", ("SML", imp_program))
haftmann@31871
   556
#> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program))
haftmann@27707
   557
haftmann@27707
   558
end
haftmann@31871
   559
haftmann@27707
   560
*}
haftmann@27707
   561
haftmann@26182
   562
haftmann@26182
   563
subsubsection {* Haskell *}
haftmann@26182
   564
haftmann@26182
   565
text {* Adaption layer *}
haftmann@26182
   566
haftmann@29793
   567
code_include Haskell "Heap"
haftmann@26182
   568
{*import qualified Control.Monad;
haftmann@26182
   569
import qualified Control.Monad.ST;
haftmann@26182
   570
import qualified Data.STRef;
haftmann@26182
   571
import qualified Data.Array.ST;
haftmann@26182
   572
haftmann@27695
   573
type RealWorld = Control.Monad.ST.RealWorld;
haftmann@26182
   574
type ST s a = Control.Monad.ST.ST s a;
haftmann@26182
   575
type STRef s a = Data.STRef.STRef s a;
haftmann@27673
   576
type STArray s a = Data.Array.ST.STArray s Int a;
haftmann@26182
   577
haftmann@26182
   578
newSTRef = Data.STRef.newSTRef;
haftmann@26182
   579
readSTRef = Data.STRef.readSTRef;
haftmann@26182
   580
writeSTRef = Data.STRef.writeSTRef;
haftmann@26182
   581
haftmann@27673
   582
newArray :: (Int, Int) -> a -> ST s (STArray s a);
haftmann@26182
   583
newArray = Data.Array.ST.newArray;
haftmann@26182
   584
haftmann@27673
   585
newListArray :: (Int, Int) -> [a] -> ST s (STArray s a);
haftmann@26182
   586
newListArray = Data.Array.ST.newListArray;
haftmann@26182
   587
haftmann@27673
   588
lengthArray :: STArray s a -> ST s Int;
haftmann@27673
   589
lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a);
haftmann@26182
   590
haftmann@27673
   591
readArray :: STArray s a -> Int -> ST s a;
haftmann@26182
   592
readArray = Data.Array.ST.readArray;
haftmann@26182
   593
haftmann@27673
   594
writeArray :: STArray s a -> Int -> a -> ST s ();
haftmann@26182
   595
writeArray = Data.Array.ST.writeArray;*}
haftmann@26182
   596
haftmann@29793
   597
code_reserved Haskell Heap
haftmann@26182
   598
haftmann@26182
   599
text {* Monad *}
haftmann@26182
   600
haftmann@29793
   601
code_type Heap (Haskell "Heap.ST/ Heap.RealWorld/ _")
haftmann@28145
   602
code_monad "op \<guillemotright>=" Haskell
haftmann@26182
   603
code_const return (Haskell "return")
haftmann@37709
   604
code_const Heap_Monad.raise' (Haskell "error/ _")
haftmann@26182
   605
haftmann@37758
   606
hide_const (open) Heap heap guard raise' fold_map
haftmann@37724
   607
haftmann@26170
   608
end