src/Tools/Code/code_haskell.ML
author haftmann
Tue Nov 24 17:28:25 2009 +0100 (2009-11-24)
changeset 33955 fff6f11b1f09
parent 33421 3789fe962a08
child 33957 e9afca2118d4
permissions -rw-r--r--
curried take/drop
haftmann@28054
     1
(*  Title:      Tools/code/code_haskell.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@28054
     4
Serializer for Haskell.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@28054
     7
signature CODE_HASKELL =
haftmann@28054
     8
sig
haftmann@28054
     9
  val setup: theory -> theory
haftmann@28054
    10
end;
haftmann@28054
    11
haftmann@28054
    12
structure Code_Haskell : CODE_HASKELL =
haftmann@28054
    13
struct
haftmann@28054
    14
haftmann@28054
    15
val target = "Haskell";
haftmann@28054
    16
haftmann@28054
    17
open Basic_Code_Thingol;
haftmann@28054
    18
open Code_Printer;
haftmann@28054
    19
haftmann@28054
    20
infixr 5 @@;
haftmann@28054
    21
infixr 5 @|;
haftmann@28054
    22
haftmann@28054
    23
haftmann@28054
    24
(** Haskell serializer **)
haftmann@28054
    25
haftmann@31054
    26
fun pr_haskell_stmt labelled_name syntax_class syntax_tyco syntax_const
haftmann@32924
    27
    reserved deresolve contr_classparam_typs deriving_show =
haftmann@28054
    28
  let
wenzelm@30364
    29
    val deresolve_base = Long_Name.base_name o deresolve;
haftmann@28054
    30
    fun class_name class = case syntax_class class
haftmann@28054
    31
     of NONE => deresolve class
haftmann@28687
    32
      | SOME class => class;
haftmann@28054
    33
    fun pr_typcontext tyvars vs = case maps (fn (v, sort) => map (pair v) sort) vs
haftmann@28054
    34
     of [] => []
haftmann@28054
    35
      | classbinds => Pretty.enum "," "(" ")" (
haftmann@28054
    36
          map (fn (v, class) =>
haftmann@32924
    37
            str (class_name class ^ " " ^ lookup_var tyvars v)) classbinds)
haftmann@28054
    38
          @@ str " => ";
haftmann@28054
    39
    fun pr_typforall tyvars vs = case map fst vs
haftmann@28054
    40
     of [] => []
haftmann@28054
    41
      | vnames => str "forall " :: Pretty.breaks
haftmann@32924
    42
          (map (str o lookup_var tyvars) vnames) @ str "." @@ Pretty.brk 1;
haftmann@28054
    43
    fun pr_tycoexpr tyvars fxy (tyco, tys) =
haftmann@28054
    44
      brackify fxy (str tyco :: map (pr_typ tyvars BR) tys)
haftmann@28054
    45
    and pr_typ tyvars fxy (tycoexpr as tyco `%% tys) = (case syntax_tyco tyco
haftmann@28054
    46
         of NONE => pr_tycoexpr tyvars fxy (deresolve tyco, tys)
haftmann@28054
    47
          | SOME (i, pr) => pr (pr_typ tyvars) fxy tys)
haftmann@32924
    48
      | pr_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
haftmann@28054
    49
    fun pr_typdecl tyvars (vs, tycoexpr) =
haftmann@28054
    50
      Pretty.block (pr_typcontext tyvars vs @| pr_tycoexpr tyvars NOBR tycoexpr);
haftmann@28054
    51
    fun pr_typscheme tyvars (vs, ty) =
haftmann@28054
    52
      Pretty.block (pr_typforall tyvars vs @ pr_typcontext tyvars vs @| pr_typ tyvars NOBR ty);
haftmann@28708
    53
    fun pr_term tyvars thm vars fxy (IConst c) =
haftmann@28708
    54
          pr_app tyvars thm vars fxy (c, [])
haftmann@28708
    55
      | pr_term tyvars thm vars fxy (t as (t1 `$ t2)) =
haftmann@28054
    56
          (case Code_Thingol.unfold_const_app t
haftmann@28708
    57
           of SOME app => pr_app tyvars thm vars fxy app
haftmann@28054
    58
            | _ =>
haftmann@28054
    59
                brackify fxy [
haftmann@28708
    60
                  pr_term tyvars thm vars NOBR t1,
haftmann@28708
    61
                  pr_term tyvars thm vars BR t2
haftmann@28054
    62
                ])
haftmann@31889
    63
      | pr_term tyvars thm vars fxy (IVar NONE) =
haftmann@31889
    64
          str "_"
haftmann@31889
    65
      | pr_term tyvars thm vars fxy (IVar (SOME v)) =
haftmann@32924
    66
          (str o lookup_var vars) v
haftmann@31724
    67
      | pr_term tyvars thm vars fxy (t as _ `|=> _) =
haftmann@28054
    68
          let
haftmann@31874
    69
            val (binds, t') = Code_Thingol.unfold_pat_abs t;
haftmann@31889
    70
            val (ps, vars') = fold_map (pr_bind tyvars thm BR o fst) binds vars;
haftmann@28708
    71
          in brackets (str "\\" :: ps @ str "->" @@ pr_term tyvars thm vars' NOBR t') end
haftmann@28708
    72
      | pr_term tyvars thm vars fxy (ICase (cases as (_, t0))) =
haftmann@28054
    73
          (case Code_Thingol.unfold_const_app t0
haftmann@28054
    74
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@28054
    75
                then pr_case tyvars thm vars fxy cases
haftmann@28708
    76
                else pr_app tyvars thm vars fxy c_ts
haftmann@28054
    77
            | NONE => pr_case tyvars thm vars fxy cases)
haftmann@28708
    78
    and pr_app' tyvars thm vars ((c, (_, tys)), ts) = case contr_classparam_typs c
haftmann@28708
    79
     of [] => (str o deresolve) c :: map (pr_term tyvars thm vars BR) ts
haftmann@28054
    80
      | fingerprint => let
haftmann@33955
    81
          val ts_fingerprint = ts ~~ curry (uncurry take) (length ts) fingerprint;
haftmann@28054
    82
          val needs_annotation = forall (fn (_, NONE) => true | (t, SOME _) =>
haftmann@28054
    83
            (not o Code_Thingol.locally_monomorphic) t) ts_fingerprint;
haftmann@28708
    84
          fun pr_term_anno (t, NONE) _ = pr_term tyvars thm vars BR t
haftmann@28054
    85
            | pr_term_anno (t, SOME _) ty =
haftmann@28708
    86
                brackets [pr_term tyvars thm vars NOBR t, str "::", pr_typ tyvars NOBR ty];
haftmann@28054
    87
        in
haftmann@28054
    88
          if needs_annotation then
haftmann@33955
    89
            (str o deresolve) c :: map2 pr_term_anno ts_fingerprint (curry (uncurry take) (length ts) tys)
haftmann@28708
    90
          else (str o deresolve) c :: map (pr_term tyvars thm vars BR) ts
haftmann@28054
    91
        end
haftmann@31054
    92
    and pr_app tyvars = gen_pr_app (pr_app' tyvars) (pr_term tyvars) syntax_const
haftmann@31889
    93
    and pr_bind tyvars thm fxy p = gen_pr_bind (pr_term tyvars) thm fxy p
haftmann@28054
    94
    and pr_case tyvars thm vars fxy (cases as ((_, [_]), _)) =
haftmann@28054
    95
          let
haftmann@29952
    96
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@28054
    97
            fun pr ((pat, ty), t) vars =
haftmann@28054
    98
              vars
haftmann@31889
    99
              |> pr_bind tyvars thm BR pat
haftmann@28708
   100
              |>> (fn p => semicolon [p, str "=", pr_term tyvars thm vars NOBR t])
haftmann@28054
   101
            val (ps, vars') = fold_map pr binds vars;
haftmann@31665
   102
          in brackify_block fxy (str "let {")
haftmann@31665
   103
            ps
haftmann@31665
   104
            (concat [str "}", str "in", pr_term tyvars thm vars' NOBR body])
haftmann@28054
   105
          end
haftmann@29952
   106
      | pr_case tyvars thm vars fxy (((t, ty), clauses as _ :: _), _) =
haftmann@28054
   107
          let
haftmann@29952
   108
            fun pr (pat, body) =
haftmann@28054
   109
              let
haftmann@31889
   110
                val (p, vars') = pr_bind tyvars thm NOBR pat vars;
haftmann@29952
   111
              in semicolon [p, str "->", pr_term tyvars thm vars' NOBR body] end;
haftmann@31665
   112
          in brackify_block fxy
haftmann@31665
   113
            (concat [str "case", pr_term tyvars thm vars NOBR t, str "of", str "{"])
haftmann@31665
   114
            (map pr clauses)
haftmann@31665
   115
            (str "}") 
haftmann@28054
   116
          end
haftmann@31376
   117
      | pr_case tyvars thm vars fxy ((_, []), _) =
haftmann@31376
   118
          (brackify fxy o Pretty.breaks o map str) ["error", "\"empty case\""];
haftmann@28663
   119
    fun pr_stmt (name, Code_Thingol.Fun (_, ((vs, ty), []))) =
haftmann@28054
   120
          let
haftmann@32924
   121
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   122
            val n = (length o fst o Code_Thingol.unfold_fun) ty;
haftmann@28054
   123
          in
haftmann@28054
   124
            Pretty.chunks [
haftmann@28054
   125
              Pretty.block [
haftmann@28054
   126
                (str o suffix " ::" o deresolve_base) name,
haftmann@28054
   127
                Pretty.brk 1,
haftmann@28054
   128
                pr_typscheme tyvars (vs, ty),
haftmann@28054
   129
                str ";"
haftmann@28054
   130
              ],
haftmann@28054
   131
              concat (
haftmann@28054
   132
                (str o deresolve_base) name
haftmann@28054
   133
                :: map str (replicate n "_")
haftmann@28054
   134
                @ str "="
haftmann@28054
   135
                :: str "error"
haftmann@28054
   136
                @@ (str o (fn s => s ^ ";") o ML_Syntax.print_string
wenzelm@30364
   137
                    o Long_Name.base_name o Long_Name.qualifier) name
haftmann@28054
   138
              )
haftmann@28054
   139
            ]
haftmann@28054
   140
          end
haftmann@28663
   141
      | pr_stmt (name, Code_Thingol.Fun (_, ((vs, ty), raw_eqs))) =
haftmann@28054
   142
          let
haftmann@28350
   143
            val eqs = filter (snd o snd) raw_eqs;
haftmann@32924
   144
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28350
   145
            fun pr_eq ((ts, t), (thm, _)) =
haftmann@28054
   146
              let
haftmann@32913
   147
                val consts = fold Code_Thingol.add_constnames (t :: ts) [];
haftmann@32924
   148
                val vars = reserved
haftmann@32924
   149
                  |> intro_base_names
haftmann@32913
   150
                      (is_none o syntax_const) deresolve consts
haftmann@32924
   151
                  |> intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@32925
   152
                      (insert (op =)) ts []);
haftmann@28054
   153
              in
haftmann@28054
   154
                semicolon (
haftmann@28054
   155
                  (str o deresolve_base) name
haftmann@28708
   156
                  :: map (pr_term tyvars thm vars BR) ts
haftmann@28054
   157
                  @ str "="
haftmann@28708
   158
                  @@ pr_term tyvars thm vars NOBR t
haftmann@28054
   159
                )
haftmann@28054
   160
              end;
haftmann@28054
   161
          in
haftmann@28054
   162
            Pretty.chunks (
haftmann@28054
   163
              Pretty.block [
haftmann@28054
   164
                (str o suffix " ::" o deresolve_base) name,
haftmann@28054
   165
                Pretty.brk 1,
haftmann@28054
   166
                pr_typscheme tyvars (vs, ty),
haftmann@28054
   167
                str ";"
haftmann@28054
   168
              ]
haftmann@28054
   169
              :: map pr_eq eqs
haftmann@28054
   170
            )
haftmann@28054
   171
          end
haftmann@28663
   172
      | pr_stmt (name, Code_Thingol.Datatype (_, (vs, []))) =
haftmann@28054
   173
          let
haftmann@32924
   174
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   175
          in
haftmann@28054
   176
            semicolon [
haftmann@28054
   177
              str "data",
haftmann@28054
   178
              pr_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
haftmann@28054
   179
            ]
haftmann@28054
   180
          end
haftmann@28663
   181
      | pr_stmt (name, Code_Thingol.Datatype (_, (vs, [(co, [ty])]))) =
haftmann@28054
   182
          let
haftmann@32924
   183
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   184
          in
haftmann@28054
   185
            semicolon (
haftmann@28054
   186
              str "newtype"
haftmann@28054
   187
              :: pr_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
haftmann@28054
   188
              :: str "="
haftmann@28054
   189
              :: (str o deresolve_base) co
haftmann@28054
   190
              :: pr_typ tyvars BR ty
haftmann@28054
   191
              :: (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@28054
   192
            )
haftmann@28054
   193
          end
haftmann@28663
   194
      | pr_stmt (name, Code_Thingol.Datatype (_, (vs, co :: cos))) =
haftmann@28054
   195
          let
haftmann@32924
   196
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28054
   197
            fun pr_co (co, tys) =
haftmann@28054
   198
              concat (
haftmann@28054
   199
                (str o deresolve_base) co
haftmann@28054
   200
                :: map (pr_typ tyvars BR) tys
haftmann@28054
   201
              )
haftmann@28054
   202
          in
haftmann@28054
   203
            semicolon (
haftmann@28054
   204
              str "data"
haftmann@28054
   205
              :: pr_typdecl tyvars (vs, (deresolve_base name, map (ITyVar o fst) vs))
haftmann@28054
   206
              :: str "="
haftmann@28054
   207
              :: pr_co co
haftmann@28054
   208
              :: map ((fn p => Pretty.block [str "| ", p]) o pr_co) cos
haftmann@28054
   209
              @ (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@28054
   210
            )
haftmann@28054
   211
          end
haftmann@28663
   212
      | pr_stmt (name, Code_Thingol.Class (_, (v, (superclasses, classparams)))) =
haftmann@28054
   213
          let
haftmann@32924
   214
            val tyvars = intro_vars [v] reserved;
haftmann@28054
   215
            fun pr_classparam (classparam, ty) =
haftmann@28054
   216
              semicolon [
haftmann@28687
   217
                (str o deresolve_base) classparam,
haftmann@28054
   218
                str "::",
haftmann@28054
   219
                pr_typ tyvars NOBR ty
haftmann@28054
   220
              ]
haftmann@28054
   221
          in
haftmann@28054
   222
            Pretty.block_enclose (
haftmann@28054
   223
              Pretty.block [
haftmann@28054
   224
                str "class ",
haftmann@28054
   225
                Pretty.block (pr_typcontext tyvars [(v, map fst superclasses)]),
haftmann@32924
   226
                str (deresolve_base name ^ " " ^ lookup_var tyvars v),
haftmann@28054
   227
                str " where {"
haftmann@28054
   228
              ],
haftmann@28054
   229
              str "};"
haftmann@28054
   230
            ) (map pr_classparam classparams)
haftmann@28054
   231
          end
haftmann@28054
   232
      | pr_stmt (_, Code_Thingol.Classinst ((class, (tyco, vs)), (_, classparam_insts))) =
haftmann@28054
   233
          let
haftmann@32924
   234
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@28687
   235
            fun pr_instdef ((classparam, c_inst), (thm, _)) = case syntax_const classparam
haftmann@28687
   236
             of NONE => semicolon [
haftmann@28687
   237
                    (str o deresolve_base) classparam,
haftmann@28687
   238
                    str "=",
haftmann@32924
   239
                    pr_app tyvars thm reserved NOBR (c_inst, [])
haftmann@28687
   240
                  ]
haftmann@28687
   241
              | SOME (k, pr) =>
haftmann@28687
   242
                  let
haftmann@28687
   243
                    val (c_inst_name, (_, tys)) = c_inst;
haftmann@28687
   244
                    val const = if (is_some o syntax_const) c_inst_name
wenzelm@30364
   245
                      then NONE else (SOME o Long_Name.base_name o deresolve) c_inst_name;
haftmann@28687
   246
                    val proto_rhs = Code_Thingol.eta_expand k (c_inst, []);
haftmann@31874
   247
                    val (vs, rhs) = (apfst o map) fst (Code_Thingol.unfold_abs proto_rhs);
haftmann@32924
   248
                    val vars = reserved
haftmann@32924
   249
                      |> intro_vars (the_list const)
haftmann@32924
   250
                      |> intro_vars (map_filter I vs);
haftmann@31889
   251
                    val lhs = IConst (classparam, (([], []), tys)) `$$ map IVar vs;
haftmann@28687
   252
                      (*dictionaries are not relevant at this late stage*)
haftmann@28687
   253
                  in
haftmann@28687
   254
                    semicolon [
haftmann@28708
   255
                      pr_term tyvars thm vars NOBR lhs,
haftmann@28687
   256
                      str "=",
haftmann@28708
   257
                      pr_term tyvars thm vars NOBR rhs
haftmann@28687
   258
                    ]
haftmann@28687
   259
                  end;
haftmann@28054
   260
          in
haftmann@28054
   261
            Pretty.block_enclose (
haftmann@28054
   262
              Pretty.block [
haftmann@28054
   263
                str "instance ",
haftmann@28054
   264
                Pretty.block (pr_typcontext tyvars vs),
haftmann@28054
   265
                str (class_name class ^ " "),
haftmann@28054
   266
                pr_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
haftmann@28054
   267
                str " where {"
haftmann@28054
   268
              ],
haftmann@28054
   269
              str "};"
haftmann@28054
   270
            ) (map pr_instdef classparam_insts)
haftmann@28054
   271
          end;
haftmann@28054
   272
  in pr_stmt end;
haftmann@28054
   273
haftmann@32924
   274
fun haskell_program_of_program labelled_name module_name module_prefix reserved raw_module_alias program =
haftmann@28054
   275
  let
haftmann@28054
   276
    val module_alias = if is_some module_name then K module_name else raw_module_alias;
haftmann@32924
   277
    val reserved = Name.make_context reserved;
haftmann@32924
   278
    val mk_name_module = mk_name_module reserved module_prefix module_alias program;
haftmann@28054
   279
    fun add_stmt (name, (stmt, deps)) =
haftmann@28054
   280
      let
haftmann@32924
   281
        val (module_name, base) = dest_name name;
haftmann@28054
   282
        val module_name' = mk_name_module module_name;
haftmann@28054
   283
        val mk_name_stmt = yield_singleton Name.variants;
haftmann@28054
   284
        fun add_fun upper (nsp_fun, nsp_typ) =
haftmann@28054
   285
          let
haftmann@28054
   286
            val (base', nsp_fun') =
haftmann@32924
   287
              mk_name_stmt (if upper then first_upper base else base) nsp_fun
haftmann@28054
   288
          in (base', (nsp_fun', nsp_typ)) end;
haftmann@28054
   289
        fun add_typ (nsp_fun, nsp_typ) =
haftmann@28054
   290
          let
haftmann@32924
   291
            val (base', nsp_typ') = mk_name_stmt (first_upper base) nsp_typ
haftmann@28054
   292
          in (base', (nsp_fun, nsp_typ')) end;
haftmann@28054
   293
        val add_name = case stmt
haftmann@28054
   294
         of Code_Thingol.Fun _ => add_fun false
haftmann@28054
   295
          | Code_Thingol.Datatype _ => add_typ
haftmann@28054
   296
          | Code_Thingol.Datatypecons _ => add_fun true
haftmann@28054
   297
          | Code_Thingol.Class _ => add_typ
haftmann@28054
   298
          | Code_Thingol.Classrel _ => pair base
haftmann@28054
   299
          | Code_Thingol.Classparam _ => add_fun false
haftmann@28054
   300
          | Code_Thingol.Classinst _ => pair base;
haftmann@28054
   301
        fun add_stmt' base' = case stmt
haftmann@28054
   302
         of Code_Thingol.Datatypecons _ =>
wenzelm@30364
   303
              cons (name, (Long_Name.append module_name' base', NONE))
haftmann@28054
   304
          | Code_Thingol.Classrel _ => I
haftmann@28054
   305
          | Code_Thingol.Classparam _ =>
wenzelm@30364
   306
              cons (name, (Long_Name.append module_name' base', NONE))
wenzelm@30364
   307
          | _ => cons (name, (Long_Name.append module_name' base', SOME stmt));
haftmann@28054
   308
      in
haftmann@32924
   309
        Symtab.map_default (module_name', ([], ([], (reserved, reserved))))
haftmann@28054
   310
              (apfst (fold (insert (op = : string * string -> bool)) deps))
haftmann@28054
   311
        #> `(fn program => add_name ((snd o snd o the o Symtab.lookup program) module_name'))
haftmann@28054
   312
        #-> (fn (base', names) =>
haftmann@28054
   313
              (Symtab.map_entry module_name' o apsnd) (fn (stmts, _) =>
haftmann@28054
   314
              (add_stmt' base' stmts, names)))
haftmann@28054
   315
      end;
haftmann@28054
   316
    val hs_program = fold add_stmt (AList.make (fn name =>
haftmann@28054
   317
      (Graph.get_node program name, Graph.imm_succs program name))
haftmann@28054
   318
      (Graph.strong_conn program |> flat)) Symtab.empty;
haftmann@28663
   319
    fun deresolver name = (fst o the o AList.lookup (op =) ((fst o snd o the
haftmann@32924
   320
      o Symtab.lookup hs_program) ((mk_name_module o fst o dest_name) name))) name
haftmann@28663
   321
      handle Option => error ("Unknown statement name: " ^ labelled_name name);
haftmann@28054
   322
  in (deresolver, hs_program) end;
haftmann@28054
   323
haftmann@28054
   324
fun serialize_haskell module_prefix raw_module_name string_classes labelled_name
haftmann@32924
   325
    raw_reserved includes raw_module_alias
haftmann@31054
   326
    syntax_class syntax_tyco syntax_const program cs destination =
haftmann@28054
   327
  let
haftmann@28054
   328
    val stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@28054
   329
    val module_name = if null stmt_names then raw_module_name else SOME "Code";
haftmann@32924
   330
    val reserved = fold (insert (op =) o fst) includes raw_reserved;
haftmann@28054
   331
    val (deresolver, hs_program) = haskell_program_of_program labelled_name
haftmann@32924
   332
      module_name module_prefix reserved raw_module_alias program;
haftmann@28054
   333
    val contr_classparam_typs = Code_Thingol.contr_classparam_typs program;
haftmann@28054
   334
    fun deriving_show tyco =
haftmann@28054
   335
      let
haftmann@28054
   336
        fun deriv _ "fun" = false
haftmann@28054
   337
          | deriv tycos tyco = member (op =) tycos tyco orelse
haftmann@28054
   338
              case try (Graph.get_node program) tyco
haftmann@28663
   339
                of SOME (Code_Thingol.Datatype (_, (_, cs))) => forall (deriv' (tyco :: tycos))
haftmann@28054
   340
                    (maps snd cs)
haftmann@28054
   341
                 | NONE => true
haftmann@28054
   342
        and deriv' tycos (tyco `%% tys) = deriv tycos tyco
haftmann@28054
   343
              andalso forall (deriv' tycos) tys
haftmann@28054
   344
          | deriv' _ (ITyVar _) = true
haftmann@28054
   345
      in deriv [] tyco end;
haftmann@32924
   346
    val reserved = make_vars reserved;
haftmann@31054
   347
    fun pr_stmt qualified = pr_haskell_stmt labelled_name
haftmann@32924
   348
      syntax_class syntax_tyco syntax_const reserved
wenzelm@30364
   349
      (if qualified then deresolver else Long_Name.base_name o deresolver)
haftmann@32903
   350
      contr_classparam_typs
haftmann@28054
   351
      (if string_classes then deriving_show else K false);
haftmann@28054
   352
    fun pr_module name content =
haftmann@28054
   353
      (name, Pretty.chunks [
haftmann@28054
   354
        str ("module " ^ name ^ " where {"),
haftmann@28054
   355
        str "",
haftmann@28054
   356
        content,
haftmann@28054
   357
        str "",
haftmann@28054
   358
        str "}"
haftmann@28054
   359
      ]);
haftmann@28054
   360
    fun serialize_module1 (module_name', (deps, (stmts, _))) =
haftmann@28054
   361
      let
haftmann@28054
   362
        val stmt_names = map fst stmts;
haftmann@33421
   363
        val qualified = is_none module_name;
haftmann@33421
   364
        val imports = subtract (op =) stmt_names deps
haftmann@28054
   365
          |> distinct (op =)
haftmann@33421
   366
          |> map_filter (try deresolver)
wenzelm@30364
   367
          |> map Long_Name.qualifier
haftmann@28054
   368
          |> distinct (op =);
haftmann@29794
   369
        fun pr_import_include (name, _) = str ("import qualified " ^ name ^ ";");
haftmann@28054
   370
        val pr_import_module = str o (if qualified
haftmann@28054
   371
          then prefix "import qualified "
haftmann@28054
   372
          else prefix "import ") o suffix ";";
haftmann@28054
   373
        val content = Pretty.chunks (
haftmann@28054
   374
            map pr_import_include includes
haftmann@28054
   375
            @ map pr_import_module imports
haftmann@28054
   376
            @ str ""
haftmann@28054
   377
            :: separate (str "") (map_filter
haftmann@28054
   378
              (fn (name, (_, SOME stmt)) => SOME (pr_stmt qualified (name, stmt))
haftmann@28054
   379
                | (_, (_, NONE)) => NONE) stmts)
haftmann@28054
   380
          )
haftmann@28054
   381
      in pr_module module_name' content end;
haftmann@28054
   382
    fun serialize_module2 (_, (_, (stmts, _))) = Pretty.chunks (
haftmann@28054
   383
      separate (str "") (map_filter
haftmann@28054
   384
        (fn (name, (_, SOME stmt)) => if null stmt_names
haftmann@28054
   385
              orelse member (op =) stmt_names name
haftmann@28054
   386
              then SOME (pr_stmt false (name, stmt))
haftmann@28054
   387
              else NONE
haftmann@28054
   388
          | (_, (_, NONE)) => NONE) stmts));
haftmann@28054
   389
    val serialize_module =
haftmann@28054
   390
      if null stmt_names then serialize_module1 else pair "" o serialize_module2;
haftmann@29832
   391
    fun check_destination destination =
haftmann@29832
   392
      (File.check destination; destination);
haftmann@28054
   393
    fun write_module destination (modlname, content) =
haftmann@28054
   394
      let
haftmann@28054
   395
        val filename = case modlname
haftmann@28054
   396
         of "" => Path.explode "Main.hs"
haftmann@28054
   397
          | _ => (Path.ext "hs" o Path.explode o implode o separate "/"
wenzelm@30364
   398
                o Long_Name.explode) modlname;
haftmann@28054
   399
        val pathname = Path.append destination filename;
haftmann@28054
   400
        val _ = File.mkdir (Path.dir pathname);
haftmann@29135
   401
      in File.write pathname
haftmann@29135
   402
        ("{-# OPTIONS_GHC -fglasgow-exts #-}\n\n"
haftmann@29135
   403
          ^ Code_Target.code_of_pretty content)
haftmann@29135
   404
      end
haftmann@28054
   405
  in
haftmann@28054
   406
    Code_Target.mk_serialization target NONE
haftmann@29832
   407
      (fn NONE => K () o map (Code_Target.code_writeln o snd) | SOME file => K () o map
haftmann@29832
   408
        (write_module (check_destination file)))
haftmann@28054
   409
      (rpair [] o cat_lines o map (Code_Target.code_of_pretty o snd))
haftmann@28054
   410
      (map (uncurry pr_module) includes
haftmann@28054
   411
        @ map serialize_module (Symtab.dest hs_program))
haftmann@28054
   412
      destination
haftmann@28054
   413
  end;
haftmann@28054
   414
haftmann@28064
   415
val literals = let
haftmann@28064
   416
  fun char_haskell c =
haftmann@28064
   417
    let
haftmann@28064
   418
      val s = ML_Syntax.print_char c;
haftmann@28064
   419
    in if s = "'" then "\\'" else s end;
haftmann@28064
   420
in Literals {
haftmann@28064
   421
  literal_char = enclose "'" "'" o char_haskell,
haftmann@28064
   422
  literal_string = quote o translate_string char_haskell,
haftmann@28064
   423
  literal_numeral = fn unbounded => fn k => if k >= 0 then string_of_int k
haftmann@28064
   424
    else enclose "(" ")" (signed_string_of_int k),
haftmann@28064
   425
  literal_list = Pretty.enum "," "[" "]",
haftmann@28064
   426
  infix_cons = (5, ":")
haftmann@28064
   427
} end;
haftmann@28064
   428
haftmann@28054
   429
haftmann@28054
   430
(** optional monad syntax **)
haftmann@28054
   431
haftmann@28054
   432
fun pretty_haskell_monad c_bind =
haftmann@28054
   433
  let
haftmann@31874
   434
    fun dest_bind t1 t2 = case Code_Thingol.split_pat_abs t2
haftmann@31889
   435
     of SOME ((pat, ty), t') =>
haftmann@31889
   436
          SOME ((SOME ((pat, ty), true), t1), t')
haftmann@28145
   437
      | NONE => NONE;
haftmann@28663
   438
    fun dest_monad c_bind_name (IConst (c, _) `$ t1 `$ t2) =
haftmann@28663
   439
          if c = c_bind_name then dest_bind t1 t2
haftmann@28145
   440
          else NONE
haftmann@28663
   441
      | dest_monad _ t = case Code_Thingol.split_let t
haftmann@28145
   442
         of SOME (((pat, ty), tbind), t') =>
haftmann@31889
   443
              SOME ((SOME ((pat, ty), false), tbind), t')
haftmann@28145
   444
          | NONE => NONE;
haftmann@28663
   445
    fun implode_monad c_bind_name = Code_Thingol.unfoldr (dest_monad c_bind_name);
haftmann@28145
   446
    fun pr_monad pr_bind pr (NONE, t) vars =
haftmann@28145
   447
          (semicolon [pr vars NOBR t], vars)
haftmann@31889
   448
      | pr_monad pr_bind pr (SOME ((bind, _), true), t) vars = vars
haftmann@28145
   449
          |> pr_bind NOBR bind
haftmann@28145
   450
          |>> (fn p => semicolon [p, str "<-", pr vars NOBR t])
haftmann@31889
   451
      | pr_monad pr_bind pr (SOME ((bind, _), false), t) vars = vars
haftmann@28145
   452
          |> pr_bind NOBR bind
haftmann@28145
   453
          |>> (fn p => semicolon [str "let", p, str "=", pr vars NOBR t]);
haftmann@31054
   454
    fun pretty _ [c_bind'] pr thm vars fxy [(t1, _), (t2, _)] = case dest_bind t1 t2
haftmann@28145
   455
     of SOME (bind, t') => let
haftmann@31054
   456
          val (binds, t'') = implode_monad c_bind' t'
haftmann@31889
   457
          val (ps, vars') = fold_map (pr_monad (gen_pr_bind (K pr) thm) pr) (bind :: binds) vars;
haftmann@28145
   458
        in (brackify fxy o single o Pretty.enclose "do {" "}" o Pretty.breaks) (ps @| pr vars' NOBR t'') end
haftmann@28145
   459
      | NONE => brackify_infix (1, L) fxy
haftmann@28145
   460
          [pr vars (INFX (1, L)) t1, str ">>=", pr vars (INFX (1, X)) t2]
haftmann@31054
   461
  in (2, ([c_bind], pretty)) end;
haftmann@28054
   462
haftmann@28145
   463
fun add_monad target' raw_c_bind thy =
haftmann@28054
   464
  let
haftmann@31156
   465
    val c_bind = Code.read_const thy raw_c_bind;
haftmann@28054
   466
  in if target = target' then
haftmann@28054
   467
    thy
haftmann@28145
   468
    |> Code_Target.add_syntax_const target c_bind
haftmann@28663
   469
        (SOME (pretty_haskell_monad c_bind))
haftmann@28054
   470
  else error "Only Haskell target allows for monad syntax" end;
haftmann@28054
   471
haftmann@28054
   472
haftmann@28054
   473
(** Isar setup **)
haftmann@28054
   474
haftmann@28054
   475
fun isar_seri_haskell module =
haftmann@28054
   476
  Code_Target.parse_args (Scan.option (Args.$$$ "root" -- Args.colon |-- Args.name)
haftmann@28054
   477
    -- Scan.optional (Args.$$$ "string_classes" >> K true) false
haftmann@28054
   478
    >> (fn (module_prefix, string_classes) =>
haftmann@28054
   479
      serialize_haskell module_prefix module string_classes));
haftmann@28054
   480
haftmann@28054
   481
val _ =
haftmann@28054
   482
  OuterSyntax.command "code_monad" "define code syntax for monads" OuterKeyword.thy_decl (
haftmann@28145
   483
    OuterParse.term_group -- OuterParse.name >> (fn (raw_bind, target) =>
haftmann@28145
   484
      Toplevel.theory  (add_monad target raw_bind))
haftmann@28054
   485
  );
haftmann@28054
   486
haftmann@28054
   487
val setup =
haftmann@28064
   488
  Code_Target.add_target (target, (isar_seri_haskell, literals))
haftmann@28054
   489
  #> Code_Target.add_syntax_tyco target "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@28054
   490
      brackify_infix (1, R) fxy [
haftmann@28054
   491
        pr_typ (INFX (1, X)) ty1,
haftmann@28054
   492
        str "->",
haftmann@28054
   493
        pr_typ (INFX (1, R)) ty2
haftmann@28054
   494
      ]))
haftmann@28054
   495
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   496
      "hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
haftmann@28054
   497
      "import", "default", "forall", "let", "in", "class", "qualified", "data",
haftmann@28054
   498
      "newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
haftmann@28054
   499
    ]
haftmann@28054
   500
  #> fold (Code_Target.add_reserved target) [
haftmann@28054
   501
      "Prelude", "Main", "Bool", "Maybe", "Either", "Ordering", "Char", "String", "Int",
haftmann@28054
   502
      "Integer", "Float", "Double", "Rational", "IO", "Eq", "Ord", "Enum", "Bounded",
haftmann@28054
   503
      "Num", "Real", "Integral", "Fractional", "Floating", "RealFloat", "Monad", "Functor",
haftmann@28054
   504
      "AlreadyExists", "ArithException", "ArrayException", "AssertionFailed", "AsyncException",
haftmann@28054
   505
      "BlockedOnDeadMVar", "Deadlock", "Denormal", "DivideByZero", "DotNetException", "DynException",
haftmann@28054
   506
      "Dynamic", "EOF", "EQ", "EmptyRec", "ErrorCall", "ExitException", "ExitFailure",
haftmann@28054
   507
      "ExitSuccess", "False", "GT", "HeapOverflow",
haftmann@28054
   508
      "IOError", "IOException", "IllegalOperation",
haftmann@28054
   509
      "IndexOutOfBounds", "Just", "Key", "LT", "Left", "LossOfPrecision", "NoMethodError",
haftmann@28054
   510
      "NoSuchThing", "NonTermination", "Nothing", "Obj", "OtherError", "Overflow",
haftmann@28054
   511
      "PatternMatchFail", "PermissionDenied", "ProtocolError", "RecConError", "RecSelError",
haftmann@28054
   512
      "RecUpdError", "ResourceBusy", "ResourceExhausted", "Right", "StackOverflow",
haftmann@28054
   513
      "ThreadKilled", "True", "TyCon", "TypeRep", "UndefinedElement", "Underflow",
haftmann@28054
   514
      "UnsupportedOperation", "UserError", "abs", "absReal", "acos", "acosh", "all",
haftmann@28054
   515
      "and", "any", "appendFile", "asTypeOf", "asciiTab", "asin", "asinh", "atan",
haftmann@28054
   516
      "atan2", "atanh", "basicIORun", "blockIO", "boundedEnumFrom", "boundedEnumFromThen",
haftmann@28054
   517
      "boundedEnumFromThenTo", "boundedEnumFromTo", "boundedPred", "boundedSucc", "break",
haftmann@28054
   518
      "catch", "catchException", "ceiling", "compare", "concat", "concatMap", "const",
haftmann@28054
   519
      "cos", "cosh", "curry", "cycle", "decodeFloat", "denominator", "div", "divMod",
haftmann@28054
   520
      "doubleToRatio", "doubleToRational", "drop", "dropWhile", "either", "elem",
haftmann@28054
   521
      "emptyRec", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
haftmann@28054
   522
      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip",
haftmann@28054
   523
      "floatDigits", "floatProperFraction", "floatRadix", "floatRange", "floatToRational",
haftmann@28054
   524
      "floor", "fmap", "foldl", "foldl'", "foldl1", "foldr", "foldr1", "fromDouble",
haftmann@28054
   525
      "fromEnum", "fromEnum_0", "fromInt", "fromInteger", "fromIntegral", "fromObj",
haftmann@28054
   526
      "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head",
haftmann@28054
   527
      "id", "inRange", "index", "init", "intToRatio", "interact", "ioError", "isAlpha",
haftmann@28054
   528
      "isAlphaNum", "isDenormalized", "isDigit", "isHexDigit", "isIEEE", "isInfinite",
haftmann@28054
   529
      "isLower", "isNaN", "isNegativeZero", "isOctDigit", "isSpace", "isUpper", "iterate", "iterate'",
haftmann@28054
   530
      "last", "lcm", "length", "lex", "lexDigits", "lexLitChar", "lexmatch", "lines", "log",
haftmann@28054
   531
      "logBase", "lookup", "loop", "map", "mapM", "mapM_", "max", "maxBound", "maximum",
haftmann@28054
   532
      "maybe", "min", "minBound", "minimum", "mod", "negate", "nonnull", "not", "notElem",
haftmann@28054
   533
      "null", "numerator", "numericEnumFrom", "numericEnumFromThen", "numericEnumFromThenTo",
haftmann@28054
   534
      "numericEnumFromTo", "odd", "or", "otherwise", "pi", "pred", 
haftmann@28054
   535
      "print", "product", "properFraction", "protectEsc", "putChar", "putStr", "putStrLn",
haftmann@28054
   536
      "quot", "quotRem", "range", "rangeSize", "rationalToDouble", "rationalToFloat",
haftmann@28054
   537
      "rationalToRealFloat", "read", "readDec", "readField", "readFieldName", "readFile",
haftmann@28054
   538
      "readFloat", "readHex", "readIO", "readInt", "readList", "readLitChar", "readLn",
haftmann@28054
   539
      "readOct", "readParen", "readSigned", "reads", "readsPrec", "realFloatToRational",
haftmann@28054
   540
      "realToFrac", "recip", "reduce", "rem", "repeat", "replicate", "return", "reverse",
haftmann@28054
   541
      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence",
haftmann@28054
   542
      "sequence_", "show", "showChar", "showException", "showField", "showList",
haftmann@28054
   543
      "showLitChar", "showParen", "showString", "shows", "showsPrec", "significand",
haftmann@28054
   544
      "signum", "signumReal", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract",
haftmann@28054
   545
      "succ", "sum", "tail", "take", "takeWhile", "takeWhile1", "tan", "tanh", "threadToIOResult",
haftmann@28054
   546
      "throw", "toEnum", "toInt", "toInteger", "toObj", "toRational", "truncate", "uncurry",
haftmann@28054
   547
      "undefined", "unlines", "unsafeCoerce", "unsafeIndex", "unsafeRangeSize", "until", "unwords",
haftmann@28054
   548
      "unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3"
haftmann@28054
   549
    ] (*due to weird handling of ':', we can't do anything else than to import *all* prelude symbols*);
haftmann@28054
   550
haftmann@28054
   551
end; (*struct*)