src/Tools/code/code_target.ML
author haftmann
Mon Aug 13 21:22:40 2007 +0200 (2007-08-13)
changeset 24251 ae3eb1766e56
parent 24219 e558fe311376
child 24284 f5afd33f5d02
permissions -rw-r--r--
fixed OCaml bug
haftmann@24219
     1
(*  Title:      Tools/code/code_target.ML
haftmann@24219
     2
    ID:         $Id$
haftmann@24219
     3
    Author:     Florian Haftmann, TU Muenchen
haftmann@24219
     4
haftmann@24219
     5
Serializer from intermediate language ("Thin-gol")
haftmann@24219
     6
to target languages (like SML or Haskell).
haftmann@24219
     7
*)
haftmann@24219
     8
haftmann@24219
     9
signature CODE_TARGET =
haftmann@24219
    10
sig
haftmann@24219
    11
  include BASIC_CODE_THINGOL;
haftmann@24219
    12
haftmann@24219
    13
  val add_syntax_class: string -> class
haftmann@24219
    14
    -> (string * (CodeUnit.const * string) list) option -> theory -> theory;
haftmann@24219
    15
  val add_syntax_inst: string -> string * class -> bool -> theory -> theory;
haftmann@24219
    16
  val add_syntax_tycoP: string -> string -> OuterParse.token list
haftmann@24219
    17
    -> (theory -> theory) * OuterParse.token list;
haftmann@24219
    18
  val add_syntax_constP: string -> string -> OuterParse.token list
haftmann@24219
    19
    -> (theory -> theory) * OuterParse.token list;
haftmann@24219
    20
haftmann@24219
    21
  val add_undefined: string -> string -> string -> theory -> theory;
haftmann@24219
    22
  val add_pretty_list: string -> string -> string -> theory -> theory;
haftmann@24219
    23
  val add_pretty_list_string: string -> string -> string
haftmann@24219
    24
    -> string -> string list -> theory -> theory;
haftmann@24219
    25
  val add_pretty_char: string -> string -> string list -> theory -> theory
haftmann@24219
    26
  val add_pretty_numeral: string -> bool -> string * typ -> string -> string -> string
haftmann@24219
    27
    -> string -> string -> theory -> theory;
haftmann@24219
    28
  val add_pretty_ml_string: string -> string -> string list -> string
haftmann@24219
    29
    -> string -> string -> theory -> theory;
haftmann@24219
    30
  val add_pretty_imperative_monad_bind: string -> string -> theory -> theory;
haftmann@24219
    31
haftmann@24219
    32
  type serializer;
haftmann@24219
    33
  val add_serializer: string * serializer -> theory -> theory;
haftmann@24219
    34
  val get_serializer: theory -> string -> bool -> string option -> string option -> Args.T list
haftmann@24219
    35
    -> (theory -> string -> string) -> string list option -> CodeThingol.code -> unit;
haftmann@24219
    36
  val assert_serializer: theory -> string -> string;
haftmann@24219
    37
haftmann@24219
    38
  val eval_verbose: bool ref;
haftmann@24219
    39
  val eval_term: theory -> (theory -> string -> string) -> CodeThingol.code
haftmann@24219
    40
    -> (string * 'a option ref) * CodeThingol.iterm -> string list -> 'a;
haftmann@24219
    41
  val code_width: int ref;
haftmann@24219
    42
haftmann@24219
    43
  val setup: theory -> theory;
haftmann@24219
    44
end;
haftmann@24219
    45
haftmann@24219
    46
structure CodeTarget : CODE_TARGET =
haftmann@24219
    47
struct
haftmann@24219
    48
haftmann@24219
    49
open BasicCodeThingol;
haftmann@24219
    50
haftmann@24219
    51
(** basics **)
haftmann@24219
    52
haftmann@24219
    53
infixr 5 @@;
haftmann@24219
    54
infixr 5 @|;
haftmann@24219
    55
fun x @@ y = [x, y];
haftmann@24219
    56
fun xs @| y = xs @ [y];
haftmann@24219
    57
val str = PrintMode.with_default Pretty.str;
haftmann@24219
    58
val concat = Pretty.block o Pretty.breaks;
haftmann@24219
    59
val brackets = Pretty.enclose "(" ")" o Pretty.breaks;
haftmann@24219
    60
fun semicolon ps = Pretty.block [concat ps, str ";"];
haftmann@24219
    61
haftmann@24219
    62
haftmann@24219
    63
(** syntax **)
haftmann@24219
    64
haftmann@24219
    65
datatype lrx = L | R | X;
haftmann@24219
    66
haftmann@24219
    67
datatype fixity =
haftmann@24219
    68
    BR
haftmann@24219
    69
  | NOBR
haftmann@24219
    70
  | INFX of (int * lrx);
haftmann@24219
    71
haftmann@24219
    72
val APP = INFX (~1, L);
haftmann@24219
    73
haftmann@24219
    74
fun eval_lrx L L = false
haftmann@24219
    75
  | eval_lrx R R = false
haftmann@24219
    76
  | eval_lrx _ _ = true;
haftmann@24219
    77
haftmann@24219
    78
fun eval_fxy NOBR NOBR = false
haftmann@24219
    79
  | eval_fxy BR NOBR = false
haftmann@24219
    80
  | eval_fxy NOBR BR = false
haftmann@24219
    81
  | eval_fxy (INFX (pr, lr)) (INFX (pr_ctxt, lr_ctxt)) =
haftmann@24219
    82
      pr < pr_ctxt
haftmann@24219
    83
      orelse pr = pr_ctxt
haftmann@24219
    84
        andalso eval_lrx lr lr_ctxt
haftmann@24219
    85
      orelse pr_ctxt = ~1
haftmann@24219
    86
  | eval_fxy _ (INFX _) = false
haftmann@24219
    87
  | eval_fxy (INFX _) NOBR = false
haftmann@24219
    88
  | eval_fxy _ _ = true;
haftmann@24219
    89
haftmann@24219
    90
fun gen_brackify _ [p] = p
haftmann@24219
    91
  | gen_brackify true (ps as _::_) = Pretty.enclose "(" ")" ps
haftmann@24219
    92
  | gen_brackify false (ps as _::_) = Pretty.block ps;
haftmann@24219
    93
haftmann@24219
    94
fun brackify fxy_ctxt ps =
haftmann@24219
    95
  gen_brackify (eval_fxy BR fxy_ctxt) (Pretty.breaks ps);
haftmann@24219
    96
haftmann@24219
    97
fun brackify_infix infx fxy_ctxt ps =
haftmann@24219
    98
  gen_brackify (eval_fxy (INFX infx) fxy_ctxt) (Pretty.breaks ps);
haftmann@24219
    99
haftmann@24219
   100
type class_syntax = string * (string -> string option);
haftmann@24219
   101
type typ_syntax = int * ((fixity -> itype -> Pretty.T)
haftmann@24219
   102
  -> fixity -> itype list -> Pretty.T);
haftmann@24219
   103
type term_syntax = int * ((CodeName.var_ctxt -> fixity -> iterm -> Pretty.T)
haftmann@24219
   104
  -> CodeName.var_ctxt -> fixity -> (iterm * itype) list -> Pretty.T);
haftmann@24219
   105
haftmann@24219
   106
haftmann@24219
   107
(* user-defined syntax *)
haftmann@24219
   108
haftmann@24219
   109
datatype 'a mixfix =
haftmann@24219
   110
    Arg of fixity
haftmann@24219
   111
  | Pretty of Pretty.T;
haftmann@24219
   112
haftmann@24219
   113
fun mk_mixfix prep_arg (fixity_this, mfx) =
haftmann@24219
   114
  let
haftmann@24219
   115
    fun is_arg (Arg _) = true
haftmann@24219
   116
      | is_arg _ = false;
haftmann@24219
   117
    val i = (length o filter is_arg) mfx;
haftmann@24219
   118
    fun fillin _ [] [] =
haftmann@24219
   119
          []
haftmann@24219
   120
      | fillin pr (Arg fxy :: mfx) (a :: args) =
haftmann@24219
   121
          (pr fxy o prep_arg) a :: fillin pr mfx args
haftmann@24219
   122
      | fillin pr (Pretty p :: mfx) args =
haftmann@24219
   123
          p :: fillin pr mfx args
haftmann@24219
   124
      | fillin _ [] _ =
haftmann@24219
   125
          error ("Inconsistent mixfix: too many arguments")
haftmann@24219
   126
      | fillin _ _ [] =
haftmann@24219
   127
          error ("Inconsistent mixfix: too less arguments");
haftmann@24219
   128
  in
haftmann@24219
   129
    (i, fn pr => fn fixity_ctxt => fn args =>
haftmann@24219
   130
      gen_brackify (eval_fxy fixity_this fixity_ctxt) (fillin pr mfx args))
haftmann@24219
   131
  end;
haftmann@24219
   132
haftmann@24219
   133
fun parse_infix prep_arg (x, i) s =
haftmann@24219
   134
  let
haftmann@24219
   135
    val l = case x of L => INFX (i, L) | _ => INFX (i, X);
haftmann@24219
   136
    val r = case x of R => INFX (i, R) | _ => INFX (i, X);
haftmann@24219
   137
  in
haftmann@24219
   138
    mk_mixfix prep_arg (INFX (i, x), [Arg l, (Pretty o Pretty.brk) 1, (Pretty o str) s, (Pretty o Pretty.brk) 1, Arg r])
haftmann@24219
   139
  end;
haftmann@24219
   140
haftmann@24219
   141
fun parse_mixfix prep_arg s =
haftmann@24219
   142
  let
haftmann@24219
   143
    val sym_any = Scan.one Symbol.is_regular;
haftmann@24219
   144
    val parse = Scan.optional ($$ "!" >> K true) false -- Scan.repeat (
haftmann@24219
   145
         ($$ "(" -- $$ "_" -- $$ ")" >> K (Arg NOBR))
haftmann@24219
   146
      || ($$ "_" >> K (Arg BR))
haftmann@24219
   147
      || ($$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length))
haftmann@24219
   148
      || (Scan.repeat1
haftmann@24219
   149
           (   $$ "'" |-- sym_any
haftmann@24219
   150
            || Scan.unless ($$ "_" || $$ "/" || $$ "(" |-- $$ "_" |-- $$ ")")
haftmann@24219
   151
                 sym_any) >> (Pretty o str o implode)));
haftmann@24219
   152
  in case Scan.finite Symbol.stopper parse (Symbol.explode s)
haftmann@24219
   153
   of ((_, p as [_]), []) => mk_mixfix prep_arg (NOBR, p)
haftmann@24219
   154
    | ((b, p as _ :: _ :: _), []) => mk_mixfix prep_arg (if b then NOBR else BR, p)
haftmann@24219
   155
    | _ => Scan.!! (the_default ("malformed mixfix annotation: " ^ quote s) o snd) Scan.fail ()
haftmann@24219
   156
  end;
haftmann@24219
   157
haftmann@24219
   158
fun parse_args f args =
haftmann@24219
   159
  case Scan.read Args.stopper f args
haftmann@24219
   160
   of SOME x => x
haftmann@24219
   161
    | NONE => error "Bad serializer arguments";
haftmann@24219
   162
haftmann@24219
   163
haftmann@24219
   164
(* generic serializer combinators *)
haftmann@24219
   165
haftmann@24219
   166
fun gen_pr_app pr_app' pr_term const_syntax labelled_name is_cons
haftmann@24219
   167
      lhs vars fxy (app as ((c, (_, tys)), ts)) =
haftmann@24219
   168
  case const_syntax c
haftmann@24219
   169
   of NONE => if lhs andalso not (is_cons c) then
haftmann@24219
   170
          error ("non-constructor on left hand side of equation: " ^ labelled_name c)
haftmann@24219
   171
        else brackify fxy (pr_app' lhs vars app)
haftmann@24219
   172
    | SOME (i, pr) =>
haftmann@24219
   173
        let
haftmann@24219
   174
          val k = if i < 0 then length tys else i;
haftmann@24219
   175
          fun pr' fxy ts = pr (pr_term lhs) vars fxy (ts ~~ curry Library.take k tys);
haftmann@24219
   176
        in if k = length ts
haftmann@24219
   177
          then pr' fxy ts
haftmann@24219
   178
        else if k < length ts
haftmann@24219
   179
          then case chop k ts of (ts1, ts2) =>
haftmann@24219
   180
            brackify fxy (pr' APP ts1 :: map (pr_term lhs vars BR) ts2)
haftmann@24219
   181
          else pr_term lhs vars fxy (CodeThingol.eta_expand app k)
haftmann@24219
   182
        end;
haftmann@24219
   183
haftmann@24219
   184
fun gen_pr_bind pr_bind' pr_term fxy ((v, pat), ty) vars =
haftmann@24219
   185
  let
haftmann@24219
   186
    val vs = case pat
haftmann@24219
   187
     of SOME pat => CodeThingol.fold_varnames (insert (op =)) pat []
haftmann@24219
   188
      | NONE => [];
haftmann@24219
   189
    val vars' = CodeName.intro_vars (the_list v) vars;
haftmann@24219
   190
    val vars'' = CodeName.intro_vars vs vars';
haftmann@24219
   191
    val v' = Option.map (CodeName.lookup_var vars') v;
haftmann@24219
   192
    val pat' = Option.map (pr_term vars'' fxy) pat;
haftmann@24219
   193
  in (pr_bind' ((v', pat'), ty), vars'') end;
haftmann@24219
   194
haftmann@24219
   195
haftmann@24219
   196
(* list, char, string, numeral and monad abstract syntax transformations *)
haftmann@24219
   197
haftmann@24219
   198
fun implode_list c_nil c_cons t =
haftmann@24219
   199
  let
haftmann@24219
   200
    fun dest_cons (IConst (c, _) `$ t1 `$ t2) =
haftmann@24219
   201
          if c = c_cons
haftmann@24219
   202
          then SOME (t1, t2)
haftmann@24219
   203
          else NONE
haftmann@24219
   204
      | dest_cons _ = NONE;
haftmann@24219
   205
    val (ts, t') = CodeThingol.unfoldr dest_cons t;
haftmann@24219
   206
  in case t'
haftmann@24219
   207
   of IConst (c, _) => if c = c_nil then SOME ts else NONE
haftmann@24219
   208
    | _ => NONE
haftmann@24219
   209
  end;
haftmann@24219
   210
haftmann@24219
   211
fun decode_char c_nibbles (IConst (c1, _), IConst (c2, _)) =
haftmann@24219
   212
      let
haftmann@24219
   213
        fun idx c = find_index (curry (op =) c) c_nibbles;
haftmann@24219
   214
        fun decode ~1 _ = NONE
haftmann@24219
   215
          | decode _ ~1 = NONE
haftmann@24219
   216
          | decode n m = SOME (chr (n * 16 + m));
haftmann@24219
   217
      in decode (idx c1) (idx c2) end
haftmann@24219
   218
  | decode_char _ _ = NONE;
haftmann@24219
   219
haftmann@24219
   220
fun implode_string c_char c_nibbles mk_char mk_string ts =
haftmann@24219
   221
  let
haftmann@24219
   222
    fun implode_char (IConst (c, _) `$ t1 `$ t2) =
haftmann@24219
   223
          if c = c_char then decode_char c_nibbles (t1, t2) else NONE
haftmann@24219
   224
      | implode_char _ = NONE;
haftmann@24219
   225
    val ts' = map implode_char ts;
haftmann@24219
   226
  in if forall is_some ts'
haftmann@24219
   227
    then (SOME o str o mk_string o implode o map_filter I) ts'
haftmann@24219
   228
    else NONE
haftmann@24219
   229
  end;
haftmann@24219
   230
haftmann@24219
   231
fun implode_numeral c_bit0 c_bit1 c_pls c_min c_bit =
haftmann@24219
   232
  let
haftmann@24219
   233
    fun dest_bit (IConst (c, _)) = if c = c_bit0 then SOME 0
haftmann@24219
   234
          else if c = c_bit1 then SOME 1
haftmann@24219
   235
          else NONE
haftmann@24219
   236
      | dest_bit _ = NONE;
haftmann@24219
   237
    fun dest_numeral (IConst (c, _)) = if c = c_pls then SOME (IntInf.fromInt 0)
haftmann@24219
   238
          else if c = c_min then SOME (IntInf.fromInt ~1)
haftmann@24219
   239
          else NONE
haftmann@24219
   240
      | dest_numeral (IConst (c, _) `$ t1 `$ t2) =
haftmann@24219
   241
          if c = c_bit then case (dest_numeral t1, dest_bit t2)
haftmann@24219
   242
           of (SOME n, SOME b) => SOME (IntInf.fromInt 2 * n + IntInf.fromInt b)
haftmann@24219
   243
            | _ => NONE
haftmann@24219
   244
          else NONE
haftmann@24219
   245
      | dest_numeral _ = NONE;
haftmann@24219
   246
  in dest_numeral end;
haftmann@24219
   247
haftmann@24219
   248
fun implode_monad c_mbind c_kbind t =
haftmann@24219
   249
  let
haftmann@24219
   250
    fun dest_monad (IConst (c, _) `$ t1 `$ t2) =
haftmann@24219
   251
          if c = c_mbind
haftmann@24219
   252
            then case CodeThingol.split_abs t2
haftmann@24219
   253
             of SOME (((v, pat), ty), t') => SOME ((SOME (((SOME v, pat), ty), true), t1), t')
haftmann@24219
   254
              | NONE => NONE
haftmann@24219
   255
          else if c = c_kbind
haftmann@24219
   256
            then SOME ((NONE, t1), t2)
haftmann@24219
   257
            else NONE
haftmann@24219
   258
      | dest_monad t = case CodeThingol.split_let t
haftmann@24219
   259
           of SOME (((pat, ty), tbind), t') => SOME ((SOME (((NONE, SOME pat), ty), false), tbind), t')
haftmann@24219
   260
            | NONE => NONE;
haftmann@24219
   261
  in CodeThingol.unfoldr dest_monad t end;
haftmann@24219
   262
haftmann@24219
   263
haftmann@24219
   264
(** name auxiliary **)
haftmann@24219
   265
haftmann@24219
   266
val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
haftmann@24219
   267
val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
haftmann@24219
   268
haftmann@24219
   269
val dest_name =
haftmann@24219
   270
  apfst NameSpace.implode o split_last o fst o split_last o NameSpace.explode;
haftmann@24219
   271
haftmann@24219
   272
fun mk_modl_name_tab init_names prefix module_alias code =
haftmann@24219
   273
  let
haftmann@24219
   274
    fun nsp_map f = NameSpace.explode #> map f #> NameSpace.implode;
haftmann@24219
   275
    fun mk_alias name =
haftmann@24219
   276
     case module_alias name
haftmann@24219
   277
      of SOME name' => name'
haftmann@24219
   278
       | NONE => nsp_map (fn name => (the_single o fst)
haftmann@24219
   279
            (Name.variants [name] init_names)) name;
haftmann@24219
   280
    fun mk_prefix name =
haftmann@24219
   281
      case prefix
haftmann@24219
   282
       of SOME prefix => NameSpace.append prefix name
haftmann@24219
   283
        | NONE => name;
haftmann@24219
   284
    val tab =
haftmann@24219
   285
      Symtab.empty
haftmann@24219
   286
      |> Graph.fold ((fn name => Symtab.default (name, (mk_alias #> mk_prefix) name))
haftmann@24219
   287
           o fst o dest_name o fst)
haftmann@24219
   288
             code
haftmann@24219
   289
  in fn name => (the o Symtab.lookup tab) name end;
haftmann@24219
   290
haftmann@24219
   291
haftmann@24219
   292
haftmann@24219
   293
(** SML/OCaml serializer **)
haftmann@24219
   294
haftmann@24219
   295
datatype ml_def =
haftmann@24219
   296
    MLFuns of (string * ((iterm list * iterm) list * typscheme)) list
haftmann@24219
   297
  | MLDatas of (string * ((vname * sort) list * (string * itype list) list)) list
haftmann@24219
   298
  | MLClass of string * ((class * string) list * (vname * (string * itype) list))
haftmann@24219
   299
  | MLClassinst of string * ((class * (string * (vname * sort) list))
haftmann@24219
   300
        * ((class * (string * (string * dict list list))) list
haftmann@24219
   301
      * (string * iterm) list));
haftmann@24219
   302
haftmann@24219
   303
fun pr_sml tyco_syntax const_syntax labelled_name init_syms deresolv is_cons ml_def =
haftmann@24219
   304
  let
haftmann@24219
   305
    val pr_label_classrel = translate_string (fn "." => "__" | c => c) o NameSpace.qualifier;
haftmann@24219
   306
    val pr_label_classop = NameSpace.base o NameSpace.qualifier;
haftmann@24219
   307
    fun pr_dicts fxy ds =
haftmann@24219
   308
      let
haftmann@24219
   309
        fun pr_dictvar (v, (_, 1)) = first_upper v ^ "_"
haftmann@24219
   310
          | pr_dictvar (v, (i, _)) = first_upper v ^ string_of_int (i+1) ^ "_";
haftmann@24219
   311
        fun pr_proj [] p =
haftmann@24219
   312
              p
haftmann@24219
   313
          | pr_proj [p'] p =
haftmann@24219
   314
              brackets [p', p]
haftmann@24219
   315
          | pr_proj (ps as _ :: _) p =
haftmann@24219
   316
              brackets [Pretty.enum " o" "(" ")" ps, p];
haftmann@24219
   317
        fun pr_dictc fxy (DictConst (inst, dss)) =
haftmann@24219
   318
              brackify fxy ((str o deresolv) inst :: map (pr_dicts BR) dss)
haftmann@24219
   319
          | pr_dictc fxy (DictVar (classrels, v)) =
haftmann@24219
   320
              pr_proj (map (str o deresolv) classrels) ((str o pr_dictvar) v)
haftmann@24219
   321
      in case ds
haftmann@24219
   322
       of [] => str "()"
haftmann@24219
   323
        | [d] => pr_dictc fxy d
haftmann@24219
   324
        | _ :: _ => (Pretty.list "(" ")" o map (pr_dictc NOBR)) ds
haftmann@24219
   325
      end;
haftmann@24219
   326
    fun pr_tyvars vs =
haftmann@24219
   327
      vs
haftmann@24219
   328
      |> map (fn (v, sort) => map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort)
haftmann@24219
   329
      |> map (pr_dicts BR);
haftmann@24219
   330
    fun pr_tycoexpr fxy (tyco, tys) =
haftmann@24219
   331
      let
haftmann@24219
   332
        val tyco' = (str o deresolv) tyco
haftmann@24219
   333
      in case map (pr_typ BR) tys
haftmann@24219
   334
       of [] => tyco'
haftmann@24219
   335
        | [p] => Pretty.block [p, Pretty.brk 1, tyco']
haftmann@24219
   336
        | (ps as _::_) => Pretty.block [Pretty.list "(" ")" ps, Pretty.brk 1, tyco']
haftmann@24219
   337
      end
haftmann@24219
   338
    and pr_typ fxy (tyco `%% tys) =
haftmann@24219
   339
          (case tyco_syntax tyco
haftmann@24219
   340
           of NONE => pr_tycoexpr fxy (tyco, tys)
haftmann@24219
   341
            | SOME (i, pr) =>
haftmann@24219
   342
                if not (i = length tys)
haftmann@24219
   343
                then error ("Number of argument mismatch in customary serialization: "
haftmann@24219
   344
                  ^ (string_of_int o length) tys ^ " given, "
haftmann@24219
   345
                  ^ string_of_int i ^ " expected")
haftmann@24219
   346
                else pr pr_typ fxy tys)
haftmann@24219
   347
      | pr_typ fxy (ITyVar v) =
haftmann@24219
   348
          str ("'" ^ v);
haftmann@24219
   349
    fun pr_term lhs vars fxy (IConst c) =
haftmann@24219
   350
          pr_app lhs vars fxy (c, [])
haftmann@24219
   351
      | pr_term lhs vars fxy (IVar v) =
haftmann@24219
   352
          str (CodeName.lookup_var vars v)
haftmann@24219
   353
      | pr_term lhs vars fxy (t as t1 `$ t2) =
haftmann@24219
   354
          (case CodeThingol.unfold_const_app t
haftmann@24219
   355
           of SOME c_ts => pr_app lhs vars fxy c_ts
haftmann@24219
   356
            | NONE =>
haftmann@24219
   357
                brackify fxy [pr_term lhs vars NOBR t1, pr_term lhs vars BR t2])
haftmann@24219
   358
      | pr_term lhs vars fxy (t as _ `|-> _) =
haftmann@24219
   359
          let
haftmann@24219
   360
            val (binds, t') = CodeThingol.unfold_abs t;
haftmann@24219
   361
            fun pr ((v, pat), ty) =
haftmann@24219
   362
              pr_bind NOBR ((SOME v, pat), ty)
haftmann@24219
   363
              #>> (fn p => concat [str "fn", p, str "=>"]);
haftmann@24219
   364
            val (ps, vars') = fold_map pr binds vars;
haftmann@24219
   365
          in brackets (ps @ [pr_term lhs vars' NOBR t']) end
haftmann@24219
   366
      | pr_term lhs vars fxy (ICase (cases as (_, t0))) = (case CodeThingol.unfold_const_app t0
haftmann@24219
   367
           of SOME (c_ts as ((c, _), _)) => if is_none (const_syntax c)
haftmann@24219
   368
                then pr_case vars fxy cases
haftmann@24219
   369
                else pr_app lhs vars fxy c_ts
haftmann@24219
   370
            | NONE => pr_case vars fxy cases)
haftmann@24219
   371
    and pr_app' lhs vars (app as ((c, (iss, tys)), ts)) =
haftmann@24219
   372
      if is_cons c then let
haftmann@24219
   373
        val k = length tys
haftmann@24219
   374
      in if k < 2 then 
haftmann@24219
   375
        (str o deresolv) c :: map (pr_term lhs vars BR) ts
haftmann@24219
   376
      else if k = length ts then
haftmann@24219
   377
        [(str o deresolv) c, Pretty.enum "," "(" ")" (map (pr_term lhs vars NOBR) ts)]
haftmann@24219
   378
      else [pr_term lhs vars BR (CodeThingol.eta_expand app k)] end else
haftmann@24219
   379
        (str o deresolv) c
haftmann@24219
   380
          :: (map (pr_dicts BR) o filter_out null) iss @ map (pr_term lhs vars BR) ts
haftmann@24219
   381
    and pr_app lhs vars = gen_pr_app pr_app' pr_term const_syntax labelled_name is_cons lhs vars
haftmann@24219
   382
    and pr_bind' ((NONE, NONE), _) = str "_"
haftmann@24219
   383
      | pr_bind' ((SOME v, NONE), _) = str v
haftmann@24219
   384
      | pr_bind' ((NONE, SOME p), _) = p
haftmann@24219
   385
      | pr_bind' ((SOME v, SOME p), _) = concat [str v, str "as", p]
haftmann@24219
   386
    and pr_bind fxy = gen_pr_bind pr_bind' (pr_term false) fxy
haftmann@24219
   387
    and pr_case vars fxy (cases as ((_, [_]), _)) =
haftmann@24219
   388
          let
haftmann@24219
   389
            val (binds, t') = CodeThingol.unfold_let (ICase cases);
haftmann@24219
   390
            fun pr ((pat, ty), t) vars =
haftmann@24219
   391
              vars
haftmann@24219
   392
              |> pr_bind NOBR ((NONE, SOME pat), ty)
haftmann@24219
   393
              |>> (fn p => semicolon [str "val", p, str "=", pr_term false vars NOBR t])
haftmann@24219
   394
            val (ps, vars') = fold_map pr binds vars;
haftmann@24219
   395
          in
haftmann@24219
   396
            Pretty.chunks [
haftmann@24219
   397
              [str ("let"), Pretty.fbrk, Pretty.chunks ps] |> Pretty.block,
haftmann@24219
   398
              [str ("in"), Pretty.fbrk, pr_term false vars' NOBR t'] |> Pretty.block,
haftmann@24219
   399
              str ("end")
haftmann@24219
   400
            ]
haftmann@24219
   401
          end
haftmann@24219
   402
      | pr_case vars fxy (((td, ty), b::bs), _) =
haftmann@24219
   403
          let
haftmann@24219
   404
            fun pr delim (pat, t) =
haftmann@24219
   405
              let
haftmann@24219
   406
                val (p, vars') = pr_bind NOBR ((NONE, SOME pat), ty) vars;
haftmann@24219
   407
              in
haftmann@24219
   408
                concat [str delim, p, str "=>", pr_term false vars' NOBR t]
haftmann@24219
   409
              end;
haftmann@24219
   410
          in
haftmann@24219
   411
            (Pretty.enclose "(" ")" o single o brackify fxy) (
haftmann@24219
   412
              str "case"
haftmann@24219
   413
              :: pr_term false vars NOBR td
haftmann@24219
   414
              :: pr "of" b
haftmann@24219
   415
              :: map (pr "|") bs
haftmann@24219
   416
            )
haftmann@24219
   417
          end
haftmann@24219
   418
      | pr_case vars fxy ((_, []), _) = str "raise Fail \"empty case\""
haftmann@24219
   419
    fun pr_def (MLFuns (funns as (funn :: funns'))) =
haftmann@24219
   420
          let
haftmann@24219
   421
            val definer =
haftmann@24219
   422
              let
haftmann@24219
   423
                fun mk [] [] = "val"
haftmann@24219
   424
                  | mk (_::_) _ = "fun"
haftmann@24219
   425
                  | mk [] vs = if (null o filter_out (null o snd)) vs then "val" else "fun";
haftmann@24219
   426
                fun chk (_, ((ts, _) :: _, (vs, _))) NONE = SOME (mk ts vs)
haftmann@24219
   427
                  | chk (_, ((ts, _) :: _, (vs, _))) (SOME defi) =
haftmann@24219
   428
                      if defi = mk ts vs then SOME defi
haftmann@24219
   429
                      else error ("Mixing simultaneous vals and funs not implemented: "
haftmann@24219
   430
                        ^ commas (map (labelled_name o fst) funns));
haftmann@24219
   431
              in the (fold chk funns NONE) end;
haftmann@24219
   432
            fun pr_funn definer (name, (eqs as eq::eqs', (raw_vs, ty))) =
haftmann@24219
   433
              let
haftmann@24219
   434
                val vs = filter_out (null o snd) raw_vs;
haftmann@24219
   435
                val shift = if null eqs' then I else
haftmann@24219
   436
                  map (Pretty.block o single o Pretty.block o single);
haftmann@24219
   437
                fun pr_eq definer (ts, t) =
haftmann@24219
   438
                  let
haftmann@24219
   439
                    val consts = map_filter
haftmann@24219
   440
                      (fn c => if (is_some o const_syntax) c
haftmann@24219
   441
                        then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
   442
                        ((fold o CodeThingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@24219
   443
                    val vars = init_syms
haftmann@24219
   444
                      |> CodeName.intro_vars consts
haftmann@24219
   445
                      |> CodeName.intro_vars ((fold o CodeThingol.fold_unbound_varnames)
haftmann@24219
   446
                           (insert (op =)) ts []);
haftmann@24219
   447
                  in
haftmann@24219
   448
                    concat (
haftmann@24219
   449
                      [str definer, (str o deresolv) name]
haftmann@24219
   450
                      @ (if null ts andalso null vs
haftmann@24219
   451
                           andalso not (ty = ITyVar "_")(*for evaluation*)
haftmann@24219
   452
                         then [str ":", pr_typ NOBR ty]
haftmann@24219
   453
                         else
haftmann@24219
   454
                           pr_tyvars vs
haftmann@24219
   455
                           @ map (pr_term true vars BR) ts)
haftmann@24219
   456
                   @ [str "=", pr_term false vars NOBR t]
haftmann@24219
   457
                    )
haftmann@24219
   458
                  end
haftmann@24219
   459
              in
haftmann@24219
   460
                (Pretty.block o Pretty.fbreaks o shift) (
haftmann@24219
   461
                  pr_eq definer eq
haftmann@24219
   462
                  :: map (pr_eq "|") eqs'
haftmann@24219
   463
                )
haftmann@24219
   464
              end;
haftmann@24219
   465
            val (ps, p) = split_last (pr_funn definer funn :: map (pr_funn "and") funns');
haftmann@24219
   466
          in Pretty.chunks (ps @ [Pretty.block ([p, str ";"])]) end
haftmann@24219
   467
     | pr_def (MLDatas (datas as (data :: datas'))) =
haftmann@24219
   468
          let
haftmann@24219
   469
            fun pr_co (co, []) =
haftmann@24219
   470
                  str (deresolv co)
haftmann@24219
   471
              | pr_co (co, tys) =
haftmann@24219
   472
                  concat [
haftmann@24219
   473
                    str (deresolv co),
haftmann@24219
   474
                    str "of",
haftmann@24219
   475
                    Pretty.enum " *" "" "" (map (pr_typ (INFX (2, X))) tys)
haftmann@24219
   476
                  ];
haftmann@24219
   477
            fun pr_data definer (tyco, (vs, [])) =
haftmann@24219
   478
                  concat (
haftmann@24219
   479
                    str definer
haftmann@24219
   480
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@24219
   481
                    :: str "="
haftmann@24219
   482
                    @@ str "EMPTY__" 
haftmann@24219
   483
                  )
haftmann@24219
   484
              | pr_data definer (tyco, (vs, cos)) =
haftmann@24219
   485
                  concat (
haftmann@24219
   486
                    str definer
haftmann@24219
   487
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@24219
   488
                    :: str "="
haftmann@24219
   489
                    :: separate (str "|") (map pr_co cos)
haftmann@24219
   490
                  );
haftmann@24219
   491
            val (ps, p) = split_last (pr_data "datatype" data :: map (pr_data "and") datas');
haftmann@24219
   492
          in Pretty.chunks (ps @ [Pretty.block ([p, str ";"])]) end
haftmann@24219
   493
     | pr_def (MLClass (class, (superclasses, (v, classops)))) =
haftmann@24219
   494
          let
haftmann@24219
   495
            val w = first_upper v ^ "_";
haftmann@24219
   496
            fun pr_superclass_field (class, classrel) =
haftmann@24219
   497
              (concat o map str) [
haftmann@24219
   498
                pr_label_classrel classrel, ":", "'" ^ v, deresolv class
haftmann@24219
   499
              ];
haftmann@24219
   500
            fun pr_classop_field (classop, ty) =
haftmann@24219
   501
              concat [
haftmann@24219
   502
                (str o pr_label_classop) classop, str ":", pr_typ NOBR ty
haftmann@24219
   503
              ];
haftmann@24219
   504
            fun pr_classop_proj (classop, _) =
haftmann@24219
   505
              semicolon [
haftmann@24219
   506
                str "fun",
haftmann@24219
   507
                (str o deresolv) classop,
haftmann@24219
   508
                Pretty.enclose "(" ")" [str (w ^ ":'" ^ v ^ " " ^ deresolv class)],
haftmann@24219
   509
                str "=",
haftmann@24219
   510
                str ("#" ^ pr_label_classop classop),
haftmann@24219
   511
                str w
haftmann@24219
   512
              ];
haftmann@24219
   513
            fun pr_superclass_proj (_, classrel) =
haftmann@24219
   514
              semicolon [
haftmann@24219
   515
                str "fun",
haftmann@24219
   516
                (str o deresolv) classrel,
haftmann@24219
   517
                Pretty.enclose "(" ")" [str (w ^ ":'" ^ v ^ " " ^ deresolv class)],
haftmann@24219
   518
                str "=",
haftmann@24219
   519
                str ("#" ^ pr_label_classrel classrel),
haftmann@24219
   520
                str w
haftmann@24219
   521
              ];
haftmann@24219
   522
          in
haftmann@24219
   523
            Pretty.chunks (
haftmann@24219
   524
              concat [
haftmann@24219
   525
                str ("type '" ^ v),
haftmann@24219
   526
                (str o deresolv) class,
haftmann@24219
   527
                str "=",
haftmann@24219
   528
                Pretty.enum "," "{" "};" (
haftmann@24219
   529
                  map pr_superclass_field superclasses @ map pr_classop_field classops
haftmann@24219
   530
                )
haftmann@24219
   531
              ]
haftmann@24219
   532
              :: map pr_superclass_proj superclasses
haftmann@24219
   533
              @ map pr_classop_proj classops
haftmann@24219
   534
            )
haftmann@24219
   535
          end
haftmann@24219
   536
     | pr_def (MLClassinst (inst, ((class, (tyco, arity)), (superarities, classop_defs)))) =
haftmann@24219
   537
          let
haftmann@24219
   538
            fun pr_superclass (_, (classrel, dss)) =
haftmann@24219
   539
              concat [
haftmann@24219
   540
                (str o pr_label_classrel) classrel,
haftmann@24219
   541
                str "=",
haftmann@24219
   542
                pr_dicts NOBR [DictConst dss]
haftmann@24219
   543
              ];
haftmann@24219
   544
            fun pr_classop (classop, t) =
haftmann@24219
   545
              let
haftmann@24219
   546
                val consts = map_filter
haftmann@24219
   547
                  (fn c => if (is_some o const_syntax) c
haftmann@24219
   548
                    then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
   549
                    (CodeThingol.fold_constnames (insert (op =)) t []);
haftmann@24219
   550
                val vars = CodeName.intro_vars consts init_syms;
haftmann@24219
   551
              in
haftmann@24219
   552
                concat [
haftmann@24219
   553
                  (str o pr_label_classop) classop,
haftmann@24219
   554
                  str "=",
haftmann@24219
   555
                  pr_term false vars NOBR t
haftmann@24219
   556
                ]
haftmann@24219
   557
              end;
haftmann@24219
   558
          in
haftmann@24219
   559
            semicolon ([
haftmann@24219
   560
              str (if null arity then "val" else "fun"),
haftmann@24219
   561
              (str o deresolv) inst ] @
haftmann@24219
   562
              pr_tyvars arity @ [
haftmann@24219
   563
              str "=",
haftmann@24219
   564
              Pretty.enum "," "{" "}" (map pr_superclass superarities @ map pr_classop classop_defs),
haftmann@24219
   565
              str ":",
haftmann@24219
   566
              pr_tycoexpr NOBR (class, [tyco `%% map (ITyVar o fst) arity])
haftmann@24219
   567
            ])
haftmann@24219
   568
          end;
haftmann@24219
   569
  in pr_def ml_def end;
haftmann@24219
   570
haftmann@24219
   571
fun pr_sml_modl name content =
haftmann@24219
   572
  Pretty.chunks ([
haftmann@24219
   573
    str ("structure " ^ name ^ " = "),
haftmann@24219
   574
    str "struct",
haftmann@24219
   575
    str ""
haftmann@24219
   576
  ] @ content @ [
haftmann@24219
   577
    str "",
haftmann@24219
   578
    str ("end; (*struct " ^ name ^ "*)")
haftmann@24219
   579
  ]);
haftmann@24219
   580
haftmann@24219
   581
fun pr_ocaml tyco_syntax const_syntax labelled_name init_syms deresolv is_cons ml_def =
haftmann@24219
   582
  let
haftmann@24219
   583
    fun pr_dicts fxy ds =
haftmann@24219
   584
      let
haftmann@24219
   585
        fun pr_dictvar (v, (_, 1)) = "_" ^ first_upper v
haftmann@24219
   586
          | pr_dictvar (v, (i, _)) = "_" ^ first_upper v ^ string_of_int (i+1);
haftmann@24219
   587
        fun pr_proj ps p =
haftmann@24219
   588
          fold_rev (fn p2 => fn p1 => Pretty.block [p1, str ".", str p2]) ps p
haftmann@24219
   589
        fun pr_dictc fxy (DictConst (inst, dss)) =
haftmann@24219
   590
              brackify fxy ((str o deresolv) inst :: map (pr_dicts BR) dss)
haftmann@24219
   591
          | pr_dictc fxy (DictVar (classrels, v)) =
haftmann@24219
   592
              pr_proj (map deresolv classrels) ((str o pr_dictvar) v)
haftmann@24219
   593
      in case ds
haftmann@24219
   594
       of [] => str "()"
haftmann@24219
   595
        | [d] => pr_dictc fxy d
haftmann@24219
   596
        | _ :: _ => (Pretty.list "(" ")" o map (pr_dictc NOBR)) ds
haftmann@24219
   597
      end;
haftmann@24219
   598
    fun pr_tyvars vs =
haftmann@24219
   599
      vs
haftmann@24219
   600
      |> map (fn (v, sort) => map_index (fn (i, _) => DictVar ([], (v, (i, length sort)))) sort)
haftmann@24219
   601
      |> map (pr_dicts BR);
haftmann@24219
   602
    fun pr_tycoexpr fxy (tyco, tys) =
haftmann@24219
   603
      let
haftmann@24219
   604
        val tyco' = (str o deresolv) tyco
haftmann@24219
   605
      in case map (pr_typ BR) tys
haftmann@24219
   606
       of [] => tyco'
haftmann@24219
   607
        | [p] => Pretty.block [p, Pretty.brk 1, tyco']
haftmann@24219
   608
        | (ps as _::_) => Pretty.block [Pretty.list "(" ")" ps, Pretty.brk 1, tyco']
haftmann@24219
   609
      end
haftmann@24219
   610
    and pr_typ fxy (tyco `%% tys) =
haftmann@24219
   611
          (case tyco_syntax tyco
haftmann@24219
   612
           of NONE => pr_tycoexpr fxy (tyco, tys)
haftmann@24219
   613
            | SOME (i, pr) =>
haftmann@24219
   614
                if not (i = length tys)
haftmann@24219
   615
                then error ("Number of argument mismatch in customary serialization: "
haftmann@24219
   616
                  ^ (string_of_int o length) tys ^ " given, "
haftmann@24219
   617
                  ^ string_of_int i ^ " expected")
haftmann@24219
   618
                else pr pr_typ fxy tys)
haftmann@24219
   619
      | pr_typ fxy (ITyVar v) =
haftmann@24219
   620
          str ("'" ^ v);
haftmann@24219
   621
    fun pr_term lhs vars fxy (IConst c) =
haftmann@24219
   622
          pr_app lhs vars fxy (c, [])
haftmann@24219
   623
      | pr_term lhs vars fxy (IVar v) =
haftmann@24219
   624
          str (CodeName.lookup_var vars v)
haftmann@24219
   625
      | pr_term lhs vars fxy (t as t1 `$ t2) =
haftmann@24219
   626
          (case CodeThingol.unfold_const_app t
haftmann@24219
   627
           of SOME c_ts => pr_app lhs vars fxy c_ts
haftmann@24219
   628
            | NONE =>
haftmann@24219
   629
                brackify fxy [pr_term lhs vars NOBR t1, pr_term lhs vars BR t2])
haftmann@24219
   630
      | pr_term lhs vars fxy (t as _ `|-> _) =
haftmann@24219
   631
          let
haftmann@24219
   632
            val (binds, t') = CodeThingol.unfold_abs t;
haftmann@24219
   633
            fun pr ((v, pat), ty) = pr_bind BR ((SOME v, pat), ty);
haftmann@24219
   634
            val (ps, vars') = fold_map pr binds vars;
haftmann@24219
   635
          in brackets (str "fun" :: ps @ str "->" @@ pr_term lhs vars' NOBR t') end
haftmann@24219
   636
      | pr_term lhs vars fxy (ICase (cases as (_, t0))) = (case CodeThingol.unfold_const_app t0
haftmann@24219
   637
           of SOME (c_ts as ((c, _), _)) => if is_none (const_syntax c)
haftmann@24219
   638
                then pr_case vars fxy cases
haftmann@24219
   639
                else pr_app lhs vars fxy c_ts
haftmann@24219
   640
            | NONE => pr_case vars fxy cases)
haftmann@24219
   641
    and pr_app' lhs vars (app as ((c, (iss, tys)), ts)) =
haftmann@24219
   642
      if is_cons c then
haftmann@24219
   643
        if length tys = length ts
haftmann@24219
   644
        then case ts
haftmann@24219
   645
         of [] => [(str o deresolv) c]
haftmann@24219
   646
          | [t] => [(str o deresolv) c, pr_term lhs vars BR t]
haftmann@24219
   647
          | _ => [(str o deresolv) c, Pretty.enum "," "(" ")" (map (pr_term lhs vars NOBR) ts)]
haftmann@24219
   648
        else [pr_term lhs vars BR (CodeThingol.eta_expand app (length tys))]
haftmann@24219
   649
      else (str o deresolv) c
haftmann@24219
   650
        :: ((map (pr_dicts BR) o filter_out null) iss @ map (pr_term lhs vars BR) ts)
haftmann@24219
   651
    and pr_app lhs vars = gen_pr_app pr_app' pr_term const_syntax labelled_name is_cons lhs vars
haftmann@24219
   652
    and pr_bind' ((NONE, NONE), _) = str "_"
haftmann@24219
   653
      | pr_bind' ((SOME v, NONE), _) = str v
haftmann@24219
   654
      | pr_bind' ((NONE, SOME p), _) = p
haftmann@24219
   655
      | pr_bind' ((SOME v, SOME p), _) = brackets [p, str "as", str v]
haftmann@24219
   656
    and pr_bind fxy = gen_pr_bind pr_bind' (pr_term false) fxy
haftmann@24219
   657
    and pr_case vars fxy (cases as ((_, [_]), _)) =
haftmann@24219
   658
          let
haftmann@24219
   659
            val (binds, t') = CodeThingol.unfold_let (ICase cases);
haftmann@24219
   660
            fun pr ((pat, ty), t) vars =
haftmann@24219
   661
              vars
haftmann@24219
   662
              |> pr_bind NOBR ((NONE, SOME pat), ty)
haftmann@24219
   663
              |>> (fn p => concat [str "let", p, str "=", pr_term false vars NOBR t, str "in"])
haftmann@24219
   664
            val (ps, vars') = fold_map pr binds vars;
haftmann@24219
   665
          in Pretty.chunks (ps @| pr_term false vars' NOBR t') end
haftmann@24219
   666
      | pr_case vars fxy (((td, ty), b::bs), _) =
haftmann@24219
   667
          let
haftmann@24219
   668
            fun pr delim (pat, t) =
haftmann@24219
   669
              let
haftmann@24219
   670
                val (p, vars') = pr_bind NOBR ((NONE, SOME pat), ty) vars;
haftmann@24219
   671
              in concat [str delim, p, str "->", pr_term false vars' NOBR t] end;
haftmann@24219
   672
          in
haftmann@24219
   673
            (Pretty.enclose "(" ")" o single o brackify fxy) (
haftmann@24219
   674
              str "match"
haftmann@24219
   675
              :: pr_term false vars NOBR td
haftmann@24219
   676
              :: pr "with" b
haftmann@24219
   677
              :: map (pr "|") bs
haftmann@24219
   678
            )
haftmann@24219
   679
          end
haftmann@24219
   680
      | pr_case vars fxy ((_, []), _) = str "failwith \"empty case\"";
haftmann@24219
   681
    fun pr_def (MLFuns (funns as funn :: funns')) =
haftmann@24219
   682
          let
haftmann@24219
   683
            fun fish_parm _ (w as SOME _) = w
haftmann@24219
   684
              | fish_parm (IVar v) NONE = SOME v
haftmann@24219
   685
              | fish_parm _ NONE = NONE;
haftmann@24219
   686
            fun fillup_parm _ (_, SOME v) = v
haftmann@24219
   687
              | fillup_parm x (i, NONE) = x ^ string_of_int i;
haftmann@24219
   688
            fun fish_parms vars eqs =
haftmann@24219
   689
              let
haftmann@24251
   690
                val fished1 = fold (map2 fish_parm) eqs (replicate (length (hd eqs)) NONE);
haftmann@24251
   691
                val x = Name.variant (map_filter I fished1) "x";
haftmann@24251
   692
                val fished2 = map_index (fillup_parm x) fished1;
haftmann@24251
   693
                val fished3 = fold_rev (fn x => fn xs => Name.variant xs x :: xs) fished2 [];
haftmann@24251
   694
                val vars' = CodeName.intro_vars fished3 vars;
haftmann@24251
   695
              in map (CodeName.lookup_var vars') fished3 end;
haftmann@24219
   696
            fun pr_eq (ts, t) =
haftmann@24219
   697
              let
haftmann@24219
   698
                val consts = map_filter
haftmann@24219
   699
                  (fn c => if (is_some o const_syntax) c
haftmann@24219
   700
                    then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
   701
                    ((fold o CodeThingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@24219
   702
                val vars = init_syms
haftmann@24219
   703
                  |> CodeName.intro_vars consts
haftmann@24219
   704
                  |> CodeName.intro_vars ((fold o CodeThingol.fold_unbound_varnames)
haftmann@24219
   705
                      (insert (op =)) ts []);
haftmann@24219
   706
              in concat [
haftmann@24219
   707
                (Pretty.block o Pretty.commas) (map (pr_term true vars NOBR) ts),
haftmann@24219
   708
                str "->",
haftmann@24219
   709
                pr_term false vars NOBR t
haftmann@24219
   710
              ] end;
haftmann@24219
   711
            fun pr_eqs [(ts, t)] =
haftmann@24219
   712
                  let
haftmann@24219
   713
                    val consts = map_filter
haftmann@24219
   714
                      (fn c => if (is_some o const_syntax) c
haftmann@24219
   715
                        then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
   716
                        ((fold o CodeThingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@24219
   717
                    val vars = init_syms
haftmann@24219
   718
                      |> CodeName.intro_vars consts
haftmann@24219
   719
                      |> CodeName.intro_vars ((fold o CodeThingol.fold_unbound_varnames)
haftmann@24219
   720
                          (insert (op =)) ts []);
haftmann@24219
   721
                  in
haftmann@24219
   722
                    concat (
haftmann@24219
   723
                      map (pr_term true vars BR) ts
haftmann@24219
   724
                      @ str "="
haftmann@24219
   725
                      @@ pr_term false vars NOBR t
haftmann@24219
   726
                    )
haftmann@24219
   727
                  end
haftmann@24219
   728
              | pr_eqs (eqs as (eq as ([_], _)) :: eqs') =
haftmann@24219
   729
                  Pretty.block (
haftmann@24219
   730
                    str "="
haftmann@24219
   731
                    :: Pretty.brk 1
haftmann@24219
   732
                    :: str "function"
haftmann@24219
   733
                    :: Pretty.brk 1
haftmann@24219
   734
                    :: pr_eq eq
haftmann@24219
   735
                    :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1] o single o pr_eq) eqs'
haftmann@24219
   736
                  )
haftmann@24219
   737
              | pr_eqs (eqs as eq :: eqs') =
haftmann@24219
   738
                  let
haftmann@24219
   739
                    val consts = map_filter
haftmann@24219
   740
                      (fn c => if (is_some o const_syntax) c
haftmann@24219
   741
                        then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
   742
                        ((fold o CodeThingol.fold_constnames) (insert (op =)) (map snd eqs) []);
haftmann@24219
   743
                    val vars = init_syms
haftmann@24219
   744
                      |> CodeName.intro_vars consts;
haftmann@24219
   745
                    val dummy_parms = (map str o fish_parms vars o map fst) eqs;
haftmann@24219
   746
                  in
haftmann@24219
   747
                    Pretty.block (
haftmann@24219
   748
                      Pretty.breaks dummy_parms
haftmann@24219
   749
                      @ Pretty.brk 1
haftmann@24219
   750
                      :: str "="
haftmann@24219
   751
                      :: Pretty.brk 1
haftmann@24219
   752
                      :: str "match"
haftmann@24219
   753
                      :: Pretty.brk 1
haftmann@24219
   754
                      :: (Pretty.block o Pretty.commas) dummy_parms
haftmann@24219
   755
                      :: Pretty.brk 1
haftmann@24219
   756
                      :: str "with"
haftmann@24219
   757
                      :: Pretty.brk 1
haftmann@24219
   758
                      :: pr_eq eq
haftmann@24219
   759
                      :: maps (append [Pretty.fbrk, str "|", Pretty.brk 1] o single o pr_eq) eqs'
haftmann@24219
   760
                    )
haftmann@24219
   761
                  end;
haftmann@24219
   762
            fun pr_funn definer (name, (eqs, (vs, ty))) =
haftmann@24219
   763
              concat (
haftmann@24219
   764
                str definer
haftmann@24219
   765
                :: (str o deresolv) name
haftmann@24219
   766
                :: pr_tyvars (filter_out (null o snd) vs)
haftmann@24219
   767
                @| pr_eqs eqs
haftmann@24219
   768
              );
haftmann@24219
   769
            val (ps, p) = split_last (pr_funn "let rec" funn :: map (pr_funn "and") funns');
haftmann@24219
   770
          in Pretty.chunks (ps @ [Pretty.block ([p, str ";;"])]) end
haftmann@24219
   771
     | pr_def (MLDatas (datas as (data :: datas'))) =
haftmann@24219
   772
          let
haftmann@24219
   773
            fun pr_co (co, []) =
haftmann@24219
   774
                  str (deresolv co)
haftmann@24219
   775
              | pr_co (co, tys) =
haftmann@24219
   776
                  concat [
haftmann@24219
   777
                    str (deresolv co),
haftmann@24219
   778
                    str "of",
haftmann@24219
   779
                    Pretty.enum " *" "" "" (map (pr_typ (INFX (2, X))) tys)
haftmann@24219
   780
                  ];
haftmann@24219
   781
            fun pr_data definer (tyco, (vs, [])) =
haftmann@24219
   782
                  concat (
haftmann@24219
   783
                    str definer
haftmann@24219
   784
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@24219
   785
                    :: str "="
haftmann@24219
   786
                    @@ str "EMPTY_"
haftmann@24219
   787
                  )
haftmann@24219
   788
              | pr_data definer (tyco, (vs, cos)) =
haftmann@24219
   789
                  concat (
haftmann@24219
   790
                    str definer
haftmann@24219
   791
                    :: pr_tycoexpr NOBR (tyco, map (ITyVar o fst) vs)
haftmann@24219
   792
                    :: str "="
haftmann@24219
   793
                    :: separate (str "|") (map pr_co cos)
haftmann@24219
   794
                  );
haftmann@24219
   795
            val (ps, p) = split_last (pr_data "type" data :: map (pr_data "and") datas');
haftmann@24219
   796
          in Pretty.chunks (ps @ [Pretty.block ([p, str ";;"])]) end
haftmann@24219
   797
     | pr_def (MLClass (class, (superclasses, (v, classops)))) =
haftmann@24219
   798
          let
haftmann@24219
   799
            val w = "_" ^ first_upper v;
haftmann@24219
   800
            fun pr_superclass_field (class, classrel) =
haftmann@24219
   801
              (concat o map str) [
haftmann@24219
   802
                deresolv classrel, ":", "'" ^ v, deresolv class
haftmann@24219
   803
              ];
haftmann@24219
   804
            fun pr_classop_field (classop, ty) =
haftmann@24219
   805
              concat [
haftmann@24219
   806
                (str o deresolv) classop, str ":", pr_typ NOBR ty
haftmann@24219
   807
              ];
haftmann@24219
   808
            fun pr_classop_proj (classop, _) =
haftmann@24219
   809
              concat [
haftmann@24219
   810
                str "let",
haftmann@24219
   811
                (str o deresolv) classop,
haftmann@24219
   812
                str w,
haftmann@24219
   813
                str "=",
haftmann@24219
   814
                str (w ^ "." ^ deresolv classop ^ ";;")
haftmann@24219
   815
              ];
haftmann@24219
   816
          in Pretty.chunks (
haftmann@24219
   817
            concat [
haftmann@24219
   818
              str ("type '" ^ v),
haftmann@24219
   819
              (str o deresolv) class,
haftmann@24219
   820
              str "=",
haftmann@24219
   821
              Pretty.enum ";" "{" "};;" (
haftmann@24219
   822
                map pr_superclass_field superclasses @ map pr_classop_field classops
haftmann@24219
   823
              )
haftmann@24219
   824
            ]
haftmann@24219
   825
            :: map pr_classop_proj classops
haftmann@24219
   826
          ) end
haftmann@24219
   827
     | pr_def (MLClassinst (inst, ((class, (tyco, arity)), (superarities, classop_defs)))) =
haftmann@24219
   828
          let
haftmann@24219
   829
            fun pr_superclass (_, (classrel, dss)) =
haftmann@24219
   830
              concat [
haftmann@24219
   831
                (str o deresolv) classrel,
haftmann@24219
   832
                str "=",
haftmann@24219
   833
                pr_dicts NOBR [DictConst dss]
haftmann@24219
   834
              ];
haftmann@24219
   835
            fun pr_classop_def (classop, t) =
haftmann@24219
   836
              let
haftmann@24219
   837
                val consts = map_filter
haftmann@24219
   838
                  (fn c => if (is_some o const_syntax) c
haftmann@24219
   839
                    then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
   840
                    (CodeThingol.fold_constnames (insert (op =)) t []);
haftmann@24219
   841
                val vars = CodeName.intro_vars consts init_syms;
haftmann@24219
   842
              in
haftmann@24219
   843
                concat [
haftmann@24219
   844
                  (str o deresolv) classop,
haftmann@24219
   845
                  str "=",
haftmann@24219
   846
                  pr_term false vars NOBR t
haftmann@24219
   847
                ]
haftmann@24219
   848
              end;
haftmann@24219
   849
          in
haftmann@24219
   850
            concat (
haftmann@24219
   851
              str "let"
haftmann@24219
   852
              :: (str o deresolv) inst
haftmann@24219
   853
              :: pr_tyvars arity
haftmann@24219
   854
              @ str "="
haftmann@24219
   855
              @@ (Pretty.enclose "(" ");;" o Pretty.breaks) [
haftmann@24219
   856
                Pretty.enum ";" "{" "}" (map pr_superclass superarities @ map pr_classop_def classop_defs),
haftmann@24219
   857
                str ":",
haftmann@24219
   858
                pr_tycoexpr NOBR (class, [tyco `%% map (ITyVar o fst) arity])
haftmann@24219
   859
              ]
haftmann@24219
   860
            )
haftmann@24219
   861
          end;
haftmann@24219
   862
  in pr_def ml_def end;
haftmann@24219
   863
haftmann@24219
   864
fun pr_ocaml_modl name content =
haftmann@24219
   865
  Pretty.chunks ([
haftmann@24219
   866
    str ("module " ^ name ^ " = "),
haftmann@24219
   867
    str "struct",
haftmann@24219
   868
    str ""
haftmann@24219
   869
  ] @ content @ [
haftmann@24219
   870
    str "",
haftmann@24219
   871
    str ("end;; (*struct " ^ name ^ "*)")
haftmann@24219
   872
  ]);
haftmann@24219
   873
haftmann@24219
   874
val code_width = ref 80;
haftmann@24219
   875
fun code_output p = Pretty.setmp_margin (!code_width) Pretty.output p ^ "\n";
haftmann@24219
   876
haftmann@24219
   877
fun seri_ml pr_def pr_modl module output labelled_name reserved_syms raw_module_alias module_prolog
haftmann@24219
   878
  (_ : string -> class_syntax option) tyco_syntax const_syntax code =
haftmann@24219
   879
  let
haftmann@24219
   880
    val module_alias = if is_some module then K module else raw_module_alias;
haftmann@24219
   881
    val is_cons = CodeThingol.is_cons code;
haftmann@24219
   882
    datatype node =
haftmann@24219
   883
        Def of string * ml_def option
haftmann@24219
   884
      | Module of string * ((Name.context * Name.context) * node Graph.T);
haftmann@24219
   885
    val init_names = Name.make_context reserved_syms;
haftmann@24219
   886
    val init_module = ((init_names, init_names), Graph.empty);
haftmann@24219
   887
    fun map_node [] f = f
haftmann@24219
   888
      | map_node (m::ms) f =
haftmann@24219
   889
          Graph.default_node (m, Module (m, init_module))
haftmann@24219
   890
          #> Graph.map_node m (fn (Module (dmodlname, (nsp, nodes))) => Module (dmodlname, (nsp, map_node ms f nodes)));
haftmann@24219
   891
    fun map_nsp_yield [] f (nsp, nodes) =
haftmann@24219
   892
          let
haftmann@24219
   893
            val (x, nsp') = f nsp
haftmann@24219
   894
          in (x, (nsp', nodes)) end
haftmann@24219
   895
      | map_nsp_yield (m::ms) f (nsp, nodes) =
haftmann@24219
   896
          let
haftmann@24219
   897
            val (x, nodes') =
haftmann@24219
   898
              nodes
haftmann@24219
   899
              |> Graph.default_node (m, Module (m, init_module))
haftmann@24219
   900
              |> Graph.map_node_yield m (fn Module (dmodlname, nsp_nodes) => 
haftmann@24219
   901
                  let
haftmann@24219
   902
                    val (x, nsp_nodes') = map_nsp_yield ms f nsp_nodes
haftmann@24219
   903
                  in (x, Module (dmodlname, nsp_nodes')) end)
haftmann@24219
   904
          in (x, (nsp, nodes')) end;
haftmann@24219
   905
    val init_syms = CodeName.make_vars reserved_syms;
haftmann@24219
   906
    val name_modl = mk_modl_name_tab init_names NONE module_alias code;
haftmann@24219
   907
    fun name_def upper name nsp =
haftmann@24219
   908
      let
haftmann@24219
   909
        val (_, base) = dest_name name;
haftmann@24219
   910
        val base' = if upper then first_upper base else base;
haftmann@24219
   911
        val ([base''], nsp') = Name.variants [base'] nsp;
haftmann@24219
   912
      in (base'', nsp') end;
haftmann@24219
   913
    fun map_nsp_fun f (nsp_fun, nsp_typ) =
haftmann@24219
   914
      let
haftmann@24219
   915
        val (x, nsp_fun') = f nsp_fun
haftmann@24219
   916
      in (x, (nsp_fun', nsp_typ)) end;
haftmann@24219
   917
    fun map_nsp_typ f (nsp_fun, nsp_typ) =
haftmann@24219
   918
      let
haftmann@24219
   919
        val (x, nsp_typ') = f nsp_typ
haftmann@24219
   920
      in (x, (nsp_fun, nsp_typ')) end;
haftmann@24219
   921
    fun mk_funs defs =
haftmann@24219
   922
      fold_map
haftmann@24219
   923
        (fn (name, CodeThingol.Fun info) =>
haftmann@24219
   924
              map_nsp_fun (name_def false name) >> (fn base => (base, (name, info)))
haftmann@24219
   925
          | (name, def) => error ("Function block containing illegal definition: " ^ labelled_name name)
haftmann@24219
   926
        ) defs
haftmann@24219
   927
      >> (split_list #> apsnd MLFuns);
haftmann@24219
   928
    fun mk_datatype defs =
haftmann@24219
   929
      fold_map
haftmann@24219
   930
        (fn (name, CodeThingol.Datatype info) =>
haftmann@24219
   931
              map_nsp_typ (name_def false name) >> (fn base => (base, SOME (name, info)))
haftmann@24219
   932
          | (name, CodeThingol.Datatypecons _) =>
haftmann@24219
   933
              map_nsp_fun (name_def true name) >> (fn base => (base, NONE))
haftmann@24219
   934
          | (name, def) => error ("Datatype block containing illegal definition: " ^ labelled_name name)
haftmann@24219
   935
        ) defs
haftmann@24219
   936
      >> (split_list #> apsnd (map_filter I
haftmann@24219
   937
        #> (fn [] => error ("Datatype block without data definition: " ^ (commas o map (labelled_name o fst)) defs)
haftmann@24219
   938
             | infos => MLDatas infos)));
haftmann@24219
   939
    fun mk_class defs =
haftmann@24219
   940
      fold_map
haftmann@24219
   941
        (fn (name, CodeThingol.Class info) =>
haftmann@24219
   942
              map_nsp_typ (name_def false name) >> (fn base => (base, SOME (name, info)))
haftmann@24219
   943
          | (name, CodeThingol.Classrel _) =>
haftmann@24219
   944
              map_nsp_fun (name_def false name) >> (fn base => (base, NONE))
haftmann@24219
   945
          | (name, CodeThingol.Classop _) =>
haftmann@24219
   946
              map_nsp_fun (name_def false name) >> (fn base => (base, NONE))
haftmann@24219
   947
          | (name, def) => error ("Class block containing illegal definition: " ^ labelled_name name)
haftmann@24219
   948
        ) defs
haftmann@24219
   949
      >> (split_list #> apsnd (map_filter I
haftmann@24219
   950
        #> (fn [] => error ("Class block without class definition: " ^ (commas o map (labelled_name o fst)) defs)
haftmann@24219
   951
             | [info] => MLClass info)));
haftmann@24219
   952
    fun mk_inst [(name, CodeThingol.Classinst info)] =
haftmann@24219
   953
      map_nsp_fun (name_def false name)
haftmann@24219
   954
      >> (fn base => ([base], MLClassinst (name, info)));
haftmann@24219
   955
    fun add_group mk defs nsp_nodes =
haftmann@24219
   956
      let
haftmann@24219
   957
        val names as (name :: names') = map fst defs;
haftmann@24219
   958
        val deps =
haftmann@24219
   959
          []
haftmann@24219
   960
          |> fold (fold (insert (op =)) o Graph.imm_succs code) names
haftmann@24219
   961
          |> subtract (op =) names;
haftmann@24219
   962
        val (modls, _) = (split_list o map dest_name) names;
haftmann@24219
   963
        val modl' = (the_single o distinct (op =) o map name_modl) modls
haftmann@24219
   964
          handle Empty =>
haftmann@24219
   965
            error ("Illegal mutual dependencies: " ^ commas (map labelled_name names));
haftmann@24219
   966
        val modl_explode = NameSpace.explode modl';
haftmann@24219
   967
        fun add_dep name name'' =
haftmann@24219
   968
          let
haftmann@24219
   969
            val modl'' = (name_modl o fst o dest_name) name'';
haftmann@24219
   970
          in if modl' = modl'' then
haftmann@24219
   971
            map_node modl_explode
haftmann@24219
   972
              (Graph.add_edge (name, name''))
haftmann@24219
   973
          else let
haftmann@24219
   974
            val (common, (diff1::_, diff2::_)) = chop_prefix (op =)
haftmann@24219
   975
              (modl_explode, NameSpace.explode modl'');
haftmann@24219
   976
          in
haftmann@24219
   977
            map_node common
haftmann@24219
   978
              (fn gr => Graph.add_edge_acyclic (diff1, diff2) gr
haftmann@24219
   979
                handle Graph.CYCLES _ => error ("Dependency "
haftmann@24219
   980
                  ^ quote name ^ " -> " ^ quote name''
haftmann@24219
   981
                  ^ " would result in module dependency cycle"))
haftmann@24219
   982
          end end;
haftmann@24219
   983
      in
haftmann@24219
   984
        nsp_nodes
haftmann@24219
   985
        |> map_nsp_yield modl_explode (mk defs)
haftmann@24219
   986
        |-> (fn (base' :: bases', def') =>
haftmann@24219
   987
           apsnd (map_node modl_explode (Graph.new_node (name, (Def (base', SOME def')))
haftmann@24219
   988
              #> fold2 (fn name' => fn base' => Graph.new_node (name', (Def (base', NONE)))) names' bases')))
haftmann@24219
   989
        |> apsnd (fold (fn name => fold (add_dep name) deps) names)
haftmann@24219
   990
        |> apsnd (fold (map_node modl_explode o Graph.add_edge) (product names names))
haftmann@24219
   991
      end;
haftmann@24219
   992
    fun group_defs [(_, CodeThingol.Bot)] =
haftmann@24219
   993
          I
haftmann@24219
   994
      | group_defs ((defs as (_, CodeThingol.Fun _)::_)) =
haftmann@24219
   995
          add_group mk_funs defs
haftmann@24219
   996
      | group_defs ((defs as (_, CodeThingol.Datatypecons _)::_)) =
haftmann@24219
   997
          add_group mk_datatype defs
haftmann@24219
   998
      | group_defs ((defs as (_, CodeThingol.Datatype _)::_)) =
haftmann@24219
   999
          add_group mk_datatype defs
haftmann@24219
  1000
      | group_defs ((defs as (_, CodeThingol.Class _)::_)) =
haftmann@24219
  1001
          add_group mk_class defs
haftmann@24219
  1002
      | group_defs ((defs as (_, CodeThingol.Classrel _)::_)) =
haftmann@24219
  1003
          add_group mk_class defs
haftmann@24219
  1004
      | group_defs ((defs as (_, CodeThingol.Classop _)::_)) =
haftmann@24219
  1005
          add_group mk_class defs
haftmann@24219
  1006
      | group_defs ((defs as [(_, CodeThingol.Classinst _)])) =
haftmann@24219
  1007
          add_group mk_inst defs
haftmann@24219
  1008
      | group_defs defs = error ("Illegal mutual dependencies: " ^
haftmann@24219
  1009
          (commas o map (labelled_name o fst)) defs)
haftmann@24219
  1010
    val (_, nodes) =
haftmann@24219
  1011
      init_module
haftmann@24219
  1012
      |> fold group_defs (map (AList.make (Graph.get_node code))
haftmann@24219
  1013
          (rev (Graph.strong_conn code)))
haftmann@24219
  1014
    fun deresolver prefix name = 
haftmann@24219
  1015
      let
haftmann@24219
  1016
        val modl = (fst o dest_name) name;
haftmann@24219
  1017
        val modl' = (NameSpace.explode o name_modl) modl;
haftmann@24219
  1018
        val (_, (_, remainder)) = chop_prefix (op =) (prefix, modl');
haftmann@24219
  1019
        val defname' =
haftmann@24219
  1020
          nodes
haftmann@24219
  1021
          |> fold (fn m => fn g => case Graph.get_node g m
haftmann@24219
  1022
              of Module (_, (_, g)) => g) modl'
haftmann@24219
  1023
          |> (fn g => case Graph.get_node g name of Def (defname, _) => defname);
haftmann@24219
  1024
      in
haftmann@24219
  1025
        NameSpace.implode (remainder @ [defname'])
haftmann@24219
  1026
      end handle Graph.UNDEF _ =>
haftmann@24219
  1027
        error ("Unknown definition name: " ^ labelled_name name);
haftmann@24219
  1028
    fun the_prolog modlname = case module_prolog modlname
haftmann@24219
  1029
     of NONE => []
haftmann@24219
  1030
      | SOME p => [p, str ""];
haftmann@24219
  1031
    fun pr_node prefix (Def (_, NONE)) =
haftmann@24219
  1032
          NONE
haftmann@24219
  1033
      | pr_node prefix (Def (_, SOME def)) =
haftmann@24219
  1034
          SOME (pr_def tyco_syntax const_syntax labelled_name init_syms
haftmann@24219
  1035
            (deresolver prefix) is_cons def)
haftmann@24219
  1036
      | pr_node prefix (Module (dmodlname, (_, nodes))) =
haftmann@24219
  1037
          SOME (pr_modl dmodlname (the_prolog (NameSpace.implode (prefix @ [dmodlname]))
haftmann@24219
  1038
            @ separate (str "") ((map_filter (pr_node (prefix @ [dmodlname]) o Graph.get_node nodes)
haftmann@24219
  1039
                o rev o flat o Graph.strong_conn) nodes)));
haftmann@24219
  1040
    val p = Pretty.chunks (the_prolog "" @ separate (str "") ((map_filter
haftmann@24219
  1041
      (pr_node [] o Graph.get_node nodes) o rev o flat o Graph.strong_conn) nodes))
haftmann@24219
  1042
  in output p end;
haftmann@24219
  1043
haftmann@24219
  1044
val eval_verbose = ref false;
haftmann@24219
  1045
haftmann@24219
  1046
fun isar_seri_sml module file =
haftmann@24219
  1047
  let
haftmann@24219
  1048
    val output = case file
haftmann@24219
  1049
     of NONE => use_text "generated code" Output.ml_output (!eval_verbose) o code_output
haftmann@24219
  1050
      | SOME "-" => writeln o code_output
haftmann@24219
  1051
      | SOME file => File.write (Path.explode file) o code_output;
haftmann@24219
  1052
  in
haftmann@24219
  1053
    parse_args (Scan.succeed ())
haftmann@24219
  1054
    #> (fn () => seri_ml pr_sml pr_sml_modl module output)
haftmann@24219
  1055
  end;
haftmann@24219
  1056
haftmann@24219
  1057
fun isar_seri_ocaml module file =
haftmann@24219
  1058
  let
haftmann@24219
  1059
    val output = case file
haftmann@24219
  1060
     of NONE => error "OCaml: no internal compilation"
haftmann@24219
  1061
      | SOME "-" => writeln o code_output
haftmann@24219
  1062
      | SOME file => File.write (Path.explode file) o code_output;
haftmann@24219
  1063
    fun output_file file = File.write (Path.explode file) o code_output;
haftmann@24219
  1064
    val output_diag = writeln o code_output;
haftmann@24219
  1065
  in
haftmann@24219
  1066
    parse_args (Scan.succeed ())
haftmann@24219
  1067
    #> (fn () => seri_ml pr_ocaml pr_ocaml_modl module output)
haftmann@24219
  1068
  end;
haftmann@24219
  1069
haftmann@24219
  1070
haftmann@24219
  1071
(** Haskell serializer **)
haftmann@24219
  1072
haftmann@24219
  1073
local
haftmann@24219
  1074
haftmann@24219
  1075
fun pr_bind' ((NONE, NONE), _) = str "_"
haftmann@24219
  1076
  | pr_bind' ((SOME v, NONE), _) = str v
haftmann@24219
  1077
  | pr_bind' ((NONE, SOME p), _) = p
haftmann@24219
  1078
  | pr_bind' ((SOME v, SOME p), _) = brackets [str v, str "@", p]
haftmann@24219
  1079
haftmann@24219
  1080
val pr_bind_haskell = gen_pr_bind pr_bind';
haftmann@24219
  1081
haftmann@24219
  1082
in
haftmann@24219
  1083
haftmann@24219
  1084
fun pr_haskell class_syntax tyco_syntax const_syntax labelled_name init_syms
haftmann@24219
  1085
    deresolv_here deresolv is_cons deriving_show def =
haftmann@24219
  1086
  let
haftmann@24219
  1087
    fun class_name class = case class_syntax class
haftmann@24219
  1088
     of NONE => deresolv class
haftmann@24219
  1089
      | SOME (class, _) => class;
haftmann@24219
  1090
    fun classop_name class classop = case class_syntax class
haftmann@24219
  1091
     of NONE => deresolv_here classop
haftmann@24219
  1092
      | SOME (_, classop_syntax) => case classop_syntax classop
haftmann@24219
  1093
         of NONE => (snd o dest_name) classop
haftmann@24219
  1094
          | SOME classop => classop
haftmann@24219
  1095
    fun pr_typparms tyvars vs =
haftmann@24219
  1096
      case maps (fn (v, sort) => map (pair v) sort) vs
haftmann@24219
  1097
       of [] => str ""
haftmann@24219
  1098
        | xs => Pretty.block [
haftmann@24219
  1099
            Pretty.enum "," "(" ")" (
haftmann@24219
  1100
              map (fn (v, class) => str
haftmann@24219
  1101
                (class_name class ^ " " ^ CodeName.lookup_var tyvars v)) xs
haftmann@24219
  1102
            ),
haftmann@24219
  1103
            str " => "
haftmann@24219
  1104
          ];
haftmann@24219
  1105
    fun pr_tycoexpr tyvars fxy (tyco, tys) =
haftmann@24219
  1106
      brackify fxy (str tyco :: map (pr_typ tyvars BR) tys)
haftmann@24219
  1107
    and pr_typ tyvars fxy (tycoexpr as tyco `%% tys) =
haftmann@24219
  1108
          (case tyco_syntax tyco
haftmann@24219
  1109
           of NONE =>
haftmann@24219
  1110
                pr_tycoexpr tyvars fxy (deresolv tyco, tys)
haftmann@24219
  1111
            | SOME (i, pr) =>
haftmann@24219
  1112
                if not (i = length tys)
haftmann@24219
  1113
                then error ("Number of argument mismatch in customary serialization: "
haftmann@24219
  1114
                  ^ (string_of_int o length) tys ^ " given, "
haftmann@24219
  1115
                  ^ string_of_int i ^ " expected")
haftmann@24219
  1116
                else pr (pr_typ tyvars) fxy tys)
haftmann@24219
  1117
      | pr_typ tyvars fxy (ITyVar v) =
haftmann@24219
  1118
          (str o CodeName.lookup_var tyvars) v;
haftmann@24219
  1119
    fun pr_typscheme_expr tyvars (vs, tycoexpr) =
haftmann@24219
  1120
      Pretty.block (pr_typparms tyvars vs @@ pr_tycoexpr tyvars NOBR tycoexpr);
haftmann@24219
  1121
    fun pr_typscheme tyvars (vs, ty) =
haftmann@24219
  1122
      Pretty.block (pr_typparms tyvars vs @@ pr_typ tyvars NOBR ty);
haftmann@24219
  1123
    fun pr_term lhs vars fxy (IConst c) =
haftmann@24219
  1124
          pr_app lhs vars fxy (c, [])
haftmann@24219
  1125
      | pr_term lhs vars fxy (t as (t1 `$ t2)) =
haftmann@24219
  1126
          (case CodeThingol.unfold_const_app t
haftmann@24219
  1127
           of SOME app => pr_app lhs vars fxy app
haftmann@24219
  1128
            | _ =>
haftmann@24219
  1129
                brackify fxy [
haftmann@24219
  1130
                  pr_term lhs vars NOBR t1,
haftmann@24219
  1131
                  pr_term lhs vars BR t2
haftmann@24219
  1132
                ])
haftmann@24219
  1133
      | pr_term lhs vars fxy (IVar v) =
haftmann@24219
  1134
          (str o CodeName.lookup_var vars) v
haftmann@24219
  1135
      | pr_term lhs vars fxy (t as _ `|-> _) =
haftmann@24219
  1136
          let
haftmann@24219
  1137
            val (binds, t') = CodeThingol.unfold_abs t;
haftmann@24219
  1138
            fun pr ((v, pat), ty) = pr_bind BR ((SOME v, pat), ty);
haftmann@24219
  1139
            val (ps, vars') = fold_map pr binds vars;
haftmann@24219
  1140
          in brackets (str "\\" :: ps @ str "->" @@ pr_term lhs vars' NOBR t') end
haftmann@24219
  1141
      | pr_term lhs vars fxy (ICase (cases as (_, t0))) = (case CodeThingol.unfold_const_app t0
haftmann@24219
  1142
           of SOME (c_ts as ((c, _), _)) => if is_none (const_syntax c)
haftmann@24219
  1143
                then pr_case vars fxy cases
haftmann@24219
  1144
                else pr_app lhs vars fxy c_ts
haftmann@24219
  1145
            | NONE => pr_case vars fxy cases)
haftmann@24219
  1146
    and pr_app' lhs vars ((c, _), ts) =
haftmann@24219
  1147
      (str o deresolv) c :: map (pr_term lhs vars BR) ts
haftmann@24219
  1148
    and pr_app lhs vars = gen_pr_app pr_app' pr_term const_syntax labelled_name is_cons lhs vars
haftmann@24219
  1149
    and pr_bind fxy = pr_bind_haskell (pr_term false) fxy
haftmann@24219
  1150
    and pr_case vars fxy (cases as ((_, [_]), _)) =
haftmann@24219
  1151
          let
haftmann@24219
  1152
            val (binds, t) = CodeThingol.unfold_let (ICase cases);
haftmann@24219
  1153
            fun pr ((pat, ty), t) vars =
haftmann@24219
  1154
              vars
haftmann@24219
  1155
              |> pr_bind BR ((NONE, SOME pat), ty)
haftmann@24219
  1156
              |>> (fn p => semicolon [p, str "=", pr_term false vars NOBR t])
haftmann@24219
  1157
            val (ps, vars') = fold_map pr binds vars;
haftmann@24219
  1158
          in
haftmann@24219
  1159
            Pretty.block_enclose (
haftmann@24219
  1160
              str "let {",
haftmann@24219
  1161
              concat [str "}", str "in", pr_term false vars' NOBR t]
haftmann@24219
  1162
            ) ps
haftmann@24219
  1163
          end
haftmann@24219
  1164
      | pr_case vars fxy (((td, ty), bs as _ :: _), _) =
haftmann@24219
  1165
          let
haftmann@24219
  1166
            fun pr (pat, t) =
haftmann@24219
  1167
              let
haftmann@24219
  1168
                val (p, vars') = pr_bind NOBR ((NONE, SOME pat), ty) vars;
haftmann@24219
  1169
              in semicolon [p, str "->", pr_term false vars' NOBR t] end;
haftmann@24219
  1170
          in
haftmann@24219
  1171
            Pretty.block_enclose (
haftmann@24219
  1172
              concat [str "(case", pr_term false vars NOBR td, str "of", str "{"],
haftmann@24219
  1173
              str "})"
haftmann@24219
  1174
            ) (map pr bs)
haftmann@24219
  1175
          end
haftmann@24219
  1176
      | pr_case vars fxy ((_, []), _) = str "error \"empty case\"";
haftmann@24219
  1177
    fun pr_def (name, CodeThingol.Fun (eqs, (vs, ty))) =
haftmann@24219
  1178
          let
haftmann@24219
  1179
            val tyvars = CodeName.intro_vars (map fst vs) init_syms;
haftmann@24219
  1180
            fun pr_eq (ts, t) =
haftmann@24219
  1181
              let
haftmann@24219
  1182
                val consts = map_filter
haftmann@24219
  1183
                  (fn c => if (is_some o const_syntax) c
haftmann@24219
  1184
                    then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
  1185
                    ((fold o CodeThingol.fold_constnames) (insert (op =)) (t :: ts) []);
haftmann@24219
  1186
                val vars = init_syms
haftmann@24219
  1187
                  |> CodeName.intro_vars consts
haftmann@24219
  1188
                  |> CodeName.intro_vars ((fold o CodeThingol.fold_unbound_varnames)
haftmann@24219
  1189
                       (insert (op =)) ts []);
haftmann@24219
  1190
              in
haftmann@24219
  1191
                semicolon (
haftmann@24219
  1192
                  (str o deresolv_here) name
haftmann@24219
  1193
                  :: map (pr_term true vars BR) ts
haftmann@24219
  1194
                  @ str "="
haftmann@24219
  1195
                  @@ pr_term false vars NOBR t
haftmann@24219
  1196
                )
haftmann@24219
  1197
              end;
haftmann@24219
  1198
          in
haftmann@24219
  1199
            Pretty.chunks (
haftmann@24219
  1200
              Pretty.block [
haftmann@24219
  1201
                (str o suffix " ::" o deresolv_here) name,
haftmann@24219
  1202
                Pretty.brk 1,
haftmann@24219
  1203
                pr_typscheme tyvars (vs, ty),
haftmann@24219
  1204
                str ";"
haftmann@24219
  1205
              ]
haftmann@24219
  1206
              :: map pr_eq eqs
haftmann@24219
  1207
            )
haftmann@24219
  1208
          end
haftmann@24219
  1209
      | pr_def (name, CodeThingol.Datatype (vs, [])) =
haftmann@24219
  1210
          let
haftmann@24219
  1211
            val tyvars = CodeName.intro_vars (map fst vs) init_syms;
haftmann@24219
  1212
          in
haftmann@24219
  1213
            semicolon [
haftmann@24219
  1214
              str "data",
haftmann@24219
  1215
              pr_typscheme_expr tyvars (vs, (deresolv_here name, map (ITyVar o fst) vs))
haftmann@24219
  1216
            ]
haftmann@24219
  1217
          end
haftmann@24219
  1218
      | pr_def (name, CodeThingol.Datatype (vs, [(co, [ty])])) =
haftmann@24219
  1219
          let
haftmann@24219
  1220
            val tyvars = CodeName.intro_vars (map fst vs) init_syms;
haftmann@24219
  1221
          in
haftmann@24219
  1222
            semicolon (
haftmann@24219
  1223
              str "newtype"
haftmann@24219
  1224
              :: pr_typscheme_expr tyvars (vs, (deresolv_here name, map (ITyVar o fst) vs))
haftmann@24219
  1225
              :: str "="
haftmann@24219
  1226
              :: (str o deresolv_here) co
haftmann@24219
  1227
              :: pr_typ tyvars BR ty
haftmann@24219
  1228
              :: (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@24219
  1229
            )
haftmann@24219
  1230
          end
haftmann@24219
  1231
      | pr_def (name, CodeThingol.Datatype (vs, co :: cos)) =
haftmann@24219
  1232
          let
haftmann@24219
  1233
            val tyvars = CodeName.intro_vars (map fst vs) init_syms;
haftmann@24219
  1234
            fun pr_co (co, tys) =
haftmann@24219
  1235
              concat (
haftmann@24219
  1236
                (str o deresolv_here) co
haftmann@24219
  1237
                :: map (pr_typ tyvars BR) tys
haftmann@24219
  1238
              )
haftmann@24219
  1239
          in
haftmann@24219
  1240
            semicolon (
haftmann@24219
  1241
              str "data"
haftmann@24219
  1242
              :: pr_typscheme_expr tyvars (vs, (deresolv_here name, map (ITyVar o fst) vs))
haftmann@24219
  1243
              :: str "="
haftmann@24219
  1244
              :: pr_co co
haftmann@24219
  1245
              :: map ((fn p => Pretty.block [str "| ", p]) o pr_co) cos
haftmann@24219
  1246
              @ (if deriving_show name then [str "deriving (Read, Show)"] else [])
haftmann@24219
  1247
            )
haftmann@24219
  1248
          end
haftmann@24219
  1249
      | pr_def (name, CodeThingol.Class (superclasss, (v, classops))) =
haftmann@24219
  1250
          let
haftmann@24219
  1251
            val tyvars = CodeName.intro_vars [v] init_syms;
haftmann@24219
  1252
            fun pr_classop (classop, ty) =
haftmann@24219
  1253
              semicolon [
haftmann@24219
  1254
                (str o classop_name name) classop,
haftmann@24219
  1255
                str "::",
haftmann@24219
  1256
                pr_typ tyvars NOBR ty
haftmann@24219
  1257
              ]
haftmann@24219
  1258
          in
haftmann@24219
  1259
            Pretty.block_enclose (
haftmann@24219
  1260
              Pretty.block [
haftmann@24219
  1261
                str "class ",
haftmann@24219
  1262
                pr_typparms tyvars [(v, map fst superclasss)],
haftmann@24219
  1263
                str (deresolv_here name ^ " " ^ CodeName.lookup_var tyvars v),
haftmann@24219
  1264
                str " where {"
haftmann@24219
  1265
              ],
haftmann@24219
  1266
              str "};"
haftmann@24219
  1267
            ) (map pr_classop classops)
haftmann@24219
  1268
          end
haftmann@24219
  1269
      | pr_def (_, CodeThingol.Classinst ((class, (tyco, vs)), (_, classop_defs))) =
haftmann@24219
  1270
          let
haftmann@24219
  1271
            val tyvars = CodeName.intro_vars (map fst vs) init_syms;
haftmann@24219
  1272
            fun pr_instdef (classop, t) =
haftmann@24219
  1273
                let
haftmann@24219
  1274
                  val consts = map_filter
haftmann@24219
  1275
                    (fn c => if (is_some o const_syntax) c
haftmann@24219
  1276
                      then NONE else (SOME o NameSpace.base o deresolv) c)
haftmann@24219
  1277
                      (CodeThingol.fold_constnames (insert (op =)) t []);
haftmann@24219
  1278
                  val vars = init_syms
haftmann@24219
  1279
                    |> CodeName.intro_vars consts;
haftmann@24219
  1280
                in
haftmann@24219
  1281
                  semicolon [
haftmann@24219
  1282
                    (str o classop_name class) classop,
haftmann@24219
  1283
                    str "=",
haftmann@24219
  1284
                    pr_term false vars NOBR t
haftmann@24219
  1285
                  ]
haftmann@24219
  1286
                end;
haftmann@24219
  1287
          in
haftmann@24219
  1288
            Pretty.block_enclose (
haftmann@24219
  1289
              Pretty.block [
haftmann@24219
  1290
                str "instance ",
haftmann@24219
  1291
                pr_typparms tyvars vs,
haftmann@24219
  1292
                str (class_name class ^ " "),
haftmann@24219
  1293
                pr_typ tyvars BR (tyco `%% map (ITyVar o fst) vs),
haftmann@24219
  1294
                str " where {"
haftmann@24219
  1295
              ],
haftmann@24219
  1296
              str "};"
haftmann@24219
  1297
            ) (map pr_instdef classop_defs)
haftmann@24219
  1298
          end;
haftmann@24219
  1299
  in pr_def def end;
haftmann@24219
  1300
haftmann@24219
  1301
fun pretty_haskell_monad c_mbind c_kbind =
haftmann@24219
  1302
  let
haftmann@24219
  1303
    fun pretty pr vars fxy [(t, _)] =
haftmann@24219
  1304
      let
haftmann@24219
  1305
        val pr_bind = pr_bind_haskell pr;
haftmann@24219
  1306
        fun pr_mbind (NONE, t) vars =
haftmann@24219
  1307
              (semicolon [pr vars NOBR t], vars)
haftmann@24219
  1308
          | pr_mbind (SOME (bind, true), t) vars = vars
haftmann@24219
  1309
              |> pr_bind NOBR bind
haftmann@24219
  1310
              |>> (fn p => semicolon [p, str "<-", pr vars NOBR t])
haftmann@24219
  1311
          | pr_mbind (SOME (bind, false), t) vars = vars
haftmann@24219
  1312
              |> pr_bind NOBR bind
haftmann@24219
  1313
              |>> (fn p => semicolon [str "let", p, str "=", pr vars NOBR t]);
haftmann@24219
  1314
        val (binds, t) = implode_monad c_mbind c_kbind t;
haftmann@24219
  1315
        val (ps, vars') = fold_map pr_mbind binds vars;
haftmann@24219
  1316
        fun brack p = if eval_fxy BR fxy then Pretty.block [str "(", p, str ")"] else p;
haftmann@24219
  1317
      in (brack o Pretty.block_enclose (str "do {", str "}")) (ps @| pr vars' NOBR t) end;
haftmann@24219
  1318
  in (1, pretty) end;
haftmann@24219
  1319
haftmann@24219
  1320
end; (*local*)
haftmann@24219
  1321
haftmann@24219
  1322
fun seri_haskell module_prefix module destination string_classes labelled_name
haftmann@24219
  1323
    reserved_syms raw_module_alias module_prolog class_syntax tyco_syntax const_syntax code =
haftmann@24219
  1324
  let
haftmann@24219
  1325
    val _ = Option.map File.check destination;
haftmann@24219
  1326
    val is_cons = CodeThingol.is_cons code;
haftmann@24219
  1327
    val module_alias = if is_some module then K module else raw_module_alias;
haftmann@24219
  1328
    val init_names = Name.make_context reserved_syms;
haftmann@24219
  1329
    val name_modl = mk_modl_name_tab init_names module_prefix module_alias code;
haftmann@24219
  1330
    fun add_def (name, (def, deps)) =
haftmann@24219
  1331
      let
haftmann@24219
  1332
        val (modl, base) = dest_name name;
haftmann@24219
  1333
        fun name_def base = Name.variants [base] #>> the_single;
haftmann@24219
  1334
        fun add_fun upper (nsp_fun, nsp_typ) =
haftmann@24219
  1335
          let
haftmann@24219
  1336
            val (base', nsp_fun') = name_def (if upper then first_upper base else base) nsp_fun
haftmann@24219
  1337
          in (base', (nsp_fun', nsp_typ)) end;
haftmann@24219
  1338
        fun add_typ (nsp_fun, nsp_typ) =
haftmann@24219
  1339
          let
haftmann@24219
  1340
            val (base', nsp_typ') = name_def (first_upper base) nsp_typ
haftmann@24219
  1341
          in (base', (nsp_fun, nsp_typ')) end;
haftmann@24219
  1342
        val add_name =
haftmann@24219
  1343
          case def
haftmann@24219
  1344
           of CodeThingol.Bot => pair base
haftmann@24219
  1345
            | CodeThingol.Fun _ => add_fun false
haftmann@24219
  1346
            | CodeThingol.Datatype _ => add_typ
haftmann@24219
  1347
            | CodeThingol.Datatypecons _ => add_fun true
haftmann@24219
  1348
            | CodeThingol.Class _ => add_typ
haftmann@24219
  1349
            | CodeThingol.Classrel _ => pair base
haftmann@24219
  1350
            | CodeThingol.Classop _ => add_fun false
haftmann@24219
  1351
            | CodeThingol.Classinst _ => pair base;
haftmann@24219
  1352
        val modlname' = name_modl modl;
haftmann@24219
  1353
        fun add_def base' =
haftmann@24219
  1354
          case def
haftmann@24219
  1355
           of CodeThingol.Bot => I
haftmann@24219
  1356
            | CodeThingol.Datatypecons _ =>
haftmann@24219
  1357
                cons (name, ((NameSpace.append modlname' base', base'), NONE))
haftmann@24219
  1358
            | CodeThingol.Classrel _ => I
haftmann@24219
  1359
            | CodeThingol.Classop _ =>
haftmann@24219
  1360
                cons (name, ((NameSpace.append modlname' base', base'), NONE))
haftmann@24219
  1361
            | _ => cons (name, ((NameSpace.append modlname' base', base'), SOME def));
haftmann@24219
  1362
      in
haftmann@24219
  1363
        Symtab.map_default (modlname', ([], ([], (init_names, init_names))))
haftmann@24219
  1364
              (apfst (fold (insert (op = : string * string -> bool)) deps))
haftmann@24219
  1365
        #> `(fn code => add_name ((snd o snd o the o Symtab.lookup code) modlname'))
haftmann@24219
  1366
        #-> (fn (base', names) =>
haftmann@24219
  1367
              (Symtab.map_entry modlname' o apsnd) (fn (defs, _) =>
haftmann@24219
  1368
              (add_def base' defs, names)))
haftmann@24219
  1369
      end;
haftmann@24219
  1370
    val code' =
haftmann@24219
  1371
      fold add_def (AList.make (fn name => (Graph.get_node code name, Graph.imm_succs code name))
haftmann@24219
  1372
        (Graph.strong_conn code |> flat)) Symtab.empty;
haftmann@24219
  1373
    val init_syms = CodeName.make_vars reserved_syms;
haftmann@24219
  1374
    fun deresolv name =
haftmann@24219
  1375
      (fst o fst o the o AList.lookup (op =) ((fst o snd o the
haftmann@24219
  1376
        o Symtab.lookup code') ((name_modl o fst o dest_name) name))) name
haftmann@24219
  1377
        handle Option => error ("Unknown definition name: " ^ labelled_name name);
haftmann@24219
  1378
    fun deresolv_here name =
haftmann@24219
  1379
      (snd o fst o the o AList.lookup (op =) ((fst o snd o the
haftmann@24219
  1380
        o Symtab.lookup code') ((name_modl o fst o dest_name) name))) name
haftmann@24219
  1381
        handle Option => error ("Unknown definition name: " ^ labelled_name name);
haftmann@24219
  1382
    fun deriving_show tyco =
haftmann@24219
  1383
      let
haftmann@24219
  1384
        fun deriv _ "fun" = false
haftmann@24219
  1385
          | deriv tycos tyco = member (op =) tycos tyco orelse
haftmann@24219
  1386
              case the_default CodeThingol.Bot (try (Graph.get_node code) tyco)
haftmann@24219
  1387
               of CodeThingol.Bot => true
haftmann@24219
  1388
                | CodeThingol.Datatype (_, cs) => forall (deriv' (tyco :: tycos))
haftmann@24219
  1389
                    (maps snd cs)
haftmann@24219
  1390
        and deriv' tycos (tyco `%% tys) = deriv tycos tyco
haftmann@24219
  1391
              andalso forall (deriv' tycos) tys
haftmann@24219
  1392
          | deriv' _ (ITyVar _) = true
haftmann@24219
  1393
      in deriv [] tyco end;
haftmann@24219
  1394
    fun seri_def qualified = pr_haskell class_syntax tyco_syntax const_syntax labelled_name init_syms
haftmann@24219
  1395
      deresolv_here (if qualified then deresolv else deresolv_here) is_cons
haftmann@24219
  1396
      (if string_classes then deriving_show else K false);
haftmann@24219
  1397
    fun write_module (SOME destination) modlname =
haftmann@24219
  1398
          let
haftmann@24219
  1399
            val filename = case modlname
haftmann@24219
  1400
             of "" => Path.explode "Main.hs"
haftmann@24219
  1401
              | _ => (Path.ext "hs" o Path.explode o implode o separate "/" o NameSpace.explode) modlname;
haftmann@24219
  1402
            val pathname = Path.append destination filename;
haftmann@24219
  1403
            val _ = File.mkdir (Path.dir pathname);
haftmann@24219
  1404
          in File.write pathname end
haftmann@24219
  1405
      | write_module NONE _ = writeln;
haftmann@24219
  1406
    fun seri_module (modlname', (imports, (defs, _))) =
haftmann@24219
  1407
      let
haftmann@24219
  1408
        val imports' =
haftmann@24219
  1409
          imports
haftmann@24219
  1410
          |> map (name_modl o fst o dest_name)
haftmann@24219
  1411
          |> distinct (op =)
haftmann@24219
  1412
          |> remove (op =) modlname';
haftmann@24219
  1413
        val qualified =
haftmann@24219
  1414
          imports
haftmann@24219
  1415
          |> map_filter (try deresolv)
haftmann@24219
  1416
          |> map NameSpace.base
haftmann@24219
  1417
          |> has_duplicates (op =);
haftmann@24219
  1418
        val mk_import = str o (if qualified
haftmann@24219
  1419
          then prefix "import qualified "
haftmann@24219
  1420
          else prefix "import ") o suffix ";";
haftmann@24219
  1421
      in
haftmann@24219
  1422
        Pretty.chunks (
haftmann@24219
  1423
          str ("module " ^ modlname' ^ " where {")
haftmann@24219
  1424
          :: str ""
haftmann@24219
  1425
          :: map mk_import imports'
haftmann@24219
  1426
          @ str ""
haftmann@24219
  1427
          :: separate (str "") ((case module_prolog modlname'
haftmann@24219
  1428
             of SOME prolog => [prolog]
haftmann@24219
  1429
              | NONE => [])
haftmann@24219
  1430
          @ map_filter
haftmann@24219
  1431
            (fn (name, (_, SOME def)) => SOME (seri_def qualified (name, def))
haftmann@24219
  1432
              | (_, (_, NONE)) => NONE) defs)
haftmann@24219
  1433
          @ str ""
haftmann@24219
  1434
          @@ str "}"
haftmann@24219
  1435
        )
haftmann@24219
  1436
        |> code_output
haftmann@24219
  1437
        |> write_module destination modlname'
haftmann@24219
  1438
      end;
haftmann@24219
  1439
  in Symtab.fold (fn modl => fn () => seri_module modl) code' () end;
haftmann@24219
  1440
haftmann@24219
  1441
fun isar_seri_haskell module file =
haftmann@24219
  1442
  let
haftmann@24219
  1443
    val destination = case file
haftmann@24219
  1444
     of NONE => error ("Haskell: no internal compilation")
haftmann@24219
  1445
      | SOME "-" => NONE
haftmann@24219
  1446
      | SOME file => SOME (Path.explode file)
haftmann@24219
  1447
  in
haftmann@24219
  1448
    parse_args (Scan.option (Args.$$$ "root" -- Args.colon |-- Args.name)
haftmann@24219
  1449
      -- Scan.optional (Args.$$$ "string_classes" >> K true) false
haftmann@24219
  1450
      >> (fn (module_prefix, string_classes) =>
haftmann@24219
  1451
        seri_haskell module_prefix module destination string_classes))
haftmann@24219
  1452
  end;
haftmann@24219
  1453
haftmann@24219
  1454
haftmann@24219
  1455
(** diagnosis serializer **)
haftmann@24219
  1456
haftmann@24219
  1457
fun seri_diagnosis labelled_name _ _ _ _ _ _ code =
haftmann@24219
  1458
  let
haftmann@24219
  1459
    val init_names = CodeName.make_vars [];
haftmann@24219
  1460
    fun pr_fun "fun" = SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@24219
  1461
          brackify_infix (1, R) fxy [
haftmann@24219
  1462
            pr_typ (INFX (1, X)) ty1,
haftmann@24219
  1463
            str "->",
haftmann@24219
  1464
            pr_typ (INFX (1, R)) ty2
haftmann@24219
  1465
          ])
haftmann@24219
  1466
      | pr_fun _ = NONE
haftmann@24219
  1467
    val pr = pr_haskell (K NONE) pr_fun (K NONE) labelled_name init_names I I (K false) (K false);
haftmann@24219
  1468
  in
haftmann@24219
  1469
    []
haftmann@24219
  1470
    |> Graph.fold (fn (name, (def, _)) => case try pr (name, def) of SOME p => cons p | NONE => I) code
haftmann@24219
  1471
    |> Pretty.chunks2
haftmann@24219
  1472
    |> code_output
haftmann@24219
  1473
    |> writeln
haftmann@24219
  1474
  end;
haftmann@24219
  1475
haftmann@24219
  1476
haftmann@24219
  1477
haftmann@24219
  1478
(** theory data **)
haftmann@24219
  1479
haftmann@24219
  1480
datatype syntax_expr = SyntaxExpr of {
haftmann@24219
  1481
  class: (string * (string -> string option)) Symtab.table,
haftmann@24219
  1482
  inst: unit Symtab.table,
haftmann@24219
  1483
  tyco: typ_syntax Symtab.table,
haftmann@24219
  1484
  const: term_syntax Symtab.table
haftmann@24219
  1485
};
haftmann@24219
  1486
haftmann@24219
  1487
fun mk_syntax_expr ((class, inst), (tyco, const)) =
haftmann@24219
  1488
  SyntaxExpr { class = class, inst = inst, tyco = tyco, const = const };
haftmann@24219
  1489
fun map_syntax_expr f (SyntaxExpr { class, inst, tyco, const }) =
haftmann@24219
  1490
  mk_syntax_expr (f ((class, inst), (tyco, const)));
haftmann@24219
  1491
fun merge_syntax_expr (SyntaxExpr { class = class1, inst = inst1, tyco = tyco1, const = const1 },
haftmann@24219
  1492
    SyntaxExpr { class = class2, inst = inst2, tyco = tyco2, const = const2 }) =
haftmann@24219
  1493
  mk_syntax_expr (
haftmann@24219
  1494
    (Symtab.join (K snd) (class1, class2),
haftmann@24219
  1495
       Symtab.join (K snd) (inst1, inst2)),
haftmann@24219
  1496
    (Symtab.join (K snd) (tyco1, tyco2),
haftmann@24219
  1497
       Symtab.join (K snd) (const1, const2))
haftmann@24219
  1498
  );
haftmann@24219
  1499
haftmann@24219
  1500
datatype syntax_modl = SyntaxModl of {
haftmann@24219
  1501
  alias: string Symtab.table,
haftmann@24219
  1502
  prolog: Pretty.T Symtab.table
haftmann@24219
  1503
};
haftmann@24219
  1504
haftmann@24219
  1505
fun mk_syntax_modl (alias, prolog) =
haftmann@24219
  1506
  SyntaxModl { alias = alias, prolog = prolog };
haftmann@24219
  1507
fun map_syntax_modl f (SyntaxModl { alias, prolog }) =
haftmann@24219
  1508
  mk_syntax_modl (f (alias, prolog));
haftmann@24219
  1509
fun merge_syntax_modl (SyntaxModl { alias = alias1, prolog = prolog1 },
haftmann@24219
  1510
    SyntaxModl { alias = alias2, prolog = prolog2 }) =
haftmann@24219
  1511
  mk_syntax_modl (
haftmann@24219
  1512
    Symtab.join (K snd) (alias1, alias2),
haftmann@24219
  1513
    Symtab.join (K snd) (prolog1, prolog2)
haftmann@24219
  1514
  );
haftmann@24219
  1515
haftmann@24219
  1516
type serializer =
haftmann@24219
  1517
  string option
haftmann@24219
  1518
  -> string option
haftmann@24219
  1519
  -> Args.T list
haftmann@24219
  1520
  -> (string -> string)
haftmann@24219
  1521
  -> string list
haftmann@24219
  1522
  -> (string -> string option)
haftmann@24219
  1523
  -> (string -> Pretty.T option)
haftmann@24219
  1524
  -> (string -> class_syntax option)
haftmann@24219
  1525
  -> (string -> typ_syntax option)
haftmann@24219
  1526
  -> (string -> term_syntax option)
haftmann@24219
  1527
  -> CodeThingol.code -> unit;
haftmann@24219
  1528
haftmann@24219
  1529
datatype target = Target of {
haftmann@24219
  1530
  serial: serial,
haftmann@24219
  1531
  serializer: serializer,
haftmann@24219
  1532
  syntax_expr: syntax_expr,
haftmann@24219
  1533
  syntax_modl: syntax_modl,
haftmann@24219
  1534
  reserved: string list
haftmann@24219
  1535
};
haftmann@24219
  1536
haftmann@24219
  1537
fun mk_target (serial, ((serializer, reserved), (syntax_expr, syntax_modl))) =
haftmann@24219
  1538
  Target { serial = serial, reserved = reserved, serializer = serializer, syntax_expr = syntax_expr, syntax_modl = syntax_modl };
haftmann@24219
  1539
fun map_target f ( Target { serial, serializer, reserved, syntax_expr, syntax_modl } ) =
haftmann@24219
  1540
  mk_target (f (serial, ((serializer, reserved), (syntax_expr, syntax_modl))));
haftmann@24219
  1541
fun merge_target target (Target { serial = serial1, serializer = serializer, reserved = reserved1,
haftmann@24219
  1542
  syntax_expr = syntax_expr1, syntax_modl = syntax_modl1 },
haftmann@24219
  1543
    Target { serial = serial2, serializer = _, reserved = reserved2,
haftmann@24219
  1544
      syntax_expr = syntax_expr2, syntax_modl = syntax_modl2 }) =
haftmann@24219
  1545
  if serial1 = serial2 then
haftmann@24219
  1546
    mk_target (serial1, ((serializer, merge (op =) (reserved1, reserved2)),
haftmann@24219
  1547
      (merge_syntax_expr (syntax_expr1, syntax_expr2),
haftmann@24219
  1548
        merge_syntax_modl (syntax_modl1, syntax_modl2))
haftmann@24219
  1549
    ))
haftmann@24219
  1550
  else
haftmann@24219
  1551
    error ("Incompatible serializers: " ^ quote target);
haftmann@24219
  1552
haftmann@24219
  1553
structure CodeTargetData = TheoryDataFun
haftmann@24219
  1554
(
haftmann@24219
  1555
  type T = target Symtab.table;
haftmann@24219
  1556
  val empty = Symtab.empty;
haftmann@24219
  1557
  val copy = I;
haftmann@24219
  1558
  val extend = I;
haftmann@24219
  1559
  fun merge _ = Symtab.join merge_target;
haftmann@24219
  1560
);
haftmann@24219
  1561
haftmann@24219
  1562
fun the_serializer (Target { serializer, ... }) = serializer;
haftmann@24219
  1563
fun the_reserved (Target { reserved, ... }) = reserved;
haftmann@24219
  1564
fun the_syntax_expr (Target { syntax_expr = SyntaxExpr x, ... }) = x;
haftmann@24219
  1565
fun the_syntax_modl (Target { syntax_modl = SyntaxModl x, ... }) = x;
haftmann@24219
  1566
haftmann@24219
  1567
fun assert_serializer thy target =
haftmann@24219
  1568
  case Symtab.lookup (CodeTargetData.get thy) target
haftmann@24219
  1569
   of SOME data => target
haftmann@24219
  1570
    | NONE => error ("Unknown code target language: " ^ quote target);
haftmann@24219
  1571
haftmann@24219
  1572
fun add_serializer (target, seri) thy =
haftmann@24219
  1573
  let
haftmann@24219
  1574
    val _ = case Symtab.lookup (CodeTargetData.get thy) target
haftmann@24219
  1575
     of SOME _ => warning ("overwriting existing serializer " ^ quote target)
haftmann@24219
  1576
      | NONE => ();
haftmann@24219
  1577
  in
haftmann@24219
  1578
    thy
haftmann@24219
  1579
    |> (CodeTargetData.map oo Symtab.map_default)
haftmann@24219
  1580
          (target, mk_target (serial (), ((seri, []),
haftmann@24219
  1581
            (mk_syntax_expr ((Symtab.empty, Symtab.empty), (Symtab.empty, Symtab.empty)),
haftmann@24219
  1582
              mk_syntax_modl (Symtab.empty, Symtab.empty)))))
haftmann@24219
  1583
          (map_target (fn (serial, ((_, keywords), syntax)) => (serial, ((seri, keywords), syntax))))
haftmann@24219
  1584
  end;
haftmann@24219
  1585
haftmann@24219
  1586
fun map_seri_data target f thy =
haftmann@24219
  1587
  let
haftmann@24219
  1588
    val _ = assert_serializer thy target;
haftmann@24219
  1589
  in
haftmann@24219
  1590
    thy
haftmann@24219
  1591
    |> (CodeTargetData.map o Symtab.map_entry target o map_target) f
haftmann@24219
  1592
  end;
haftmann@24219
  1593
haftmann@24219
  1594
val target_SML = "SML";
haftmann@24219
  1595
val target_OCaml = "OCaml";
haftmann@24219
  1596
val target_Haskell = "Haskell";
haftmann@24219
  1597
val target_diag = "diag";
haftmann@24219
  1598
haftmann@24219
  1599
fun get_serializer thy target permissive module file args labelled_name = fn cs =>
haftmann@24219
  1600
  let
haftmann@24219
  1601
    val data = case Symtab.lookup (CodeTargetData.get thy) target
haftmann@24219
  1602
     of SOME data => data
haftmann@24219
  1603
      | NONE => error ("Unknown code target language: " ^ quote target);
haftmann@24219
  1604
    val seri = the_serializer data;
haftmann@24219
  1605
    val reserved = the_reserved data;
haftmann@24219
  1606
    val { alias, prolog } = the_syntax_modl data;
haftmann@24219
  1607
    val { class, inst, tyco, const } = the_syntax_expr data;
haftmann@24219
  1608
    val project = if target = target_diag then I
haftmann@24219
  1609
      else CodeThingol.project_code permissive
haftmann@24219
  1610
        (Symtab.keys class @ Symtab.keys inst @ Symtab.keys tyco @ Symtab.keys const) cs;
haftmann@24219
  1611
    fun check_empty_funs code = case CodeThingol.empty_funs code
haftmann@24219
  1612
     of [] => code
haftmann@24219
  1613
      | names => error ("No defining equations for " ^ commas (map (labelled_name thy) names));
haftmann@24219
  1614
  in
haftmann@24219
  1615
    project
haftmann@24219
  1616
    #> check_empty_funs
haftmann@24219
  1617
    #> seri module file args (labelled_name thy) reserved (Symtab.lookup alias) (Symtab.lookup prolog)
haftmann@24219
  1618
      (Symtab.lookup class) (Symtab.lookup tyco) (Symtab.lookup const)
haftmann@24219
  1619
  end;
haftmann@24219
  1620
haftmann@24219
  1621
fun eval_term thy labelled_name code ((ref_name, reff), t) args =
haftmann@24219
  1622
  let
haftmann@24219
  1623
    val val_name = "Isabelle_Eval.EVAL.EVAL";
haftmann@24219
  1624
    val val_name' = "Isabelle_Eval.EVAL";
haftmann@24219
  1625
    val val_name'_args = space_implode " " (val_name' :: map (enclose "(" ")") args);
haftmann@24219
  1626
    val seri = get_serializer thy "SML" false (SOME "Isabelle_Eval") NONE [] labelled_name;
haftmann@24219
  1627
    fun eval code = (
haftmann@24219
  1628
      reff := NONE;
haftmann@24219
  1629
      seri (SOME [val_name]) code;
haftmann@24219
  1630
      use_text "generated code for evaluation" Output.ml_output (!eval_verbose)
haftmann@24219
  1631
        ("val _ = (" ^ ref_name ^ " := SOME (" ^ val_name'_args ^ "))");
haftmann@24219
  1632
      case !reff
haftmann@24219
  1633
       of NONE => error ("Could not retrieve value of ML reference " ^ quote ref_name
haftmann@24219
  1634
            ^ " (reference probably has been shadowed)")
haftmann@24219
  1635
        | SOME value => value
haftmann@24219
  1636
      );
haftmann@24219
  1637
  in
haftmann@24219
  1638
    code
haftmann@24219
  1639
    |> CodeThingol.add_eval_def (val_name, t)
haftmann@24219
  1640
    |> eval
haftmann@24219
  1641
  end;
haftmann@24219
  1642
haftmann@24219
  1643
haftmann@24219
  1644
haftmann@24219
  1645
(** optional pretty serialization **)
haftmann@24219
  1646
haftmann@24219
  1647
local
haftmann@24219
  1648
haftmann@24219
  1649
val pretty : (string * {
haftmann@24219
  1650
    pretty_char: string -> string,
haftmann@24219
  1651
    pretty_string: string -> string,
haftmann@24219
  1652
    pretty_numeral: bool -> IntInf.int -> string,
haftmann@24219
  1653
    pretty_list: Pretty.T list -> Pretty.T,
haftmann@24219
  1654
    infix_cons: int * string
haftmann@24219
  1655
  }) list = [
haftmann@24219
  1656
  ("SML", { pretty_char = prefix "#" o quote o ML_Syntax.print_char,
haftmann@24219
  1657
      pretty_string = ML_Syntax.print_string,
haftmann@24219
  1658
      pretty_numeral = fn unbounded => fn k =>
haftmann@24219
  1659
        if unbounded then "(" ^ IntInf.toString k ^ " : IntInf.int)"
haftmann@24219
  1660
        else IntInf.toString k,
haftmann@24219
  1661
      pretty_list = Pretty.enum "," "[" "]",
haftmann@24219
  1662
      infix_cons = (7, "::")}),
haftmann@24219
  1663
  ("OCaml", { pretty_char = fn c => enclose "'" "'"
haftmann@24219
  1664
        (let val i = ord c
haftmann@24219
  1665
          in if i < 32 orelse i = 39 orelse i = 92
haftmann@24219
  1666
            then prefix "\\" (string_of_int i)
haftmann@24219
  1667
            else c
haftmann@24219
  1668
          end),
haftmann@24219
  1669
      pretty_string = (fn _ => error "OCaml: no pretty strings"),
haftmann@24219
  1670
      pretty_numeral = fn unbounded => fn k => if k >= IntInf.fromInt 0 then
haftmann@24219
  1671
            if unbounded then
haftmann@24219
  1672
              "(Big_int.big_int_of_int " ^ IntInf.toString k ^ ")"
haftmann@24219
  1673
            else IntInf.toString k
haftmann@24219
  1674
          else
haftmann@24219
  1675
            if unbounded then
haftmann@24219
  1676
              "(Big_int.big_int_of_int " ^ (enclose "(" ")" o prefix "-"
haftmann@24219
  1677
                o IntInf.toString o op ~) k ^ ")"
haftmann@24219
  1678
            else (enclose "(" ")" o prefix "-" o IntInf.toString o op ~) k,
haftmann@24219
  1679
      pretty_list = Pretty.enum ";" "[" "]",
haftmann@24219
  1680
      infix_cons = (6, "::")}),
haftmann@24219
  1681
  ("Haskell", { pretty_char = fn c => enclose "'" "'"
haftmann@24219
  1682
        (let val i = ord c
haftmann@24219
  1683
          in if i < 32 orelse i = 39 orelse i = 92
haftmann@24219
  1684
            then Library.prefix "\\" (string_of_int i)
haftmann@24219
  1685
            else c
haftmann@24219
  1686
          end),
haftmann@24219
  1687
      pretty_string = ML_Syntax.print_string,
haftmann@24219
  1688
      pretty_numeral = fn unbounded => fn k => if k >= IntInf.fromInt 0 then
haftmann@24219
  1689
            IntInf.toString k
haftmann@24219
  1690
          else
haftmann@24219
  1691
            (enclose "(" ")" o Library.prefix "-" o IntInf.toString o IntInf.~) k,
haftmann@24219
  1692
      pretty_list = Pretty.enum "," "[" "]",
haftmann@24219
  1693
      infix_cons = (5, ":")})
haftmann@24219
  1694
];
haftmann@24219
  1695
haftmann@24219
  1696
in
haftmann@24219
  1697
haftmann@24219
  1698
fun pr_pretty target = case AList.lookup (op =) pretty target
haftmann@24219
  1699
 of SOME x => x
haftmann@24219
  1700
  | NONE => error ("Unknown code target language: " ^ quote target);
haftmann@24219
  1701
haftmann@24219
  1702
fun default_list (target_fxy, target_cons) pr fxy t1 t2 =
haftmann@24219
  1703
  brackify_infix (target_fxy, R) fxy [
haftmann@24219
  1704
    pr (INFX (target_fxy, X)) t1,
haftmann@24219
  1705
    str target_cons,
haftmann@24219
  1706
    pr (INFX (target_fxy, R)) t2
haftmann@24219
  1707
  ];
haftmann@24219
  1708
haftmann@24219
  1709
fun pretty_list c_nil c_cons target =
haftmann@24219
  1710
  let
haftmann@24219
  1711
    val pretty_ops = pr_pretty target;
haftmann@24219
  1712
    val mk_list = #pretty_list pretty_ops;
haftmann@24219
  1713
    fun pretty pr vars fxy [(t1, _), (t2, _)] =
haftmann@24219
  1714
      case Option.map (cons t1) (implode_list c_nil c_cons t2)
haftmann@24219
  1715
       of SOME ts => mk_list (map (pr vars NOBR) ts)
haftmann@24219
  1716
        | NONE => default_list (#infix_cons pretty_ops) (pr vars) fxy t1 t2;
haftmann@24219
  1717
  in (2, pretty) end;
haftmann@24219
  1718
haftmann@24219
  1719
fun pretty_list_string c_nil c_cons c_char c_nibbles target =
haftmann@24219
  1720
  let
haftmann@24219
  1721
    val pretty_ops = pr_pretty target;
haftmann@24219
  1722
    val mk_list = #pretty_list pretty_ops;
haftmann@24219
  1723
    val mk_char = #pretty_char pretty_ops;
haftmann@24219
  1724
    val mk_string = #pretty_string pretty_ops;
haftmann@24219
  1725
    fun pretty pr vars fxy [(t1, _), (t2, _)] =
haftmann@24219
  1726
      case Option.map (cons t1) (implode_list c_nil c_cons t2)
haftmann@24219
  1727
       of SOME ts => case implode_string c_char c_nibbles mk_char mk_string ts
haftmann@24219
  1728
           of SOME p => p
haftmann@24219
  1729
            | NONE => mk_list (map (pr vars NOBR) ts)
haftmann@24219
  1730
        | NONE => default_list (#infix_cons pretty_ops) (pr vars) fxy t1 t2;
haftmann@24219
  1731
  in (2, pretty) end;
haftmann@24219
  1732
haftmann@24219
  1733
fun pretty_char c_char c_nibbles target =
haftmann@24219
  1734
  let
haftmann@24219
  1735
    val mk_char = #pretty_char (pr_pretty target);
haftmann@24219
  1736
    fun pretty _ _ _ [(t1, _), (t2, _)] =
haftmann@24219
  1737
      case decode_char c_nibbles (t1, t2)
haftmann@24219
  1738
       of SOME c => (str o mk_char) c
haftmann@24219
  1739
        | NONE => error "Illegal character expression";
haftmann@24219
  1740
  in (2, pretty) end;
haftmann@24219
  1741
haftmann@24219
  1742
fun pretty_numeral unbounded c_bit0 c_bit1 c_pls c_min c_bit target =
haftmann@24219
  1743
  let
haftmann@24219
  1744
    val mk_numeral = #pretty_numeral (pr_pretty target);
haftmann@24219
  1745
    fun pretty _ _ _ [(t, _)] =
haftmann@24219
  1746
      case implode_numeral c_bit0 c_bit1 c_pls c_min c_bit t
haftmann@24219
  1747
       of SOME k => (str o mk_numeral unbounded) k
haftmann@24219
  1748
        | NONE => error "Illegal numeral expression";
haftmann@24219
  1749
  in (1, pretty) end;
haftmann@24219
  1750
haftmann@24219
  1751
fun pretty_ml_string c_char c_nibbles c_nil c_cons target =
haftmann@24219
  1752
  let
haftmann@24219
  1753
    val pretty_ops = pr_pretty target;
haftmann@24219
  1754
    val mk_char = #pretty_char pretty_ops;
haftmann@24219
  1755
    val mk_string = #pretty_string pretty_ops;
haftmann@24219
  1756
    fun pretty pr vars fxy [(t, _)] =
haftmann@24219
  1757
      case implode_list c_nil c_cons t
haftmann@24219
  1758
       of SOME ts => (case implode_string c_char c_nibbles mk_char mk_string ts
haftmann@24219
  1759
           of SOME p => p
haftmann@24219
  1760
            | NONE => error "Illegal ml_string expression")
haftmann@24219
  1761
        | NONE => error "Illegal ml_string expression";
haftmann@24219
  1762
  in (1, pretty) end;
haftmann@24219
  1763
haftmann@24219
  1764
val pretty_imperative_monad_bind =
haftmann@24219
  1765
  let
haftmann@24219
  1766
    fun pretty (pr : CodeName.var_ctxt -> fixity -> iterm -> Pretty.T)
haftmann@24219
  1767
          vars fxy [(t1, _), ((v, ty) `|-> t2, _)] =
haftmann@24219
  1768
            pr vars fxy (ICase (((t1, ty), ([(IVar v, t2)])), IVar ""))
haftmann@24219
  1769
      | pretty pr vars fxy [(t1, _), (t2, ty2)] =
haftmann@24219
  1770
          let
haftmann@24219
  1771
            (*this code suffers from the lack of a proper concept for bindings*)
haftmann@24219
  1772
            val vs = CodeThingol.fold_varnames cons t2 [];
haftmann@24219
  1773
            val v = Name.variant vs "x";
haftmann@24219
  1774
            val vars' = CodeName.intro_vars [v] vars;
haftmann@24219
  1775
            val var = IVar v;
haftmann@24219
  1776
            val ty = (hd o fst o CodeThingol.unfold_fun) ty2;
haftmann@24219
  1777
          in pr vars' fxy (ICase (((t1, ty), ([(var, t2 `$ var)])), IVar "")) end;
haftmann@24219
  1778
  in (2, pretty) end;
haftmann@24219
  1779
haftmann@24219
  1780
end; (*local*)
haftmann@24219
  1781
haftmann@24219
  1782
(** ML and Isar interface **)
haftmann@24219
  1783
haftmann@24219
  1784
local
haftmann@24219
  1785
haftmann@24219
  1786
fun map_syntax_exprs target =
haftmann@24219
  1787
  map_seri_data target o apsnd o apsnd o apfst o map_syntax_expr;
haftmann@24219
  1788
fun map_syntax_modls target =
haftmann@24219
  1789
  map_seri_data target o apsnd o apsnd o apsnd o map_syntax_modl;
haftmann@24219
  1790
fun map_reserveds target =
haftmann@24219
  1791
  map_seri_data target o apsnd o apfst o apsnd;
haftmann@24219
  1792
haftmann@24219
  1793
fun gen_add_syntax_class prep_class prep_const target raw_class raw_syn thy =
haftmann@24219
  1794
  let
haftmann@24219
  1795
    val cls = prep_class thy raw_class;
haftmann@24219
  1796
    val class = CodeName.class thy cls;
haftmann@24219
  1797
    fun mk_classop (const as (c, _)) = case AxClass.class_of_param thy c
haftmann@24219
  1798
     of SOME class' => if cls = class' then CodeName.const thy const
haftmann@24219
  1799
          else error ("Not a class operation for class " ^ quote class ^ ": " ^ quote c)
haftmann@24219
  1800
      | NONE => error ("Not a class operation: " ^ quote c);
haftmann@24219
  1801
    fun mk_syntax_ops raw_ops = AList.lookup (op =)
haftmann@24219
  1802
      ((map o apfst) (mk_classop o prep_const thy) raw_ops);
haftmann@24219
  1803
  in case raw_syn
haftmann@24219
  1804
   of SOME (syntax, raw_ops) =>
haftmann@24219
  1805
      thy
haftmann@24219
  1806
      |> (map_syntax_exprs target o apfst o apfst)
haftmann@24219
  1807
           (Symtab.update (class, (syntax, mk_syntax_ops raw_ops)))
haftmann@24219
  1808
    | NONE =>
haftmann@24219
  1809
      thy
haftmann@24219
  1810
      |> (map_syntax_exprs target o apfst o apfst)
haftmann@24219
  1811
           (Symtab.delete_safe class)
haftmann@24219
  1812
  end;
haftmann@24219
  1813
haftmann@24219
  1814
fun gen_add_syntax_inst prep_class prep_tyco target (raw_tyco, raw_class) add_del thy =
haftmann@24219
  1815
  let
haftmann@24219
  1816
    val inst = CodeName.instance thy (prep_class thy raw_class, prep_tyco thy raw_tyco);
haftmann@24219
  1817
  in if add_del then
haftmann@24219
  1818
    thy
haftmann@24219
  1819
    |> (map_syntax_exprs target o apfst o apsnd)
haftmann@24219
  1820
        (Symtab.update (inst, ()))
haftmann@24219
  1821
  else
haftmann@24219
  1822
    thy
haftmann@24219
  1823
    |> (map_syntax_exprs target o apfst o apsnd)
haftmann@24219
  1824
        (Symtab.delete_safe inst)
haftmann@24219
  1825
  end;
haftmann@24219
  1826
haftmann@24219
  1827
fun gen_add_syntax_tyco prep_tyco target raw_tyco raw_syn thy =
haftmann@24219
  1828
  let
haftmann@24219
  1829
    val tyco = prep_tyco thy raw_tyco;
haftmann@24219
  1830
    val tyco' = if tyco = "fun" then "fun" else CodeName.tyco thy tyco;
haftmann@24219
  1831
    fun check_args (syntax as (n, _)) = if n <> Sign.arity_number thy tyco
haftmann@24219
  1832
      then error ("Number of arguments mismatch in syntax for type constructor " ^ quote tyco)
haftmann@24219
  1833
      else syntax
haftmann@24219
  1834
  in case raw_syn
haftmann@24219
  1835
   of SOME syntax =>
haftmann@24219
  1836
      thy
haftmann@24219
  1837
      |> (map_syntax_exprs target o apsnd o apfst)
haftmann@24219
  1838
           (Symtab.update (tyco', check_args syntax))
haftmann@24219
  1839
   | NONE =>
haftmann@24219
  1840
      thy
haftmann@24219
  1841
      |> (map_syntax_exprs target o apsnd o apfst)
haftmann@24219
  1842
           (Symtab.delete_safe tyco')
haftmann@24219
  1843
  end;
haftmann@24219
  1844
haftmann@24219
  1845
fun gen_add_syntax_const prep_const target raw_c raw_syn thy =
haftmann@24219
  1846
  let
haftmann@24219
  1847
    val c = prep_const thy raw_c;
haftmann@24219
  1848
    val c' = CodeName.const thy c;
haftmann@24219
  1849
    fun check_args (syntax as (n, _)) = if n > (length o fst o strip_type o Sign.the_const_type thy o fst) c
haftmann@24219
  1850
      then error ("Too many arguments in syntax for constant " ^ (quote o fst) c)
haftmann@24219
  1851
      else syntax;
haftmann@24219
  1852
  in case raw_syn
haftmann@24219
  1853
   of SOME syntax =>
haftmann@24219
  1854
      thy
haftmann@24219
  1855
      |> (map_syntax_exprs target o apsnd o apsnd)
haftmann@24219
  1856
           (Symtab.update (c', check_args syntax))
haftmann@24219
  1857
   | NONE =>
haftmann@24219
  1858
      thy
haftmann@24219
  1859
      |> (map_syntax_exprs target o apsnd o apsnd)
haftmann@24219
  1860
           (Symtab.delete_safe c')
haftmann@24219
  1861
  end;
haftmann@24219
  1862
haftmann@24219
  1863
fun cert_class thy class =
haftmann@24219
  1864
  let
haftmann@24219
  1865
    val _ = AxClass.get_definition thy class;
haftmann@24219
  1866
  in class end;
haftmann@24219
  1867
haftmann@24219
  1868
fun read_class thy raw_class =
haftmann@24219
  1869
  let
haftmann@24219
  1870
    val class = Sign.intern_class thy raw_class;
haftmann@24219
  1871
    val _ = AxClass.get_definition thy class;
haftmann@24219
  1872
  in class end;
haftmann@24219
  1873
haftmann@24219
  1874
fun cert_tyco thy tyco =
haftmann@24219
  1875
  let
haftmann@24219
  1876
    val _ = if Sign.declared_tyname thy tyco then ()
haftmann@24219
  1877
      else error ("No such type constructor: " ^ quote tyco);
haftmann@24219
  1878
  in tyco end;
haftmann@24219
  1879
haftmann@24219
  1880
fun read_tyco thy raw_tyco =
haftmann@24219
  1881
  let
haftmann@24219
  1882
    val tyco = Sign.intern_type thy raw_tyco;
haftmann@24219
  1883
    val _ = if Sign.declared_tyname thy tyco then ()
haftmann@24219
  1884
      else error ("No such type constructor: " ^ quote raw_tyco);
haftmann@24219
  1885
  in tyco end;
haftmann@24219
  1886
haftmann@24219
  1887
fun idfs_of_const thy c =
haftmann@24219
  1888
  let
haftmann@24219
  1889
    val c' = (c, Sign.the_const_type thy c);
haftmann@24219
  1890
    val c'' = CodeUnit.const_of_cexpr thy c';
haftmann@24219
  1891
  in (c'', CodeName.const thy c'') end;
haftmann@24219
  1892
haftmann@24219
  1893
fun no_bindings x = (Option.map o apsnd)
haftmann@24219
  1894
  (fn pretty => fn pr => fn vars => pretty (pr vars)) x;
haftmann@24219
  1895
haftmann@24219
  1896
fun gen_add_haskell_monad prep_const c_run c_mbind c_kbind thy =
haftmann@24219
  1897
  let
haftmann@24219
  1898
    val c_run' = prep_const thy c_run;
haftmann@24219
  1899
    val c_mbind' = prep_const thy c_mbind;
haftmann@24219
  1900
    val c_mbind'' = CodeName.const thy c_mbind';
haftmann@24219
  1901
    val c_kbind' = prep_const thy c_kbind;
haftmann@24219
  1902
    val c_kbind'' = CodeName.const thy c_kbind';
haftmann@24219
  1903
    val pr = pretty_haskell_monad c_mbind'' c_kbind''
haftmann@24219
  1904
  in
haftmann@24219
  1905
    thy
haftmann@24219
  1906
    |> gen_add_syntax_const (K I) target_Haskell c_run' (SOME pr)
haftmann@24219
  1907
    |> gen_add_syntax_const (K I) target_Haskell c_mbind'
haftmann@24219
  1908
          (no_bindings (SOME (parse_infix fst (L, 1) ">>=")))
haftmann@24219
  1909
    |> gen_add_syntax_const (K I) target_Haskell c_kbind'
haftmann@24219
  1910
          (no_bindings (SOME (parse_infix fst (L, 1) ">>")))
haftmann@24219
  1911
  end;
haftmann@24219
  1912
haftmann@24219
  1913
fun add_reserved target =
haftmann@24219
  1914
  let
haftmann@24219
  1915
    fun add sym syms = if member (op =) syms sym
haftmann@24219
  1916
      then error ("Reserved symbol " ^ quote sym ^ " already declared")
haftmann@24219
  1917
      else insert (op =) sym syms
haftmann@24219
  1918
  in map_reserveds target o add end;
haftmann@24219
  1919
haftmann@24219
  1920
fun add_modl_alias target =
haftmann@24219
  1921
  map_syntax_modls target o apfst o Symtab.update o apsnd CodeName.check_modulename;
haftmann@24219
  1922
haftmann@24219
  1923
fun add_modl_prolog target =
haftmann@24219
  1924
  map_syntax_modls target o apsnd o
haftmann@24219
  1925
    (fn (modl, NONE) => Symtab.delete modl | (modl, SOME prolog) =>
haftmann@24219
  1926
      Symtab.update (modl, Pretty.str prolog));
haftmann@24219
  1927
haftmann@24219
  1928
fun zip_list (x::xs) f g =
haftmann@24219
  1929
  f
haftmann@24219
  1930
  #-> (fn y =>
haftmann@24219
  1931
    fold_map (fn x => g |-- f >> pair x) xs
haftmann@24219
  1932
    #-> (fn xys => pair ((x, y) :: xys)));
haftmann@24219
  1933
haftmann@24219
  1934
structure P = OuterParse
haftmann@24219
  1935
and K = OuterKeyword
haftmann@24219
  1936
haftmann@24219
  1937
fun parse_multi_syntax parse_thing parse_syntax =
haftmann@24219
  1938
  P.and_list1 parse_thing
haftmann@24219
  1939
  #-> (fn things => Scan.repeat1 (P.$$$ "(" |-- P.name --
haftmann@24219
  1940
        (zip_list things parse_syntax (P.$$$ "and")) --| P.$$$ ")"));
haftmann@24219
  1941
haftmann@24219
  1942
val (infixK, infixlK, infixrK) = ("infix", "infixl", "infixr");
haftmann@24219
  1943
haftmann@24219
  1944
fun parse_syntax prep_arg xs =
haftmann@24219
  1945
  Scan.option ((
haftmann@24219
  1946
      ((P.$$$ infixK  >> K X)
haftmann@24219
  1947
        || (P.$$$ infixlK >> K L)
haftmann@24219
  1948
        || (P.$$$ infixrK >> K R))
haftmann@24219
  1949
        -- P.nat >> parse_infix prep_arg
haftmann@24219
  1950
      || Scan.succeed (parse_mixfix prep_arg))
haftmann@24219
  1951
      -- P.string
haftmann@24219
  1952
      >> (fn (parse, s) => parse s)) xs;
haftmann@24219
  1953
haftmann@24219
  1954
val (code_classK, code_instanceK, code_typeK, code_constK, code_monadK,
haftmann@24219
  1955
  code_reservedK, code_modulenameK, code_moduleprologK) =
haftmann@24219
  1956
  ("code_class", "code_instance", "code_type", "code_const", "code_monad",
haftmann@24219
  1957
    "code_reserved", "code_modulename", "code_moduleprolog");
haftmann@24219
  1958
haftmann@24219
  1959
in
haftmann@24219
  1960
haftmann@24219
  1961
val parse_syntax = parse_syntax;
haftmann@24219
  1962
haftmann@24219
  1963
val add_syntax_class = gen_add_syntax_class cert_class (K I);
haftmann@24219
  1964
val add_syntax_inst = gen_add_syntax_inst cert_class cert_tyco;
haftmann@24219
  1965
val add_syntax_tyco = gen_add_syntax_tyco cert_tyco;
haftmann@24219
  1966
val add_syntax_const = gen_add_syntax_const (K I);
haftmann@24219
  1967
haftmann@24219
  1968
val add_syntax_class_cmd = gen_add_syntax_class read_class CodeUnit.read_const;
haftmann@24219
  1969
val add_syntax_inst_cmd = gen_add_syntax_inst read_class read_tyco;
haftmann@24219
  1970
val add_syntax_tyco_cmd = gen_add_syntax_tyco read_tyco;
haftmann@24219
  1971
val add_syntax_const_cmd = gen_add_syntax_const CodeUnit.read_const;
haftmann@24219
  1972
haftmann@24219
  1973
fun add_syntax_tycoP target tyco = parse_syntax I >> add_syntax_tyco_cmd target tyco;
haftmann@24219
  1974
fun add_syntax_constP target c = parse_syntax fst >> (add_syntax_const_cmd target c o no_bindings);
haftmann@24219
  1975
haftmann@24219
  1976
fun add_undefined target undef target_undefined thy =
haftmann@24219
  1977
  let
haftmann@24219
  1978
    val (undef', _) = idfs_of_const thy undef;
haftmann@24219
  1979
    fun pr _ _ _ _ = str target_undefined;
haftmann@24219
  1980
  in
haftmann@24219
  1981
    thy
haftmann@24219
  1982
    |> add_syntax_const target undef' (SOME (~1, pr))
haftmann@24219
  1983
  end;
haftmann@24219
  1984
haftmann@24219
  1985
fun add_pretty_list target nill cons thy =
haftmann@24219
  1986
  let
haftmann@24219
  1987
    val (_, nil'') = idfs_of_const thy nill;
haftmann@24219
  1988
    val (cons', cons'') = idfs_of_const thy cons;
haftmann@24219
  1989
    val pr = pretty_list nil'' cons'' target;
haftmann@24219
  1990
  in
haftmann@24219
  1991
    thy
haftmann@24219
  1992
    |> add_syntax_const target cons' (SOME pr)
haftmann@24219
  1993
  end;
haftmann@24219
  1994
haftmann@24219
  1995
fun add_pretty_list_string target nill cons charr nibbles thy =
haftmann@24219
  1996
  let
haftmann@24219
  1997
    val (_, nil'') = idfs_of_const thy nill;
haftmann@24219
  1998
    val (cons', cons'') = idfs_of_const thy cons;
haftmann@24219
  1999
    val (_, charr'') = idfs_of_const thy charr;
haftmann@24219
  2000
    val (_, nibbles'') = split_list (map (idfs_of_const thy) nibbles);
haftmann@24219
  2001
    val pr = pretty_list_string nil'' cons'' charr'' nibbles'' target;
haftmann@24219
  2002
  in
haftmann@24219
  2003
    thy
haftmann@24219
  2004
    |> add_syntax_const target cons' (SOME pr)
haftmann@24219
  2005
  end;
haftmann@24219
  2006
haftmann@24219
  2007
fun add_pretty_char target charr nibbles thy =
haftmann@24219
  2008
  let
haftmann@24219
  2009
    val (charr', charr'') = idfs_of_const thy charr;
haftmann@24219
  2010
    val (_, nibbles'') = split_list (map (idfs_of_const thy) nibbles);
haftmann@24219
  2011
    val pr = pretty_char charr'' nibbles'' target;
haftmann@24219
  2012
  in
haftmann@24219
  2013
    thy
haftmann@24219
  2014
    |> add_syntax_const target charr' (SOME pr)
haftmann@24219
  2015
  end;
haftmann@24219
  2016
haftmann@24219
  2017
fun add_pretty_numeral target unbounded number_of b0 b1 pls min bit thy =
haftmann@24219
  2018
  let
haftmann@24219
  2019
    val number_of' = CodeUnit.const_of_cexpr thy number_of;
haftmann@24219
  2020
    val (_, b0'') = idfs_of_const thy b0;
haftmann@24219
  2021
    val (_, b1'') = idfs_of_const thy b1;
haftmann@24219
  2022
    val (_, pls'') = idfs_of_const thy pls;
haftmann@24219
  2023
    val (_, min'') = idfs_of_const thy min;
haftmann@24219
  2024
    val (_, bit'') = idfs_of_const thy bit;
haftmann@24219
  2025
    val pr = pretty_numeral unbounded b0'' b1'' pls'' min'' bit'' target;
haftmann@24219
  2026
  in
haftmann@24219
  2027
    thy
haftmann@24219
  2028
    |> add_syntax_const target number_of' (SOME pr)
haftmann@24219
  2029
  end;
haftmann@24219
  2030
haftmann@24219
  2031
fun add_pretty_ml_string target charr nibbles nill cons str thy =
haftmann@24219
  2032
  let
haftmann@24219
  2033
    val (_, charr'') = idfs_of_const thy charr;
haftmann@24219
  2034
    val (_, nibbles'') = split_list (map (idfs_of_const thy) nibbles);
haftmann@24219
  2035
    val (_, nil'') = idfs_of_const thy nill;
haftmann@24219
  2036
    val (_, cons'') = idfs_of_const thy cons;
haftmann@24219
  2037
    val (str', _) = idfs_of_const thy str;
haftmann@24219
  2038
    val pr = pretty_ml_string charr'' nibbles'' nil'' cons'' target;
haftmann@24219
  2039
  in
haftmann@24219
  2040
    thy
haftmann@24219
  2041
    |> add_syntax_const target str' (SOME pr)
haftmann@24219
  2042
  end;
haftmann@24219
  2043
haftmann@24219
  2044
fun add_pretty_imperative_monad_bind target bind thy =
haftmann@24219
  2045
  let
haftmann@24219
  2046
    val (bind', _) = idfs_of_const thy bind;
haftmann@24219
  2047
    val pr = pretty_imperative_monad_bind
haftmann@24219
  2048
  in
haftmann@24219
  2049
    thy
haftmann@24219
  2050
    |> add_syntax_const target bind' (SOME pr)
haftmann@24219
  2051
  end;
haftmann@24219
  2052
haftmann@24219
  2053
val add_haskell_monad = gen_add_haskell_monad CodeUnit.read_const;
haftmann@24219
  2054
haftmann@24219
  2055
val code_classP =
haftmann@24219
  2056
  OuterSyntax.command code_classK "define code syntax for class" K.thy_decl (
haftmann@24219
  2057
    parse_multi_syntax P.xname
haftmann@24219
  2058
      (Scan.option (P.string -- Scan.optional (P.$$$ "where" |-- Scan.repeat1
haftmann@24219
  2059
        (P.term --| (P.$$$ "\\<equiv>" || P.$$$ "==") -- P.string)) []))
haftmann@24219
  2060
    >> (Toplevel.theory oo fold) (fn (target, syns) =>
haftmann@24219
  2061
          fold (fn (raw_class, syn) => add_syntax_class_cmd target raw_class syn) syns)
haftmann@24219
  2062
  );
haftmann@24219
  2063
haftmann@24219
  2064
val code_instanceP =
haftmann@24219
  2065
  OuterSyntax.command code_instanceK "define code syntax for instance" K.thy_decl (
haftmann@24219
  2066
    parse_multi_syntax (P.xname --| P.$$$ "::" -- P.xname)
haftmann@24219
  2067
      ((P.minus >> K true) || Scan.succeed false)
haftmann@24219
  2068
    >> (Toplevel.theory oo fold) (fn (target, syns) =>
haftmann@24219
  2069
          fold (fn (raw_inst, add_del) => add_syntax_inst_cmd target raw_inst add_del) syns)
haftmann@24219
  2070
  );
haftmann@24219
  2071
haftmann@24219
  2072
val code_typeP =
haftmann@24219
  2073
  OuterSyntax.command code_typeK "define code syntax for type constructor" K.thy_decl (
haftmann@24219
  2074
    parse_multi_syntax P.xname (parse_syntax I)
haftmann@24219
  2075
    >> (Toplevel.theory oo fold) (fn (target, syns) =>
haftmann@24219
  2076
          fold (fn (raw_tyco, syn) => add_syntax_tyco_cmd target raw_tyco syn) syns)
haftmann@24219
  2077
  );
haftmann@24219
  2078
haftmann@24219
  2079
val code_constP =
haftmann@24219
  2080
  OuterSyntax.command code_constK "define code syntax for constant" K.thy_decl (
haftmann@24219
  2081
    parse_multi_syntax P.term (parse_syntax fst)
haftmann@24219
  2082
    >> (Toplevel.theory oo fold) (fn (target, syns) =>
haftmann@24219
  2083
          fold (fn (raw_const, syn) => add_syntax_const_cmd target raw_const (no_bindings syn)) syns)
haftmann@24219
  2084
  );
haftmann@24219
  2085
haftmann@24219
  2086
val code_monadP =
haftmann@24219
  2087
  OuterSyntax.command code_monadK "define code syntax for Haskell monads" K.thy_decl (
haftmann@24219
  2088
    P.term -- P.term -- P.term
haftmann@24219
  2089
    >> (fn ((raw_run, raw_mbind), raw_kbind) => Toplevel.theory 
haftmann@24219
  2090
          (add_haskell_monad raw_run raw_mbind raw_kbind))
haftmann@24219
  2091
  );
haftmann@24219
  2092
haftmann@24219
  2093
val code_reservedP =
haftmann@24219
  2094
  OuterSyntax.command code_reservedK "declare words as reserved for target language" K.thy_decl (
haftmann@24219
  2095
    P.name -- Scan.repeat1 P.name
haftmann@24219
  2096
    >> (fn (target, reserveds) => (Toplevel.theory o fold (add_reserved target)) reserveds)
haftmann@24219
  2097
  )
haftmann@24219
  2098
haftmann@24219
  2099
val code_modulenameP =
haftmann@24219
  2100
  OuterSyntax.command code_modulenameK "alias module to other name" K.thy_decl (
haftmann@24219
  2101
    P.name -- Scan.repeat1 (P.name -- P.name)
haftmann@24219
  2102
    >> (fn (target, modlnames) => (Toplevel.theory o fold (add_modl_alias target)) modlnames)
haftmann@24219
  2103
  )
haftmann@24219
  2104
haftmann@24219
  2105
val code_moduleprologP =
haftmann@24219
  2106
  OuterSyntax.command code_moduleprologK "add prolog to module" K.thy_decl (
haftmann@24219
  2107
    P.name -- Scan.repeat1 (P.name -- (P.text >> (fn "-" => NONE | s => SOME s)))
haftmann@24219
  2108
    >> (fn (target, prologs) => (Toplevel.theory o fold (add_modl_prolog target)) prologs)
haftmann@24219
  2109
  )
haftmann@24219
  2110
haftmann@24219
  2111
val _ = OuterSyntax.add_keywords [infixK, infixlK, infixrK];
haftmann@24219
  2112
haftmann@24219
  2113
val _ = OuterSyntax.add_parsers [code_classP, code_instanceP, code_typeP, code_constP,
haftmann@24219
  2114
  code_reservedP, code_modulenameP, code_moduleprologP, code_monadP];
haftmann@24219
  2115
haftmann@24219
  2116
haftmann@24219
  2117
(*including serializer defaults*)
haftmann@24219
  2118
val setup =
haftmann@24219
  2119
  add_serializer (target_SML, isar_seri_sml)
haftmann@24219
  2120
  #> add_serializer (target_OCaml, isar_seri_ocaml)
haftmann@24219
  2121
  #> add_serializer (target_Haskell, isar_seri_haskell)
haftmann@24219
  2122
  #> add_serializer (target_diag, fn _ => fn _ => fn _ => seri_diagnosis)
haftmann@24219
  2123
  #> add_syntax_tyco "SML" "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@24219
  2124
      (gen_brackify (case fxy of NOBR => false | _ => eval_fxy (INFX (1, R)) fxy) o Pretty.breaks) [
haftmann@24219
  2125
        pr_typ (INFX (1, X)) ty1,
haftmann@24219
  2126
        str "->",
haftmann@24219
  2127
        pr_typ (INFX (1, R)) ty2
haftmann@24219
  2128
      ]))
haftmann@24219
  2129
  #> add_syntax_tyco "OCaml" "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@24219
  2130
      (gen_brackify (case fxy of NOBR => false | _ => eval_fxy (INFX (1, R)) fxy) o Pretty.breaks) [
haftmann@24219
  2131
        pr_typ (INFX (1, X)) ty1,
haftmann@24219
  2132
        str "->",
haftmann@24219
  2133
        pr_typ (INFX (1, R)) ty2
haftmann@24219
  2134
      ]))
haftmann@24219
  2135
  #> add_syntax_tyco "Haskell" "fun" (SOME (2, fn pr_typ => fn fxy => fn [ty1, ty2] =>
haftmann@24219
  2136
      brackify_infix (1, R) fxy [
haftmann@24219
  2137
        pr_typ (INFX (1, X)) ty1,
haftmann@24219
  2138
        str "->",
haftmann@24219
  2139
        pr_typ (INFX (1, R)) ty2
haftmann@24219
  2140
      ]))
haftmann@24219
  2141
  #> fold (add_reserved "SML") ML_Syntax.reserved_names
haftmann@24219
  2142
  #> fold (add_reserved "SML")
haftmann@24219
  2143
      ["o" (*dictionary projections use it already*), "Fail", "div", "mod" (*standard infixes*)]
haftmann@24219
  2144
  #> fold (add_reserved "OCaml") [
haftmann@24219
  2145
      "and", "as", "assert", "begin", "class",
haftmann@24219
  2146
      "constraint", "do", "done", "downto", "else", "end", "exception",
haftmann@24219
  2147
      "external", "false", "for", "fun", "function", "functor", "if",
haftmann@24219
  2148
      "in", "include", "inherit", "initializer", "lazy", "let", "match", "method",
haftmann@24219
  2149
      "module", "mutable", "new", "object", "of", "open", "or", "private", "rec",
haftmann@24219
  2150
      "sig", "struct", "then", "to", "true", "try", "type", "val",
haftmann@24219
  2151
      "virtual", "when", "while", "with"
haftmann@24219
  2152
    ]
haftmann@24219
  2153
  #> fold (add_reserved "OCaml") ["failwith", "mod"]
haftmann@24219
  2154
  #> fold (add_reserved "Haskell") [
haftmann@24219
  2155
      "hiding", "deriving", "where", "case", "of", "infix", "infixl", "infixr",
haftmann@24219
  2156
      "import", "default", "forall", "let", "in", "class", "qualified", "data",
haftmann@24219
  2157
      "newtype", "instance", "if", "then", "else", "type", "as", "do", "module"
haftmann@24219
  2158
    ]
haftmann@24219
  2159
  #> fold (add_reserved "Haskell") [
haftmann@24219
  2160
      "Prelude", "Main", "Bool", "Maybe", "Either", "Ordering", "Char", "String", "Int",
haftmann@24219
  2161
      "Integer", "Float", "Double", "Rational", "IO", "Eq", "Ord", "Enum", "Bounded",
haftmann@24219
  2162
      "Num", "Real", "Integral", "Fractional", "Floating", "RealFloat", "Monad", "Functor",
haftmann@24219
  2163
      "AlreadyExists", "ArithException", "ArrayException", "AssertionFailed", "AsyncException",
haftmann@24219
  2164
      "BlockedOnDeadMVar", "Deadlock", "Denormal", "DivideByZero", "DotNetException", "DynException",
haftmann@24219
  2165
      "Dynamic", "EOF", "EQ", "EmptyRec", "ErrorCall", "ExitException", "ExitFailure",
haftmann@24219
  2166
      "ExitSuccess", "False", "GT", "HeapOverflow",
haftmann@24219
  2167
      "IOError", "IOException", "IllegalOperation",
haftmann@24219
  2168
      "IndexOutOfBounds", "Just", "Key", "LT", "Left", "LossOfPrecision", "NoMethodError",
haftmann@24219
  2169
      "NoSuchThing", "NonTermination", "Nothing", "Obj", "OtherError", "Overflow",
haftmann@24219
  2170
      "PatternMatchFail", "PermissionDenied", "ProtocolError", "RecConError", "RecSelError",
haftmann@24219
  2171
      "RecUpdError", "ResourceBusy", "ResourceExhausted", "Right", "StackOverflow",
haftmann@24219
  2172
      "ThreadKilled", "True", "TyCon", "TypeRep", "UndefinedElement", "Underflow",
haftmann@24219
  2173
      "UnsupportedOperation", "UserError", "abs", "absReal", "acos", "acosh", "all",
haftmann@24219
  2174
      "and", "any", "appendFile", "asTypeOf", "asciiTab", "asin", "asinh", "atan",
haftmann@24219
  2175
      "atan2", "atanh", "basicIORun", "blockIO", "boundedEnumFrom", "boundedEnumFromThen",
haftmann@24219
  2176
      "boundedEnumFromThenTo", "boundedEnumFromTo", "boundedPred", "boundedSucc", "break",
haftmann@24219
  2177
      "catch", "catchException", "ceiling", "compare", "concat", "concatMap", "const",
haftmann@24219
  2178
      "cos", "cosh", "curry", "cycle", "decodeFloat", "denominator", "div", "divMod",
haftmann@24219
  2179
      "doubleToRatio", "doubleToRational", "drop", "dropWhile", "either", "elem",
haftmann@24219
  2180
      "emptyRec", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
haftmann@24219
  2181
      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip",
haftmann@24219
  2182
      "floatDigits", "floatProperFraction", "floatRadix", "floatRange", "floatToRational",
haftmann@24219
  2183
      "floor", "fmap", "foldl", "foldl'", "foldl1", "foldr", "foldr1", "fromDouble",
haftmann@24219
  2184
      "fromEnum", "fromEnum_0", "fromInt", "fromInteger", "fromIntegral", "fromObj",
haftmann@24219
  2185
      "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head",
haftmann@24219
  2186
      "id", "inRange", "index", "init", "intToRatio", "interact", "ioError", "isAlpha",
haftmann@24219
  2187
      "isAlphaNum", "isDenormalized", "isDigit", "isHexDigit", "isIEEE", "isInfinite",
haftmann@24219
  2188
      "isLower", "isNaN", "isNegativeZero", "isOctDigit", "isSpace", "isUpper", "iterate", "iterate'",
haftmann@24219
  2189
      "last", "lcm", "length", "lex", "lexDigits", "lexLitChar", "lexmatch", "lines", "log",
haftmann@24219
  2190
      "logBase", "lookup", "loop", "map", "mapM", "mapM_", "max", "maxBound", "maximum",
haftmann@24219
  2191
      "maybe", "min", "minBound", "minimum", "mod", "negate", "nonnull", "not", "notElem",
haftmann@24219
  2192
      "null", "numerator", "numericEnumFrom", "numericEnumFromThen", "numericEnumFromThenTo",
haftmann@24219
  2193
      "numericEnumFromTo", "odd", "or", "otherwise", "pi", "pred", 
haftmann@24219
  2194
      "print", "product", "properFraction", "protectEsc", "putChar", "putStr", "putStrLn",
haftmann@24219
  2195
      "quot", "quotRem", "range", "rangeSize", "rationalToDouble", "rationalToFloat",
haftmann@24219
  2196
      "rationalToRealFloat", "read", "readDec", "readField", "readFieldName", "readFile",
haftmann@24219
  2197
      "readFloat", "readHex", "readIO", "readInt", "readList", "readLitChar", "readLn",
haftmann@24219
  2198
      "readOct", "readParen", "readSigned", "reads", "readsPrec", "realFloatToRational",
haftmann@24219
  2199
      "realToFrac", "recip", "reduce", "rem", "repeat", "replicate", "return", "reverse",
haftmann@24219
  2200
      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence",
haftmann@24219
  2201
      "sequence_", "show", "showChar", "showException", "showField", "showList",
haftmann@24219
  2202
      "showLitChar", "showParen", "showString", "shows", "showsPrec", "significand",
haftmann@24219
  2203
      "signum", "signumReal", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract",
haftmann@24219
  2204
      "succ", "sum", "tail", "take", "takeWhile", "takeWhile1", "tan", "tanh", "threadToIOResult",
haftmann@24219
  2205
      "throw", "toEnum", "toInt", "toInteger", "toObj", "toRational", "truncate", "uncurry",
haftmann@24219
  2206
      "undefined", "unlines", "unsafeCoerce", "unsafeIndex", "unsafeRangeSize", "until", "unwords",
haftmann@24219
  2207
      "unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3"
haftmann@24219
  2208
    ] (*due to weird handling of ':', we can't do anything else than to import *all* prelude symbols*);
haftmann@24219
  2209
haftmann@24219
  2210
end; (*local*)
haftmann@24219
  2211
haftmann@24219
  2212
end; (*struct*)