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