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