src/HOL/Imperative_HOL/Heap_Monad.thy
author haftmann
Fri Oct 29 13:49:49 2010 +0200 (2010-10-29)
changeset 40266 d72f1f734e5a
parent 40173 0ffdd6baec03
child 40267 a03e288d7902
permissions -rw-r--r--
remove term_of equations for Heap type explicitly
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@37771
   125
  The @{text crel} 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@37771
   130
definition crel :: "'a Heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> 'a \<Rightarrow> bool" where
haftmann@37878
   131
  crel_def: "crel c h h' r \<longleftrightarrow> execute c h = Some (r, h')"
haftmann@37771
   132
haftmann@37771
   133
lemma crelI:
haftmann@37878
   134
  "execute c h = Some (r, h') \<Longrightarrow> crel c h h' r"
haftmann@37771
   135
  by (simp add: crel_def)
haftmann@37771
   136
haftmann@37771
   137
lemma crelE:
haftmann@37771
   138
  assumes "crel 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@37771
   143
  from assms have *: "execute c h = Some (r, h')" by (simp add: crel_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@37771
   151
lemma crel_success:
haftmann@37771
   152
  "crel c h h' r \<Longrightarrow> success c h"
haftmann@37771
   153
  by (simp add: crel_def success_def)
haftmann@37771
   154
haftmann@37771
   155
lemma success_crelE:
haftmann@37771
   156
  assumes "success c h"
haftmann@37771
   157
  obtains r h' where "crel c h h' r"
haftmann@37771
   158
  using assms by (auto simp add: crel_def success_def)
haftmann@37771
   159
haftmann@37771
   160
lemma crel_deterministic:
haftmann@37771
   161
  assumes "crel f h h' a"
haftmann@37771
   162
    and "crel f h h'' b"
haftmann@37771
   163
  shows "a = b" and "h' = h''"
haftmann@37771
   164
  using assms unfolding crel_def by auto
haftmann@37771
   165
haftmann@37771
   166
ML {* structure Crel_Intros = Named_Thms(
haftmann@37771
   167
  val name = "crel_intros"
haftmann@37771
   168
  val description = "introduction rules for crel"
haftmann@37771
   169
) *}
haftmann@37771
   170
haftmann@37771
   171
ML {* structure Crel_Elims = Named_Thms(
haftmann@37771
   172
  val name = "crel_elims"
haftmann@37771
   173
  val description = "elimination rules for crel"
haftmann@37771
   174
) *}
haftmann@37771
   175
haftmann@37771
   176
setup "Crel_Intros.setup #> Crel_Elims.setup"
haftmann@37771
   177
haftmann@37771
   178
lemma crel_LetI [crel_intros]:
haftmann@37771
   179
  assumes "x = t" "crel (f x) h h' r"
haftmann@37771
   180
  shows "crel (let x = t in f x) h h' r"
haftmann@37771
   181
  using assms by simp
haftmann@37771
   182
haftmann@37771
   183
lemma crel_LetE [crel_elims]:
haftmann@37771
   184
  assumes "crel (let x = t in f x) h h' r"
haftmann@37771
   185
  obtains "crel (f t) h h' r"
haftmann@37771
   186
  using assms by simp
haftmann@37771
   187
haftmann@37771
   188
lemma crel_ifI:
haftmann@37771
   189
  assumes "c \<Longrightarrow> crel t h h' r"
haftmann@37771
   190
    and "\<not> c \<Longrightarrow> crel e h h' r"
haftmann@37771
   191
  shows "crel (if c then t else e) h h' r"
haftmann@37771
   192
  by (cases c) (simp_all add: assms)
haftmann@37771
   193
haftmann@37771
   194
lemma crel_ifE:
haftmann@37771
   195
  assumes "crel (if c then t else e) h h' r"
haftmann@37771
   196
  obtains "c" "crel t h h' r"
haftmann@37771
   197
    | "\<not> c" "crel e h h' r"
haftmann@37771
   198
  using assms by (cases c) simp_all
haftmann@37771
   199
haftmann@37771
   200
lemma crel_tapI [crel_intros]:
haftmann@37771
   201
  assumes "h' = h" "r = f h"
haftmann@37771
   202
  shows "crel (tap f) h h' r"
haftmann@37787
   203
  by (rule crelI) (simp add: assms execute_simps)
haftmann@37771
   204
haftmann@37771
   205
lemma crel_tapE [crel_elims]:
haftmann@37771
   206
  assumes "crel (tap f) h h' r"
haftmann@37771
   207
  obtains "h' = h" and "r = f h"
haftmann@37787
   208
  using assms by (rule crelE) (auto simp add: execute_simps)
haftmann@37771
   209
haftmann@37771
   210
lemma crel_heapI [crel_intros]:
haftmann@37771
   211
  assumes "h' = snd (f h)" "r = fst (f h)"
haftmann@37771
   212
  shows "crel (heap f) h h' r"
haftmann@37787
   213
  by (rule crelI) (simp add: assms execute_simps)
haftmann@37771
   214
haftmann@37771
   215
lemma crel_heapE [crel_elims]:
haftmann@37771
   216
  assumes "crel (heap f) h h' r"
haftmann@37771
   217
  obtains "h' = snd (f h)" and "r = fst (f h)"
haftmann@37787
   218
  using assms by (rule crelE) (simp add: execute_simps)
haftmann@37771
   219
haftmann@37771
   220
lemma crel_guardI [crel_intros]:
haftmann@37771
   221
  assumes "P h" "h' = snd (f h)" "r = fst (f h)"
haftmann@37771
   222
  shows "crel (guard P f) h h' r"
haftmann@37771
   223
  by (rule crelI) (simp add: assms execute_simps)
haftmann@37771
   224
haftmann@37771
   225
lemma crel_guardE [crel_elims]:
haftmann@37771
   226
  assumes "crel (guard P f) h h' r"
haftmann@37771
   227
  obtains "h' = snd (f h)" "r = fst (f h)" "P h"
haftmann@37771
   228
  using assms by (rule crelE)
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@37771
   245
lemma crel_returnI [crel_intros]:
haftmann@37771
   246
  "h = h' \<Longrightarrow> crel (return x) h h' x"
haftmann@37787
   247
  by (rule crelI) (simp add: execute_simps)
haftmann@37771
   248
haftmann@37771
   249
lemma crel_returnE [crel_elims]:
haftmann@37771
   250
  assumes "crel (return x) h h' r"
haftmann@37771
   251
  obtains "r = x" "h' = h"
haftmann@37787
   252
  using assms by (rule crelE) (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@37771
   261
lemma crel_raiseE [crel_elims]:
haftmann@37771
   262
  assumes "crel (raise x) h h' r"
haftmann@37771
   263
  obtains "False"
haftmann@37787
   264
  using assms by (rule crelE) (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@37771
   294
lemma success_bind_crelI [success_intros]:
haftmann@37771
   295
  "crel f h h' x \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
haftmann@37771
   296
  by (auto simp add: crel_def success_def bind_def)
haftmann@37771
   297
haftmann@37771
   298
lemma crel_bindI [crel_intros]:
haftmann@37771
   299
  assumes "crel f h h' r" "crel (g r) h' h'' r'"
haftmann@37771
   300
  shows "crel (f \<guillemotright>= g) h h'' r'"
haftmann@37771
   301
  using assms
haftmann@37771
   302
  apply (auto intro!: crelI elim!: crelE successE)
haftmann@37771
   303
  apply (subst execute_bind, simp_all)
haftmann@37771
   304
  done
haftmann@37771
   305
haftmann@37771
   306
lemma crel_bindE [crel_elims]:
haftmann@37771
   307
  assumes "crel (f \<guillemotright>= g) h h'' r'"
haftmann@37771
   308
  obtains h' r where "crel f h h' r" "crel (g r) h' h'' r'"
haftmann@37771
   309
  using assms by (auto simp add: crel_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@37771
   346
lemma crel_assertI [crel_intros]:
haftmann@37771
   347
  "P x \<Longrightarrow> h' = h \<Longrightarrow> r = x \<Longrightarrow> crel (assert P x) h h' r"
haftmann@37771
   348
  by (rule crelI) (simp add: execute_assert)
haftmann@37771
   349
 
haftmann@37771
   350
lemma crel_assertE [crel_elims]:
haftmann@37771
   351
  assumes "crel (assert P x) h h' r"
haftmann@37771
   352
  obtains "P x" "r = x" "h' = h"
haftmann@37771
   353
  using assms by (rule crelE) (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@26182
   405
subsection {* Code generator setup *}
haftmann@26182
   406
haftmann@26182
   407
subsubsection {* Logical intermediate layer *}
haftmann@26182
   408
bulwahn@39250
   409
definition raise' :: "String.literal \<Rightarrow> 'a Heap" where
bulwahn@39250
   410
  [code del]: "raise' s = raise (explode s)"
bulwahn@39250
   411
bulwahn@39250
   412
lemma [code_post]: "raise' (STR s) = raise s"
bulwahn@39250
   413
unfolding raise'_def by (simp add: STR_inverse)
haftmann@26182
   414
haftmann@37709
   415
lemma raise_raise' [code_inline]:
haftmann@37709
   416
  "raise s = raise' (STR s)"
bulwahn@39250
   417
  unfolding raise'_def by (simp add: STR_inverse)
haftmann@26182
   418
haftmann@37709
   419
code_datatype raise' -- {* avoid @{const "Heap"} formally *}
haftmann@26182
   420
haftmann@26182
   421
haftmann@27707
   422
subsubsection {* SML and OCaml *}
haftmann@26182
   423
haftmann@26752
   424
code_type Heap (SML "unit/ ->/ _")
haftmann@37828
   425
code_const bind (SML "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())")
haftmann@27707
   426
code_const return (SML "!(fn/ ()/ =>/ _)")
haftmann@37709
   427
code_const Heap_Monad.raise' (SML "!(raise/ Fail/ _)")
haftmann@26182
   428
haftmann@37754
   429
code_type Heap (OCaml "unit/ ->/ _")
haftmann@37828
   430
code_const bind (OCaml "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())")
haftmann@27707
   431
code_const return (OCaml "!(fun/ ()/ ->/ _)")
haftmann@37828
   432
code_const Heap_Monad.raise' (OCaml "failwith")
haftmann@27707
   433
haftmann@37838
   434
haftmann@37838
   435
subsubsection {* Haskell *}
haftmann@37838
   436
haftmann@37838
   437
text {* Adaption layer *}
haftmann@37838
   438
haftmann@37838
   439
code_include Haskell "Heap"
haftmann@37838
   440
{*import qualified Control.Monad;
haftmann@37838
   441
import qualified Control.Monad.ST;
haftmann@37838
   442
import qualified Data.STRef;
haftmann@37838
   443
import qualified Data.Array.ST;
haftmann@37838
   444
haftmann@37964
   445
import Natural;
haftmann@37964
   446
haftmann@37838
   447
type RealWorld = Control.Monad.ST.RealWorld;
haftmann@37838
   448
type ST s a = Control.Monad.ST.ST s a;
haftmann@37838
   449
type STRef s a = Data.STRef.STRef s a;
haftmann@37964
   450
type STArray s a = Data.Array.ST.STArray s Natural a;
haftmann@37838
   451
haftmann@37838
   452
newSTRef = Data.STRef.newSTRef;
haftmann@37838
   453
readSTRef = Data.STRef.readSTRef;
haftmann@37838
   454
writeSTRef = Data.STRef.writeSTRef;
haftmann@37838
   455
haftmann@37964
   456
newArray :: Natural -> a -> ST s (STArray s a);
haftmann@37838
   457
newArray k = Data.Array.ST.newArray (0, k);
haftmann@37838
   458
haftmann@37838
   459
newListArray :: [a] -> ST s (STArray s a);
haftmann@37964
   460
newListArray xs = Data.Array.ST.newListArray (0, (fromInteger . toInteger . length) xs) xs;
haftmann@37838
   461
haftmann@37964
   462
newFunArray :: Natural -> (Natural -> a) -> ST s (STArray s a);
haftmann@37838
   463
newFunArray k f = Data.Array.ST.newListArray (0, k) (map f [0..k-1]);
haftmann@37838
   464
haftmann@37964
   465
lengthArray :: STArray s a -> ST s Natural;
haftmann@37838
   466
lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a);
haftmann@37838
   467
haftmann@37964
   468
readArray :: STArray s a -> Natural -> ST s a;
haftmann@37838
   469
readArray = Data.Array.ST.readArray;
haftmann@37838
   470
haftmann@37964
   471
writeArray :: STArray s a -> Natural -> a -> ST s ();
haftmann@37838
   472
writeArray = Data.Array.ST.writeArray;*}
haftmann@37838
   473
haftmann@37838
   474
code_reserved Haskell Heap
haftmann@37838
   475
haftmann@37838
   476
text {* Monad *}
haftmann@37838
   477
haftmann@37838
   478
code_type Heap (Haskell "Heap.ST/ Heap.RealWorld/ _")
haftmann@37838
   479
code_monad bind Haskell
haftmann@37838
   480
code_const return (Haskell "return")
haftmann@37838
   481
code_const Heap_Monad.raise' (Haskell "error")
haftmann@37838
   482
haftmann@37838
   483
haftmann@37838
   484
subsubsection {* Scala *}
haftmann@37838
   485
haftmann@37842
   486
code_include Scala "Heap"
haftmann@38968
   487
{*object Heap {
haftmann@38968
   488
  def bind[A, B](f: Unit => A, g: A => Unit => B): Unit => B = (_: Unit) => g (f ()) ()
haftmann@38968
   489
}
haftmann@37842
   490
haftmann@37842
   491
class Ref[A](x: A) {
haftmann@37842
   492
  var value = x
haftmann@37842
   493
}
haftmann@37842
   494
haftmann@37842
   495
object Ref {
haftmann@38771
   496
  def apply[A](x: A): Ref[A] =
haftmann@38771
   497
    new Ref[A](x)
haftmann@38771
   498
  def lookup[A](r: Ref[A]): A =
haftmann@38771
   499
    r.value
haftmann@38771
   500
  def update[A](r: Ref[A], x: A): Unit =
haftmann@38771
   501
    { r.value = x }
haftmann@37842
   502
}
haftmann@37842
   503
haftmann@37964
   504
object Array {
haftmann@38968
   505
  import collection.mutable.ArraySeq
haftmann@38968
   506
  def alloc[A](n: Natural)(x: A): ArraySeq[A] =
haftmann@38771
   507
    ArraySeq.fill(n.as_Int)(x)
haftmann@38968
   508
  def make[A](n: Natural)(f: Natural => A): ArraySeq[A] =
haftmann@38968
   509
    ArraySeq.tabulate(n.as_Int)((k: Int) => f(Natural(k)))
haftmann@38968
   510
  def len[A](a: ArraySeq[A]): Natural =
haftmann@38968
   511
    Natural(a.length)
haftmann@38968
   512
  def nth[A](a: ArraySeq[A], n: Natural): A =
haftmann@38771
   513
    a(n.as_Int)
haftmann@38968
   514
  def upd[A](a: ArraySeq[A], n: Natural, x: A): Unit =
haftmann@38771
   515
    a.update(n.as_Int, x)
haftmann@38771
   516
  def freeze[A](a: ArraySeq[A]): List[A] =
haftmann@38771
   517
    a.toList
haftmann@38968
   518
}
haftmann@38968
   519
*}
haftmann@37842
   520
haftmann@38968
   521
code_reserved Scala Heap Ref Array
haftmann@37838
   522
haftmann@37838
   523
code_type Heap (Scala "Unit/ =>/ _")
haftmann@38771
   524
code_const bind (Scala "Heap.bind")
haftmann@37842
   525
code_const return (Scala "('_: Unit)/ =>/ _")
haftmann@37845
   526
code_const Heap_Monad.raise' (Scala "!error((_))")
haftmann@37838
   527
haftmann@37838
   528
haftmann@37838
   529
subsubsection {* Target variants with less units *}
haftmann@37838
   530
haftmann@31871
   531
setup {*
haftmann@31871
   532
haftmann@31871
   533
let
haftmann@27707
   534
haftmann@31871
   535
open Code_Thingol;
haftmann@31871
   536
haftmann@31871
   537
fun imp_program naming =
haftmann@27707
   538
haftmann@31871
   539
  let
haftmann@31871
   540
    fun is_const c = case lookup_const naming c
haftmann@31871
   541
     of SOME c' => (fn c'' => c' = c'')
haftmann@31871
   542
      | NONE => K false;
haftmann@37756
   543
    val is_bind = is_const @{const_name bind};
haftmann@31871
   544
    val is_return = is_const @{const_name return};
haftmann@31893
   545
    val dummy_name = "";
haftmann@31893
   546
    val dummy_case_term = IVar NONE;
haftmann@31871
   547
    (*assumption: dummy values are not relevant for serialization*)
haftmann@38057
   548
    val (unitt, unitT) = case lookup_const naming @{const_name Unity}
haftmann@38057
   549
     of SOME unit' => (IConst (unit', (([], []), [])), the (lookup_tyco naming @{type_name unit}) `%% [])
haftmann@31871
   550
      | NONE => error ("Must include " ^ @{const_name Unity} ^ " in generated constants.");
haftmann@31871
   551
    fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t)
haftmann@31871
   552
      | dest_abs (t, ty) =
haftmann@31871
   553
          let
haftmann@31871
   554
            val vs = fold_varnames cons t [];
haftmann@31871
   555
            val v = Name.variant vs "x";
haftmann@31871
   556
            val ty' = (hd o fst o unfold_fun) ty;
haftmann@31893
   557
          in ((SOME v, ty'), t `$ IVar (SOME v)) end;
haftmann@31871
   558
    fun force (t as IConst (c, _) `$ t') = if is_return c
haftmann@31871
   559
          then t' else t `$ unitt
haftmann@31871
   560
      | force t = t `$ unitt;
haftmann@38385
   561
    fun tr_bind'' [(t1, _), (t2, ty2)] =
haftmann@31871
   562
      let
haftmann@31871
   563
        val ((v, ty), t) = dest_abs (t2, ty2);
haftmann@38385
   564
      in ICase (((force t1, ty), [(IVar v, tr_bind' t)]), dummy_case_term) end
haftmann@38385
   565
    and tr_bind' t = case unfold_app t
haftmann@38386
   566
     of (IConst (c, (_, ty1 :: ty2 :: _)), [x1, x2]) => if is_bind c
haftmann@38386
   567
          then tr_bind'' [(x1, ty1), (x2, ty2)]
haftmann@38386
   568
          else force t
haftmann@38386
   569
      | _ => force t;
haftmann@38057
   570
    fun imp_monad_bind'' ts = (SOME dummy_name, unitT) `|=> ICase (((IVar (SOME dummy_name), unitT),
haftmann@38385
   571
      [(unitt, tr_bind'' ts)]), dummy_case_term)
haftmann@38385
   572
    fun imp_monad_bind' (const as (c, (_, tys))) ts = if is_bind c then case (ts, tys)
haftmann@31871
   573
       of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)]
haftmann@31871
   574
        | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3
haftmann@31871
   575
        | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts))
haftmann@31871
   576
      else IConst const `$$ map imp_monad_bind ts
haftmann@31871
   577
    and imp_monad_bind (IConst const) = imp_monad_bind' const []
haftmann@31871
   578
      | imp_monad_bind (t as IVar _) = t
haftmann@31871
   579
      | imp_monad_bind (t as _ `$ _) = (case unfold_app t
haftmann@31871
   580
         of (IConst const, ts) => imp_monad_bind' const ts
haftmann@31871
   581
          | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts)
haftmann@31871
   582
      | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t
haftmann@31871
   583
      | imp_monad_bind (ICase (((t, ty), pats), t0)) = ICase
haftmann@31871
   584
          (((imp_monad_bind t, ty),
haftmann@31871
   585
            (map o pairself) imp_monad_bind pats),
haftmann@31871
   586
              imp_monad_bind t0);
haftmann@28663
   587
haftmann@39021
   588
  in (Graph.map o K o map_terms_stmt) imp_monad_bind end;
haftmann@27707
   589
haftmann@27707
   590
in
haftmann@27707
   591
haftmann@31871
   592
Code_Target.extend_target ("SML_imp", ("SML", imp_program))
haftmann@31871
   593
#> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program))
haftmann@37838
   594
#> Code_Target.extend_target ("Scala_imp", ("Scala", imp_program))
haftmann@27707
   595
haftmann@27707
   596
end
haftmann@31871
   597
haftmann@27707
   598
*}
haftmann@27707
   599
haftmann@26182
   600
krauss@40173
   601
section {* Partial function definition setup *}
krauss@40173
   602
krauss@40173
   603
definition "Heap_ord = img_ord execute (fun_ord option_ord)"
krauss@40173
   604
definition "Heap_lub = img_lub execute Heap (fun_lub (flat_lub None))"
krauss@40173
   605
krauss@40173
   606
interpretation heap!:
krauss@40173
   607
  partial_function_definitions Heap_ord Heap_lub
krauss@40173
   608
unfolding Heap_ord_def Heap_lub_def
krauss@40173
   609
apply (rule partial_function_image)
krauss@40173
   610
apply (rule partial_function_lift)
krauss@40173
   611
apply (rule flat_interpretation)
krauss@40173
   612
by (auto intro: Heap_eqI)
krauss@40173
   613
krauss@40173
   614
abbreviation "mono_Heap \<equiv> monotone (fun_ord Heap_ord) Heap_ord"
krauss@40173
   615
krauss@40173
   616
lemma Heap_ordI:
krauss@40173
   617
  assumes "\<And>h. execute x h = None \<or> execute x h = execute y h"
krauss@40173
   618
  shows "Heap_ord x y"
krauss@40173
   619
using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
krauss@40173
   620
by blast
krauss@40173
   621
krauss@40173
   622
lemma Heap_ordE:
krauss@40173
   623
  assumes "Heap_ord x y"
krauss@40173
   624
  obtains "execute x h = None" | "execute x h = execute y h"
krauss@40173
   625
using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
krauss@40173
   626
by atomize_elim blast
krauss@40173
   627
krauss@40173
   628
krauss@40173
   629
lemma bind_mono[partial_function_mono]:
krauss@40173
   630
assumes mf: "mono_Heap B" and mg: "\<And>y. mono_Heap (\<lambda>f. C y f)"
krauss@40173
   631
shows "mono_Heap (\<lambda>f. B f \<guillemotright>= (\<lambda>y. C y f))"
krauss@40173
   632
proof (rule monotoneI)
krauss@40173
   633
  fix f g :: "'a \<Rightarrow> 'b Heap" assume fg: "fun_ord Heap_ord f g"
krauss@40173
   634
  from mf
krauss@40173
   635
  have 1: "Heap_ord (B f) (B g)" by (rule monotoneD) (rule fg)
krauss@40173
   636
  from mg
krauss@40173
   637
  have 2: "\<And>y'. Heap_ord (C y' f) (C y' g)" by (rule monotoneD) (rule fg)
krauss@40173
   638
krauss@40173
   639
  have "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y. C y f))"
krauss@40173
   640
    (is "Heap_ord ?L ?R")
krauss@40173
   641
  proof (rule Heap_ordI)
krauss@40173
   642
    fix h
krauss@40173
   643
    from 1 show "execute ?L h = None \<or> execute ?L h = execute ?R h"
krauss@40173
   644
      by (rule Heap_ordE[where h = h]) (auto simp: execute_bind_case)
krauss@40173
   645
  qed
krauss@40173
   646
  also
krauss@40173
   647
  have "Heap_ord (B g \<guillemotright>= (\<lambda>y'. C y' f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))"
krauss@40173
   648
    (is "Heap_ord ?L ?R")
krauss@40173
   649
  proof (rule Heap_ordI)
krauss@40173
   650
    fix h
krauss@40173
   651
    show "execute ?L h = None \<or> execute ?L h = execute ?R h"
krauss@40173
   652
    proof (cases "execute (B g) h")
krauss@40173
   653
      case None
krauss@40173
   654
      then have "execute ?L h = None" by (auto simp: execute_bind_case)
krauss@40173
   655
      thus ?thesis ..
krauss@40173
   656
    next
krauss@40173
   657
      case Some
krauss@40173
   658
      then obtain r h' where "execute (B g) h = Some (r, h')"
krauss@40173
   659
        by (metis surjective_pairing)
krauss@40173
   660
      then have "execute ?L h = execute (C r f) h'"
krauss@40173
   661
        "execute ?R h = execute (C r g) h'"
krauss@40173
   662
        by (auto simp: execute_bind_case)
krauss@40173
   663
      with 2[of r] show ?thesis by (auto elim: Heap_ordE)
krauss@40173
   664
    qed
krauss@40173
   665
  qed
krauss@40173
   666
  finally (heap.leq_trans)
krauss@40173
   667
  show "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))" .
krauss@40173
   668
qed
krauss@40173
   669
haftmann@37758
   670
hide_const (open) Heap heap guard raise' fold_map
haftmann@37724
   671
haftmann@26170
   672
end