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