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