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