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