src/HOL/Imperative_HOL/Heap_Monad.thy
author haftmann
Mon Nov 22 09:37:39 2010 +0100 (2010-11-22)
changeset 40671 5e46057ba8e0
parent 40267 a03e288d7902
child 41413 64cd30d6b0b8
permissions -rw-r--r--
renamed slightly ambivalent crel to effect
haftmann@37787
     1
(*  Title:      HOL/Imperative_HOL/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@37771
     5
header {* A monad with a polymorphic heap and primitive reasoning infrastructure *}
haftmann@26170
     6
haftmann@26170
     7
theory Heap_Monad
haftmann@37964
     8
imports Heap Monad_Syntax Code_Natural
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@40266
    19
lemma [code, code del]:
haftmann@40266
    20
  "(Code_Evaluation.term_of :: 'a::typerep Heap \<Rightarrow> Code_Evaluation.term) = Code_Evaluation.term_of"
haftmann@40266
    21
  ..
haftmann@40266
    22
haftmann@37709
    23
primrec execute :: "'a Heap \<Rightarrow> heap \<Rightarrow> ('a \<times> heap) option" where
haftmann@37709
    24
  [code del]: "execute (Heap f) = f"
haftmann@26170
    25
haftmann@37758
    26
lemma Heap_cases [case_names succeed fail]:
haftmann@37758
    27
  fixes f and h
haftmann@37758
    28
  assumes succeed: "\<And>x h'. execute f h = Some (x, h') \<Longrightarrow> P"
haftmann@37758
    29
  assumes fail: "execute f h = None \<Longrightarrow> P"
haftmann@37758
    30
  shows P
haftmann@37758
    31
  using assms by (cases "execute f h") auto
haftmann@37758
    32
haftmann@26170
    33
lemma Heap_execute [simp]:
haftmann@26170
    34
  "Heap (execute f) = f" by (cases f) simp_all
haftmann@26170
    35
haftmann@26170
    36
lemma Heap_eqI:
haftmann@26170
    37
  "(\<And>h. execute f h = execute g h) \<Longrightarrow> f = g"
nipkow@39302
    38
    by (cases f, cases g) (auto simp: fun_eq_iff)
haftmann@26170
    39
haftmann@37758
    40
ML {* structure Execute_Simps = Named_Thms(
haftmann@37758
    41
  val name = "execute_simps"
haftmann@37758
    42
  val description = "simplification rules for execute"
haftmann@37758
    43
) *}
haftmann@37758
    44
haftmann@37758
    45
setup Execute_Simps.setup
haftmann@37758
    46
haftmann@37787
    47
lemma execute_Let [execute_simps]:
haftmann@37758
    48
  "execute (let x = t in f x) = (let x = t in execute (f x))"
haftmann@37758
    49
  by (simp add: Let_def)
haftmann@37758
    50
haftmann@37758
    51
haftmann@37758
    52
subsubsection {* Specialised lifters *}
haftmann@37758
    53
haftmann@37758
    54
definition tap :: "(heap \<Rightarrow> 'a) \<Rightarrow> 'a Heap" where
haftmann@37758
    55
  [code del]: "tap f = Heap (\<lambda>h. Some (f h, h))"
haftmann@37758
    56
haftmann@37787
    57
lemma execute_tap [execute_simps]:
haftmann@37758
    58
  "execute (tap f) h = Some (f h, h)"
haftmann@37758
    59
  by (simp add: tap_def)
haftmann@26170
    60
haftmann@37709
    61
definition heap :: "(heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
haftmann@37709
    62
  [code del]: "heap f = Heap (Some \<circ> f)"
haftmann@26170
    63
haftmann@37787
    64
lemma execute_heap [execute_simps]:
haftmann@37709
    65
  "execute (heap f) = Some \<circ> f"
haftmann@26170
    66
  by (simp add: heap_def)
haftmann@26170
    67
haftmann@37754
    68
definition guard :: "(heap \<Rightarrow> bool) \<Rightarrow> (heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
haftmann@37754
    69
  [code del]: "guard P f = Heap (\<lambda>h. if P h then Some (f h) else None)"
haftmann@37754
    70
haftmann@37758
    71
lemma execute_guard [execute_simps]:
haftmann@37754
    72
  "\<not> P h \<Longrightarrow> execute (guard P f) h = None"
haftmann@37754
    73
  "P h \<Longrightarrow> execute (guard P f) h = Some (f h)"
haftmann@37754
    74
  by (simp_all add: guard_def)
haftmann@37754
    75
haftmann@37758
    76
haftmann@37758
    77
subsubsection {* Predicate classifying successful computations *}
haftmann@37758
    78
haftmann@37758
    79
definition success :: "'a Heap \<Rightarrow> heap \<Rightarrow> bool" where
haftmann@37758
    80
  "success f h \<longleftrightarrow> execute f h \<noteq> None"
haftmann@37758
    81
haftmann@37758
    82
lemma successI:
haftmann@37758
    83
  "execute f h \<noteq> None \<Longrightarrow> success f h"
haftmann@37758
    84
  by (simp add: success_def)
haftmann@37758
    85
haftmann@37758
    86
lemma successE:
haftmann@37758
    87
  assumes "success f h"
haftmann@37771
    88
  obtains r h' where "r = fst (the (execute c h))"
haftmann@37771
    89
    and "h' = snd (the (execute c h))"
haftmann@37771
    90
    and "execute f h \<noteq> None"
haftmann@37771
    91
  using assms by (simp add: success_def)
haftmann@37758
    92
haftmann@37758
    93
ML {* structure Success_Intros = Named_Thms(
haftmann@37758
    94
  val name = "success_intros"
haftmann@37758
    95
  val description = "introduction rules for success"
haftmann@37758
    96
) *}
haftmann@37758
    97
haftmann@37758
    98
setup Success_Intros.setup
haftmann@37758
    99
haftmann@37787
   100
lemma success_tapI [success_intros]:
haftmann@37758
   101
  "success (tap f) h"
haftmann@37787
   102
  by (rule successI) (simp add: execute_simps)
haftmann@37758
   103
haftmann@37787
   104
lemma success_heapI [success_intros]:
haftmann@37758
   105
  "success (heap f) h"
haftmann@37787
   106
  by (rule successI) (simp add: execute_simps)
haftmann@37758
   107
haftmann@37758
   108
lemma success_guardI [success_intros]:
haftmann@37758
   109
  "P h \<Longrightarrow> success (guard P f) h"
haftmann@37758
   110
  by (rule successI) (simp add: execute_guard)
haftmann@37758
   111
haftmann@37758
   112
lemma success_LetI [success_intros]:
haftmann@37758
   113
  "x = t \<Longrightarrow> success (f x) h \<Longrightarrow> success (let x = t in f x) h"
haftmann@37758
   114
  by (simp add: Let_def)
haftmann@37758
   115
haftmann@37771
   116
lemma success_ifI:
haftmann@37771
   117
  "(c \<Longrightarrow> success t h) \<Longrightarrow> (\<not> c \<Longrightarrow> success e h) \<Longrightarrow>
haftmann@37771
   118
    success (if c then t else e) h"
haftmann@37771
   119
  by (simp add: success_def)
haftmann@37771
   120
haftmann@37771
   121
haftmann@37771
   122
subsubsection {* Predicate for a simple relational calculus *}
haftmann@37771
   123
haftmann@37771
   124
text {*
haftmann@40671
   125
  The @{text effect} predicate states that when a computation @{text c}
haftmann@37771
   126
  runs with the heap @{text h} will result in return value @{text r}
haftmann@37771
   127
  and a heap @{text "h'"}, i.e.~no exception occurs.
haftmann@37771
   128
*}  
haftmann@37771
   129
haftmann@40671
   130
definition effect :: "'a Heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> 'a \<Rightarrow> bool" where
haftmann@40671
   131
  effect_def: "effect c h h' r \<longleftrightarrow> execute c h = Some (r, h')"
haftmann@37771
   132
haftmann@40671
   133
lemma effectI:
haftmann@40671
   134
  "execute c h = Some (r, h') \<Longrightarrow> effect c h h' r"
haftmann@40671
   135
  by (simp add: effect_def)
haftmann@37771
   136
haftmann@40671
   137
lemma effectE:
haftmann@40671
   138
  assumes "effect c h h' r"
haftmann@37771
   139
  obtains "r = fst (the (execute c h))"
haftmann@37771
   140
    and "h' = snd (the (execute c h))"
haftmann@37771
   141
    and "success c h"
haftmann@37771
   142
proof (rule that)
haftmann@40671
   143
  from assms have *: "execute c h = Some (r, h')" by (simp add: effect_def)
haftmann@37771
   144
  then show "success c h" by (simp add: success_def)
haftmann@37771
   145
  from * have "fst (the (execute c h)) = r" and "snd (the (execute c h)) = h'"
haftmann@37771
   146
    by simp_all
haftmann@37771
   147
  then show "r = fst (the (execute c h))"
haftmann@37771
   148
    and "h' = snd (the (execute c h))" by simp_all
haftmann@37771
   149
qed
haftmann@37771
   150
haftmann@40671
   151
lemma effect_success:
haftmann@40671
   152
  "effect c h h' r \<Longrightarrow> success c h"
haftmann@40671
   153
  by (simp add: effect_def success_def)
haftmann@37771
   154
haftmann@40671
   155
lemma success_effectE:
haftmann@37771
   156
  assumes "success c h"
haftmann@40671
   157
  obtains r h' where "effect c h h' r"
haftmann@40671
   158
  using assms by (auto simp add: effect_def success_def)
haftmann@37771
   159
haftmann@40671
   160
lemma effect_deterministic:
haftmann@40671
   161
  assumes "effect f h h' a"
haftmann@40671
   162
    and "effect f h h'' b"
haftmann@37771
   163
  shows "a = b" and "h' = h''"
haftmann@40671
   164
  using assms unfolding effect_def by auto
haftmann@37771
   165
haftmann@37771
   166
ML {* structure Crel_Intros = Named_Thms(
haftmann@40671
   167
  val name = "effect_intros"
haftmann@40671
   168
  val description = "introduction rules for effect"
haftmann@37771
   169
) *}
haftmann@37771
   170
haftmann@37771
   171
ML {* structure Crel_Elims = Named_Thms(
haftmann@40671
   172
  val name = "effect_elims"
haftmann@40671
   173
  val description = "elimination rules for effect"
haftmann@37771
   174
) *}
haftmann@37771
   175
haftmann@37771
   176
setup "Crel_Intros.setup #> Crel_Elims.setup"
haftmann@37771
   177
haftmann@40671
   178
lemma effect_LetI [effect_intros]:
haftmann@40671
   179
  assumes "x = t" "effect (f x) h h' r"
haftmann@40671
   180
  shows "effect (let x = t in f x) h h' r"
haftmann@37771
   181
  using assms by simp
haftmann@37771
   182
haftmann@40671
   183
lemma effect_LetE [effect_elims]:
haftmann@40671
   184
  assumes "effect (let x = t in f x) h h' r"
haftmann@40671
   185
  obtains "effect (f t) h h' r"
haftmann@37771
   186
  using assms by simp
haftmann@37771
   187
haftmann@40671
   188
lemma effect_ifI:
haftmann@40671
   189
  assumes "c \<Longrightarrow> effect t h h' r"
haftmann@40671
   190
    and "\<not> c \<Longrightarrow> effect e h h' r"
haftmann@40671
   191
  shows "effect (if c then t else e) h h' r"
haftmann@37771
   192
  by (cases c) (simp_all add: assms)
haftmann@37771
   193
haftmann@40671
   194
lemma effect_ifE:
haftmann@40671
   195
  assumes "effect (if c then t else e) h h' r"
haftmann@40671
   196
  obtains "c" "effect t h h' r"
haftmann@40671
   197
    | "\<not> c" "effect e h h' r"
haftmann@37771
   198
  using assms by (cases c) simp_all
haftmann@37771
   199
haftmann@40671
   200
lemma effect_tapI [effect_intros]:
haftmann@37771
   201
  assumes "h' = h" "r = f h"
haftmann@40671
   202
  shows "effect (tap f) h h' r"
haftmann@40671
   203
  by (rule effectI) (simp add: assms execute_simps)
haftmann@37771
   204
haftmann@40671
   205
lemma effect_tapE [effect_elims]:
haftmann@40671
   206
  assumes "effect (tap f) h h' r"
haftmann@37771
   207
  obtains "h' = h" and "r = f h"
haftmann@40671
   208
  using assms by (rule effectE) (auto simp add: execute_simps)
haftmann@37771
   209
haftmann@40671
   210
lemma effect_heapI [effect_intros]:
haftmann@37771
   211
  assumes "h' = snd (f h)" "r = fst (f h)"
haftmann@40671
   212
  shows "effect (heap f) h h' r"
haftmann@40671
   213
  by (rule effectI) (simp add: assms execute_simps)
haftmann@37771
   214
haftmann@40671
   215
lemma effect_heapE [effect_elims]:
haftmann@40671
   216
  assumes "effect (heap f) h h' r"
haftmann@37771
   217
  obtains "h' = snd (f h)" and "r = fst (f h)"
haftmann@40671
   218
  using assms by (rule effectE) (simp add: execute_simps)
haftmann@37771
   219
haftmann@40671
   220
lemma effect_guardI [effect_intros]:
haftmann@37771
   221
  assumes "P h" "h' = snd (f h)" "r = fst (f h)"
haftmann@40671
   222
  shows "effect (guard P f) h h' r"
haftmann@40671
   223
  by (rule effectI) (simp add: assms execute_simps)
haftmann@37771
   224
haftmann@40671
   225
lemma effect_guardE [effect_elims]:
haftmann@40671
   226
  assumes "effect (guard P f) h h' r"
haftmann@37771
   227
  obtains "h' = snd (f h)" "r = fst (f h)" "P h"
haftmann@40671
   228
  using assms by (rule effectE)
haftmann@37771
   229
    (auto simp add: execute_simps elim!: successE, cases "P h", auto simp add: execute_simps)
haftmann@37771
   230
haftmann@37758
   231
haftmann@37758
   232
subsubsection {* Monad combinators *}
haftmann@26170
   233
haftmann@37709
   234
definition return :: "'a \<Rightarrow> 'a Heap" where
haftmann@26170
   235
  [code del]: "return x = heap (Pair x)"
haftmann@26170
   236
haftmann@37787
   237
lemma execute_return [execute_simps]:
haftmann@37709
   238
  "execute (return x) = Some \<circ> Pair x"
haftmann@37787
   239
  by (simp add: return_def execute_simps)
haftmann@26170
   240
haftmann@37787
   241
lemma success_returnI [success_intros]:
haftmann@37758
   242
  "success (return x) h"
haftmann@37787
   243
  by (rule successI) (simp add: execute_simps)
haftmann@37758
   244
haftmann@40671
   245
lemma effect_returnI [effect_intros]:
haftmann@40671
   246
  "h = h' \<Longrightarrow> effect (return x) h h' x"
haftmann@40671
   247
  by (rule effectI) (simp add: execute_simps)
haftmann@37771
   248
haftmann@40671
   249
lemma effect_returnE [effect_elims]:
haftmann@40671
   250
  assumes "effect (return x) h h' r"
haftmann@37771
   251
  obtains "r = x" "h' = h"
haftmann@40671
   252
  using assms by (rule effectE) (simp add: execute_simps)
haftmann@37771
   253
haftmann@37709
   254
definition raise :: "string \<Rightarrow> 'a Heap" where -- {* the string is just decoration *}
haftmann@37709
   255
  [code del]: "raise s = Heap (\<lambda>_. None)"
haftmann@26170
   256
haftmann@37787
   257
lemma execute_raise [execute_simps]:
haftmann@37709
   258
  "execute (raise s) = (\<lambda>_. None)"
haftmann@26170
   259
  by (simp add: raise_def)
haftmann@26170
   260
haftmann@40671
   261
lemma effect_raiseE [effect_elims]:
haftmann@40671
   262
  assumes "effect (raise x) h h' r"
haftmann@37771
   263
  obtains "False"
haftmann@40671
   264
  using assms by (rule effectE) (simp add: success_def execute_simps)
haftmann@37771
   265
krauss@37792
   266
definition bind :: "'a Heap \<Rightarrow> ('a \<Rightarrow> 'b Heap) \<Rightarrow> 'b Heap" where
krauss@37792
   267
  [code del]: "bind f g = Heap (\<lambda>h. case execute f h of
haftmann@37709
   268
                  Some (x, h') \<Rightarrow> execute (g x) h'
haftmann@37709
   269
                | None \<Rightarrow> None)"
haftmann@37709
   270
krauss@37792
   271
setup {*
krauss@37792
   272
  Adhoc_Overloading.add_variant 
haftmann@37816
   273
    @{const_name Monad_Syntax.bind} @{const_name Heap_Monad.bind}
krauss@37792
   274
*}
krauss@37792
   275
haftmann@37758
   276
lemma execute_bind [execute_simps]:
haftmann@37709
   277
  "execute f h = Some (x, h') \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g x) h'"
haftmann@37709
   278
  "execute f h = None \<Longrightarrow> execute (f \<guillemotright>= g) h = None"
haftmann@37756
   279
  by (simp_all add: bind_def)
haftmann@37709
   280
haftmann@38409
   281
lemma execute_bind_case:
haftmann@38409
   282
  "execute (f \<guillemotright>= g) h = (case (execute f h) of
haftmann@38409
   283
    Some (x, h') \<Rightarrow> execute (g x) h' | None \<Rightarrow> None)"
haftmann@38409
   284
  by (simp add: bind_def)
haftmann@38409
   285
haftmann@37771
   286
lemma execute_bind_success:
haftmann@37771
   287
  "success f h \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g (fst (the (execute f h)))) (snd (the (execute f h)))"
haftmann@37771
   288
  by (cases f h rule: Heap_cases) (auto elim!: successE simp add: bind_def)
haftmann@37771
   289
haftmann@37771
   290
lemma success_bind_executeI:
haftmann@37771
   291
  "execute f h = Some (x, h') \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
haftmann@37758
   292
  by (auto intro!: successI elim!: successE simp add: bind_def)
haftmann@37758
   293
haftmann@40671
   294
lemma success_bind_effectI [success_intros]:
haftmann@40671
   295
  "effect f h h' x \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
haftmann@40671
   296
  by (auto simp add: effect_def success_def bind_def)
haftmann@37771
   297
haftmann@40671
   298
lemma effect_bindI [effect_intros]:
haftmann@40671
   299
  assumes "effect f h h' r" "effect (g r) h' h'' r'"
haftmann@40671
   300
  shows "effect (f \<guillemotright>= g) h h'' r'"
haftmann@37771
   301
  using assms
haftmann@40671
   302
  apply (auto intro!: effectI elim!: effectE successE)
haftmann@37771
   303
  apply (subst execute_bind, simp_all)
haftmann@37771
   304
  done
haftmann@37771
   305
haftmann@40671
   306
lemma effect_bindE [effect_elims]:
haftmann@40671
   307
  assumes "effect (f \<guillemotright>= g) h h'' r'"
haftmann@40671
   308
  obtains h' r where "effect f h h' r" "effect (g r) h' h'' r'"
haftmann@40671
   309
  using assms by (auto simp add: effect_def bind_def split: option.split_asm)
haftmann@37771
   310
haftmann@37771
   311
lemma execute_bind_eq_SomeI:
haftmann@37878
   312
  assumes "execute f h = Some (x, h')"
haftmann@37878
   313
    and "execute (g x) h' = Some (y, h'')"
haftmann@37878
   314
  shows "execute (f \<guillemotright>= g) h = Some (y, h'')"
haftmann@37756
   315
  using assms by (simp add: bind_def)
haftmann@37754
   316
haftmann@37709
   317
lemma return_bind [simp]: "return x \<guillemotright>= f = f x"
haftmann@37787
   318
  by (rule Heap_eqI) (simp add: execute_bind execute_simps)
haftmann@37709
   319
haftmann@37709
   320
lemma bind_return [simp]: "f \<guillemotright>= return = f"
haftmann@37787
   321
  by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits)
haftmann@37709
   322
haftmann@37828
   323
lemma bind_bind [simp]: "(f \<guillemotright>= g) \<guillemotright>= k = (f :: 'a Heap) \<guillemotright>= (\<lambda>x. g x \<guillemotright>= k)"
haftmann@37787
   324
  by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits)
haftmann@37709
   325
haftmann@37709
   326
lemma raise_bind [simp]: "raise e \<guillemotright>= f = raise e"
haftmann@37787
   327
  by (rule Heap_eqI) (simp add: execute_simps)
haftmann@37709
   328
haftmann@26170
   329
haftmann@37758
   330
subsection {* Generic combinators *}
haftmann@26170
   331
haftmann@37758
   332
subsubsection {* Assertions *}
haftmann@26170
   333
haftmann@37709
   334
definition assert :: "('a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a Heap" where
haftmann@37709
   335
  "assert P x = (if P x then return x else raise ''assert'')"
haftmann@28742
   336
haftmann@37758
   337
lemma execute_assert [execute_simps]:
haftmann@37754
   338
  "P x \<Longrightarrow> execute (assert P x) h = Some (x, h)"
haftmann@37754
   339
  "\<not> P x \<Longrightarrow> execute (assert P x) h = None"
haftmann@37787
   340
  by (simp_all add: assert_def execute_simps)
haftmann@37754
   341
haftmann@37758
   342
lemma success_assertI [success_intros]:
haftmann@37758
   343
  "P x \<Longrightarrow> success (assert P x) h"
haftmann@37758
   344
  by (rule successI) (simp add: execute_assert)
haftmann@37758
   345
haftmann@40671
   346
lemma effect_assertI [effect_intros]:
haftmann@40671
   347
  "P x \<Longrightarrow> h' = h \<Longrightarrow> r = x \<Longrightarrow> effect (assert P x) h h' r"
haftmann@40671
   348
  by (rule effectI) (simp add: execute_assert)
haftmann@37771
   349
 
haftmann@40671
   350
lemma effect_assertE [effect_elims]:
haftmann@40671
   351
  assumes "effect (assert P x) h h' r"
haftmann@37771
   352
  obtains "P x" "r = x" "h' = h"
haftmann@40671
   353
  using assms by (rule effectE) (cases "P x", simp_all add: execute_assert success_def)
haftmann@37771
   354
haftmann@28742
   355
lemma assert_cong [fundef_cong]:
haftmann@28742
   356
  assumes "P = P'"
haftmann@28742
   357
  assumes "\<And>x. P' x \<Longrightarrow> f x = f' x"
haftmann@28742
   358
  shows "(assert P x >>= f) = (assert P' x >>= f')"
haftmann@37754
   359
  by (rule Heap_eqI) (insert assms, simp add: assert_def)
haftmann@28742
   360
haftmann@37758
   361
haftmann@37758
   362
subsubsection {* Plain lifting *}
haftmann@37758
   363
haftmann@37754
   364
definition lift :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b Heap" where
haftmann@37754
   365
  "lift f = return o f"
haftmann@37709
   366
haftmann@37754
   367
lemma lift_collapse [simp]:
haftmann@37754
   368
  "lift f x = return (f x)"
haftmann@37754
   369
  by (simp add: lift_def)
haftmann@37709
   370
haftmann@37754
   371
lemma bind_lift:
haftmann@37754
   372
  "(f \<guillemotright>= lift g) = (f \<guillemotright>= (\<lambda>x. return (g x)))"
haftmann@37754
   373
  by (simp add: lift_def comp_def)
haftmann@37709
   374
haftmann@37758
   375
haftmann@37758
   376
subsubsection {* Iteration -- warning: this is rarely useful! *}
haftmann@37758
   377
haftmann@37756
   378
primrec fold_map :: "('a \<Rightarrow> 'b Heap) \<Rightarrow> 'a list \<Rightarrow> 'b list Heap" where
haftmann@37756
   379
  "fold_map f [] = return []"
krauss@37792
   380
| "fold_map f (x # xs) = do {
haftmann@37709
   381
     y \<leftarrow> f x;
haftmann@37756
   382
     ys \<leftarrow> fold_map f xs;
haftmann@37709
   383
     return (y # ys)
krauss@37792
   384
   }"
haftmann@37709
   385
haftmann@37756
   386
lemma fold_map_append:
haftmann@37756
   387
  "fold_map f (xs @ ys) = fold_map f xs \<guillemotright>= (\<lambda>xs. fold_map f ys \<guillemotright>= (\<lambda>ys. return (xs @ ys)))"
haftmann@37754
   388
  by (induct xs) simp_all
haftmann@37754
   389
haftmann@37758
   390
lemma execute_fold_map_unchanged_heap [execute_simps]:
haftmann@37754
   391
  assumes "\<And>x. x \<in> set xs \<Longrightarrow> \<exists>y. execute (f x) h = Some (y, h)"
haftmann@37756
   392
  shows "execute (fold_map f xs) h =
haftmann@37754
   393
    Some (List.map (\<lambda>x. fst (the (execute (f x) h))) xs, h)"
haftmann@37754
   394
using assms proof (induct xs)
haftmann@37787
   395
  case Nil show ?case by (simp add: execute_simps)
haftmann@37754
   396
next
haftmann@37754
   397
  case (Cons x xs)
haftmann@37754
   398
  from Cons.prems obtain y
haftmann@37754
   399
    where y: "execute (f x) h = Some (y, h)" by auto
haftmann@37756
   400
  moreover from Cons.prems Cons.hyps have "execute (fold_map f xs) h =
haftmann@37754
   401
    Some (map (\<lambda>x. fst (the (execute (f x) h))) xs, h)" by auto
haftmann@37787
   402
  ultimately show ?case by (simp, simp only: execute_bind(1), simp add: execute_simps)
haftmann@37754
   403
qed
haftmann@37754
   404
haftmann@40267
   405
haftmann@40267
   406
subsection {* Partial function definition setup *}
haftmann@40267
   407
haftmann@40267
   408
definition Heap_ord :: "'a Heap \<Rightarrow> 'a Heap \<Rightarrow> bool" where
haftmann@40267
   409
  "Heap_ord = img_ord execute (fun_ord option_ord)"
haftmann@40267
   410
haftmann@40267
   411
definition Heap_lub :: "('a Heap \<Rightarrow> bool) \<Rightarrow> 'a Heap" where
haftmann@40267
   412
  "Heap_lub = img_lub execute Heap (fun_lub (flat_lub None))"
haftmann@40267
   413
haftmann@40267
   414
interpretation heap!: partial_function_definitions Heap_ord Heap_lub
haftmann@40267
   415
proof -
haftmann@40267
   416
  have "partial_function_definitions (fun_ord option_ord) (fun_lub (flat_lub None))"
haftmann@40267
   417
    by (rule partial_function_lift) (rule flat_interpretation)
haftmann@40267
   418
  then have "partial_function_definitions (img_ord execute (fun_ord option_ord))
haftmann@40267
   419
      (img_lub execute Heap (fun_lub (flat_lub None)))"
haftmann@40267
   420
    by (rule partial_function_image) (auto intro: Heap_eqI)
haftmann@40267
   421
  then show "partial_function_definitions Heap_ord Heap_lub"
haftmann@40267
   422
    by (simp only: Heap_ord_def Heap_lub_def)
haftmann@40267
   423
qed
haftmann@40267
   424
haftmann@40267
   425
abbreviation "mono_Heap \<equiv> monotone (fun_ord Heap_ord) Heap_ord"
haftmann@40267
   426
haftmann@40267
   427
lemma Heap_ordI:
haftmann@40267
   428
  assumes "\<And>h. execute x h = None \<or> execute x h = execute y h"
haftmann@40267
   429
  shows "Heap_ord x y"
haftmann@40267
   430
  using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
haftmann@40267
   431
  by blast
haftmann@40267
   432
haftmann@40267
   433
lemma Heap_ordE:
haftmann@40267
   434
  assumes "Heap_ord x y"
haftmann@40267
   435
  obtains "execute x h = None" | "execute x h = execute y h"
haftmann@40267
   436
  using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
haftmann@40267
   437
  by atomize_elim blast
haftmann@40267
   438
haftmann@40267
   439
lemma bind_mono[partial_function_mono]:
haftmann@40267
   440
  assumes mf: "mono_Heap B" and mg: "\<And>y. mono_Heap (\<lambda>f. C y f)"
haftmann@40267
   441
  shows "mono_Heap (\<lambda>f. B f \<guillemotright>= (\<lambda>y. C y f))"
haftmann@40267
   442
proof (rule monotoneI)
haftmann@40267
   443
  fix f g :: "'a \<Rightarrow> 'b Heap" assume fg: "fun_ord Heap_ord f g"
haftmann@40267
   444
  from mf
haftmann@40267
   445
  have 1: "Heap_ord (B f) (B g)" by (rule monotoneD) (rule fg)
haftmann@40267
   446
  from mg
haftmann@40267
   447
  have 2: "\<And>y'. Heap_ord (C y' f) (C y' g)" by (rule monotoneD) (rule fg)
haftmann@40267
   448
haftmann@40267
   449
  have "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y. C y f))"
haftmann@40267
   450
    (is "Heap_ord ?L ?R")
haftmann@40267
   451
  proof (rule Heap_ordI)
haftmann@40267
   452
    fix h
haftmann@40267
   453
    from 1 show "execute ?L h = None \<or> execute ?L h = execute ?R h"
haftmann@40267
   454
      by (rule Heap_ordE[where h = h]) (auto simp: execute_bind_case)
haftmann@40267
   455
  qed
haftmann@40267
   456
  also
haftmann@40267
   457
  have "Heap_ord (B g \<guillemotright>= (\<lambda>y'. C y' f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))"
haftmann@40267
   458
    (is "Heap_ord ?L ?R")
haftmann@40267
   459
  proof (rule Heap_ordI)
haftmann@40267
   460
    fix h
haftmann@40267
   461
    show "execute ?L h = None \<or> execute ?L h = execute ?R h"
haftmann@40267
   462
    proof (cases "execute (B g) h")
haftmann@40267
   463
      case None
haftmann@40267
   464
      then have "execute ?L h = None" by (auto simp: execute_bind_case)
haftmann@40267
   465
      thus ?thesis ..
haftmann@40267
   466
    next
haftmann@40267
   467
      case Some
haftmann@40267
   468
      then obtain r h' where "execute (B g) h = Some (r, h')"
haftmann@40267
   469
        by (metis surjective_pairing)
haftmann@40267
   470
      then have "execute ?L h = execute (C r f) h'"
haftmann@40267
   471
        "execute ?R h = execute (C r g) h'"
haftmann@40267
   472
        by (auto simp: execute_bind_case)
haftmann@40267
   473
      with 2[of r] show ?thesis by (auto elim: Heap_ordE)
haftmann@40267
   474
    qed
haftmann@40267
   475
  qed
haftmann@40267
   476
  finally (heap.leq_trans)
haftmann@40267
   477
  show "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))" .
haftmann@40267
   478
qed
haftmann@40267
   479
haftmann@40267
   480
haftmann@26182
   481
subsection {* Code generator setup *}
haftmann@26182
   482
haftmann@26182
   483
subsubsection {* Logical intermediate layer *}
haftmann@26182
   484
bulwahn@39250
   485
definition raise' :: "String.literal \<Rightarrow> 'a Heap" where
bulwahn@39250
   486
  [code del]: "raise' s = raise (explode s)"
bulwahn@39250
   487
bulwahn@39250
   488
lemma [code_post]: "raise' (STR s) = raise s"
bulwahn@39250
   489
unfolding raise'_def by (simp add: STR_inverse)
haftmann@26182
   490
haftmann@37709
   491
lemma raise_raise' [code_inline]:
haftmann@37709
   492
  "raise s = raise' (STR s)"
bulwahn@39250
   493
  unfolding raise'_def by (simp add: STR_inverse)
haftmann@26182
   494
haftmann@37709
   495
code_datatype raise' -- {* avoid @{const "Heap"} formally *}
haftmann@26182
   496
haftmann@26182
   497
haftmann@27707
   498
subsubsection {* SML and OCaml *}
haftmann@26182
   499
haftmann@26752
   500
code_type Heap (SML "unit/ ->/ _")
haftmann@37828
   501
code_const bind (SML "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())")
haftmann@27707
   502
code_const return (SML "!(fn/ ()/ =>/ _)")
haftmann@37709
   503
code_const Heap_Monad.raise' (SML "!(raise/ Fail/ _)")
haftmann@26182
   504
haftmann@37754
   505
code_type Heap (OCaml "unit/ ->/ _")
haftmann@37828
   506
code_const bind (OCaml "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())")
haftmann@27707
   507
code_const return (OCaml "!(fun/ ()/ ->/ _)")
haftmann@37828
   508
code_const Heap_Monad.raise' (OCaml "failwith")
haftmann@27707
   509
haftmann@37838
   510
haftmann@37838
   511
subsubsection {* Haskell *}
haftmann@37838
   512
haftmann@37838
   513
text {* Adaption layer *}
haftmann@37838
   514
haftmann@37838
   515
code_include Haskell "Heap"
haftmann@37838
   516
{*import qualified Control.Monad;
haftmann@37838
   517
import qualified Control.Monad.ST;
haftmann@37838
   518
import qualified Data.STRef;
haftmann@37838
   519
import qualified Data.Array.ST;
haftmann@37838
   520
haftmann@37964
   521
import Natural;
haftmann@37964
   522
haftmann@37838
   523
type RealWorld = Control.Monad.ST.RealWorld;
haftmann@37838
   524
type ST s a = Control.Monad.ST.ST s a;
haftmann@37838
   525
type STRef s a = Data.STRef.STRef s a;
haftmann@37964
   526
type STArray s a = Data.Array.ST.STArray s Natural a;
haftmann@37838
   527
haftmann@37838
   528
newSTRef = Data.STRef.newSTRef;
haftmann@37838
   529
readSTRef = Data.STRef.readSTRef;
haftmann@37838
   530
writeSTRef = Data.STRef.writeSTRef;
haftmann@37838
   531
haftmann@37964
   532
newArray :: Natural -> a -> ST s (STArray s a);
haftmann@37838
   533
newArray k = Data.Array.ST.newArray (0, k);
haftmann@37838
   534
haftmann@37838
   535
newListArray :: [a] -> ST s (STArray s a);
haftmann@37964
   536
newListArray xs = Data.Array.ST.newListArray (0, (fromInteger . toInteger . length) xs) xs;
haftmann@37838
   537
haftmann@37964
   538
newFunArray :: Natural -> (Natural -> a) -> ST s (STArray s a);
haftmann@37838
   539
newFunArray k f = Data.Array.ST.newListArray (0, k) (map f [0..k-1]);
haftmann@37838
   540
haftmann@37964
   541
lengthArray :: STArray s a -> ST s Natural;
haftmann@37838
   542
lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a);
haftmann@37838
   543
haftmann@37964
   544
readArray :: STArray s a -> Natural -> ST s a;
haftmann@37838
   545
readArray = Data.Array.ST.readArray;
haftmann@37838
   546
haftmann@37964
   547
writeArray :: STArray s a -> Natural -> a -> ST s ();
haftmann@37838
   548
writeArray = Data.Array.ST.writeArray;*}
haftmann@37838
   549
haftmann@37838
   550
code_reserved Haskell Heap
haftmann@37838
   551
haftmann@37838
   552
text {* Monad *}
haftmann@37838
   553
haftmann@37838
   554
code_type Heap (Haskell "Heap.ST/ Heap.RealWorld/ _")
haftmann@37838
   555
code_monad bind Haskell
haftmann@37838
   556
code_const return (Haskell "return")
haftmann@37838
   557
code_const Heap_Monad.raise' (Haskell "error")
haftmann@37838
   558
haftmann@37838
   559
haftmann@37838
   560
subsubsection {* Scala *}
haftmann@37838
   561
haftmann@37842
   562
code_include Scala "Heap"
haftmann@38968
   563
{*object Heap {
haftmann@38968
   564
  def bind[A, B](f: Unit => A, g: A => Unit => B): Unit => B = (_: Unit) => g (f ()) ()
haftmann@38968
   565
}
haftmann@37842
   566
haftmann@37842
   567
class Ref[A](x: A) {
haftmann@37842
   568
  var value = x
haftmann@37842
   569
}
haftmann@37842
   570
haftmann@37842
   571
object Ref {
haftmann@38771
   572
  def apply[A](x: A): Ref[A] =
haftmann@38771
   573
    new Ref[A](x)
haftmann@38771
   574
  def lookup[A](r: Ref[A]): A =
haftmann@38771
   575
    r.value
haftmann@38771
   576
  def update[A](r: Ref[A], x: A): Unit =
haftmann@38771
   577
    { r.value = x }
haftmann@37842
   578
}
haftmann@37842
   579
haftmann@37964
   580
object Array {
haftmann@38968
   581
  import collection.mutable.ArraySeq
haftmann@38968
   582
  def alloc[A](n: Natural)(x: A): ArraySeq[A] =
haftmann@38771
   583
    ArraySeq.fill(n.as_Int)(x)
haftmann@38968
   584
  def make[A](n: Natural)(f: Natural => A): ArraySeq[A] =
haftmann@38968
   585
    ArraySeq.tabulate(n.as_Int)((k: Int) => f(Natural(k)))
haftmann@38968
   586
  def len[A](a: ArraySeq[A]): Natural =
haftmann@38968
   587
    Natural(a.length)
haftmann@38968
   588
  def nth[A](a: ArraySeq[A], n: Natural): A =
haftmann@38771
   589
    a(n.as_Int)
haftmann@38968
   590
  def upd[A](a: ArraySeq[A], n: Natural, x: A): Unit =
haftmann@38771
   591
    a.update(n.as_Int, x)
haftmann@38771
   592
  def freeze[A](a: ArraySeq[A]): List[A] =
haftmann@38771
   593
    a.toList
haftmann@38968
   594
}
haftmann@38968
   595
*}
haftmann@37842
   596
haftmann@38968
   597
code_reserved Scala Heap Ref Array
haftmann@37838
   598
haftmann@37838
   599
code_type Heap (Scala "Unit/ =>/ _")
haftmann@38771
   600
code_const bind (Scala "Heap.bind")
haftmann@37842
   601
code_const return (Scala "('_: Unit)/ =>/ _")
haftmann@37845
   602
code_const Heap_Monad.raise' (Scala "!error((_))")
haftmann@37838
   603
haftmann@37838
   604
haftmann@37838
   605
subsubsection {* Target variants with less units *}
haftmann@37838
   606
haftmann@31871
   607
setup {*
haftmann@31871
   608
haftmann@31871
   609
let
haftmann@27707
   610
haftmann@31871
   611
open Code_Thingol;
haftmann@31871
   612
haftmann@31871
   613
fun imp_program naming =
haftmann@27707
   614
haftmann@31871
   615
  let
haftmann@31871
   616
    fun is_const c = case lookup_const naming c
haftmann@31871
   617
     of SOME c' => (fn c'' => c' = c'')
haftmann@31871
   618
      | NONE => K false;
haftmann@37756
   619
    val is_bind = is_const @{const_name bind};
haftmann@31871
   620
    val is_return = is_const @{const_name return};
haftmann@31893
   621
    val dummy_name = "";
haftmann@31893
   622
    val dummy_case_term = IVar NONE;
haftmann@31871
   623
    (*assumption: dummy values are not relevant for serialization*)
haftmann@38057
   624
    val (unitt, unitT) = case lookup_const naming @{const_name Unity}
haftmann@38057
   625
     of SOME unit' => (IConst (unit', (([], []), [])), the (lookup_tyco naming @{type_name unit}) `%% [])
haftmann@31871
   626
      | NONE => error ("Must include " ^ @{const_name Unity} ^ " in generated constants.");
haftmann@31871
   627
    fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t)
haftmann@31871
   628
      | dest_abs (t, ty) =
haftmann@31871
   629
          let
haftmann@31871
   630
            val vs = fold_varnames cons t [];
haftmann@31871
   631
            val v = Name.variant vs "x";
haftmann@31871
   632
            val ty' = (hd o fst o unfold_fun) ty;
haftmann@31893
   633
          in ((SOME v, ty'), t `$ IVar (SOME v)) end;
haftmann@31871
   634
    fun force (t as IConst (c, _) `$ t') = if is_return c
haftmann@31871
   635
          then t' else t `$ unitt
haftmann@31871
   636
      | force t = t `$ unitt;
haftmann@38385
   637
    fun tr_bind'' [(t1, _), (t2, ty2)] =
haftmann@31871
   638
      let
haftmann@31871
   639
        val ((v, ty), t) = dest_abs (t2, ty2);
haftmann@38385
   640
      in ICase (((force t1, ty), [(IVar v, tr_bind' t)]), dummy_case_term) end
haftmann@38385
   641
    and tr_bind' t = case unfold_app t
haftmann@38386
   642
     of (IConst (c, (_, ty1 :: ty2 :: _)), [x1, x2]) => if is_bind c
haftmann@38386
   643
          then tr_bind'' [(x1, ty1), (x2, ty2)]
haftmann@38386
   644
          else force t
haftmann@38386
   645
      | _ => force t;
haftmann@38057
   646
    fun imp_monad_bind'' ts = (SOME dummy_name, unitT) `|=> ICase (((IVar (SOME dummy_name), unitT),
haftmann@38385
   647
      [(unitt, tr_bind'' ts)]), dummy_case_term)
haftmann@38385
   648
    fun imp_monad_bind' (const as (c, (_, tys))) ts = if is_bind c then case (ts, tys)
haftmann@31871
   649
       of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)]
haftmann@31871
   650
        | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3
haftmann@31871
   651
        | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts))
haftmann@31871
   652
      else IConst const `$$ map imp_monad_bind ts
haftmann@31871
   653
    and imp_monad_bind (IConst const) = imp_monad_bind' const []
haftmann@31871
   654
      | imp_monad_bind (t as IVar _) = t
haftmann@31871
   655
      | imp_monad_bind (t as _ `$ _) = (case unfold_app t
haftmann@31871
   656
         of (IConst const, ts) => imp_monad_bind' const ts
haftmann@31871
   657
          | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts)
haftmann@31871
   658
      | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t
haftmann@31871
   659
      | imp_monad_bind (ICase (((t, ty), pats), t0)) = ICase
haftmann@31871
   660
          (((imp_monad_bind t, ty),
haftmann@31871
   661
            (map o pairself) imp_monad_bind pats),
haftmann@31871
   662
              imp_monad_bind t0);
haftmann@28663
   663
haftmann@39021
   664
  in (Graph.map o K o map_terms_stmt) imp_monad_bind end;
haftmann@27707
   665
haftmann@27707
   666
in
haftmann@27707
   667
haftmann@31871
   668
Code_Target.extend_target ("SML_imp", ("SML", imp_program))
haftmann@31871
   669
#> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program))
haftmann@37838
   670
#> Code_Target.extend_target ("Scala_imp", ("Scala", imp_program))
haftmann@27707
   671
haftmann@27707
   672
end
haftmann@31871
   673
haftmann@27707
   674
*}
haftmann@27707
   675
haftmann@37758
   676
hide_const (open) Heap heap guard raise' fold_map
haftmann@37724
   677
haftmann@26170
   678
end