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