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