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