ocaml_printer.ml 12.2 KB
Newer Older
Mário Pereira's avatar
Mário Pereira committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
(*  Copyright 2010-2016   --   INRIA - CNRS - Paris-Sud University  *)
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

(** Printer for extracted OCaml code *)

open Compile
open Format
open Ident
open Pp
18
19
open Ity
open Term
20
21
open Expr
open Ty
22
23
24
open Theory
open Pmodule
open Stdlib
Mário Pereira's avatar
Mário Pereira committed
25
open Pdecl
Mário Pereira's avatar
Mário Pereira committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

module Print = struct

  open ML

  let ocaml_keywords =
    ["and"; "as"; "assert"; "asr"; "begin";
     "class"; "constraint"; "do"; "done"; "downto"; "else"; "end";
     "exception"; "external"; "false"; "for"; "fun"; "function";
     "functor"; "if"; "in"; "include"; "inherit"; "initializer";
     "land"; "lazy"; "let"; "lor"; "lsl"; "lsr"; "lxor"; "match";
     "method"; "mod"; "module"; "mutable"; "new"; "object"; "of";
     "open"; "or"; "private"; "rec"; "sig"; "struct"; "then"; "to";
     "true"; "try"; "type"; "val"; "virtual"; "when"; "while"; "with";
     "raise";]

42
43
44
45
46
  let is_ocaml_keyword =
    let h = Hstr.create 16 in
    List.iter (fun s -> Hstr.add h s ()) ocaml_keywords;
    Hstr.mem h

Mário Pereira's avatar
Mário Pereira committed
47
  let iprinter, aprinter =
Mário Pereira's avatar
Mário Pereira committed
48
    let isanitize = sanitizer char_to_alpha char_to_alnumus in
Mário Pereira's avatar
Mário Pereira committed
49
50
51
    let lsanitize = sanitizer char_to_lalpha char_to_alnumus in
    create_ident_printer ocaml_keywords ~sanitizer:isanitize,
    create_ident_printer ocaml_keywords ~sanitizer:lsanitize
Mário Pereira's avatar
Mário Pereira committed
52

Mário Pereira's avatar
Mário Pereira committed
53
54
55
56
57
58
59
  let forget_tvs () =
    forget_all aprinter

  let forget_id vs = forget_id iprinter vs
  let forget_var (id, _, _) = forget_id id
  let forget_vars = List.iter forget_var

Mário Pereira's avatar
Mário Pereira committed
60
61
62
63
  let print_ident fmt id =
    let s = id_unique iprinter id in
    fprintf fmt "%s" s

64
65
  let print_qident ~sanitizer info fmt id =
    try
66
      let _, _, q =
67
68
69
70
71
72
73
74
75
76
77
        try Pmodule.restore_path id
        with Not_found -> Theory.restore_path id in
      let s = String.concat "__" q in
      let s = Ident.sanitizer char_to_alpha char_to_alnumus s in
      let s = sanitizer s in
      let s = if is_ocaml_keyword s then s ^ "_renamed" else s in
      if Sid.mem id info.info_current_th.th_local ||
         Opt.fold (fun _ m -> Sid.mem id m.Pmodule.mod_local)
           false info.info_current_mo
      then fprintf fmt "%s" s
      else
78
        (* let fname = if lp = [] then info.info_fname else None in *)
79
80
81
82
83
84
85
86
        let m = Strings.capitalize "m" in
        fprintf fmt "%s.%s" m s
    with Not_found ->
      let s = id_unique ~sanitizer iprinter id in
      fprintf fmt "%s" s

  let print_lident = print_qident ~sanitizer:Strings.uncapitalize
  let print_uident = print_qident ~sanitizer:Strings.capitalize
Mário Pereira's avatar
Mário Pereira committed
87
88

  let print_tv fmt tv =
89
    fprintf fmt "'%s" (id_unique aprinter tv.tv_name)
Mário Pereira's avatar
Mário Pereira committed
90

91
92
93
  let protect_on b s =
    if b then "(" ^^ s ^^ ")" else s

Mário Pereira's avatar
Mário Pereira committed
94
95
  let star fmt () = fprintf fmt " *@ "

96
97
  (** Types *)

98
  let rec print_ty ?(paren=false) fmt = function
99
    | Tvar tv ->
100
      print_tv fmt tv
Mário Pereira's avatar
Mário Pereira committed
101
    | Ttuple [] ->
102
      fprintf fmt "unit"
Mário Pereira's avatar
Mário Pereira committed
103
    | Ttuple tl ->
104
105
      fprintf fmt (protect_on paren "@[%a@]")
        (print_list star (print_ty ~paren:false)) tl
Mário Pereira's avatar
Mário Pereira committed
106
    | Tapp (ts, []) ->
107
      print_ident fmt ts
Mário Pereira's avatar
Mário Pereira committed
108
    | Tapp (ts, [ty]) ->
109
110
      fprintf fmt (protect_on paren "%a@ %a")
        (print_ty ~paren:true) ty print_ident ts
Mário Pereira's avatar
Mário Pereira committed
111
    | Tapp (ts, tl) ->
112
113
114
      fprintf fmt (protect_on paren "(%a)@ %a")
        (print_list comma (print_ty ~paren:false)) tl
        print_ident ts
Mário Pereira's avatar
Mário Pereira committed
115

116
  let print_vsty fmt (v, ty, _) =
117
118
119
120
121
122
123
    fprintf fmt "%a:@ %a" print_ident v (print_ty ~paren:false) ty

  let print_tv_arg = print_tv
  let print_tv_args fmt = function
    | []   -> ()
    | [tv] -> fprintf fmt "%a@ " print_tv_arg tv
    | tvl  -> fprintf fmt "(%a)@ " (print_list comma print_tv_arg) tvl
Mário Pereira's avatar
Mário Pereira committed
124
125
126
127

  let print_vs_arg fmt vs =
    fprintf fmt "@[(%a)@]" print_vsty vs

Mário Pereira's avatar
Mário Pereira committed
128
129
130
131
132
133
134
135
136
137
138
139
140
  let print_path =
    print_list dot pp_print_string (* point-free *)

  let print_path_id fmt = function
    | [], id -> print_ident fmt id
    | p, id  -> fprintf fmt "%a.%a" print_path p print_ident id

  let print_theory_name fmt th =
    print_path_id fmt (th.th_path, th.th_name)

  let print_module_name fmt m =
    print_theory_name fmt m.mod_theory

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
  let rec print_pat fmt = function
    | Pwild ->
       fprintf fmt "_"
    | Pident id ->
       print_ident fmt id
    | Pas (p, id) ->
       fprintf fmt "%a as %a" print_pat p print_ident id
    | Por (p1, p2) ->
       fprintf fmt "%a | %a" print_pat p1 print_pat p2
    | Ptuple pl ->
       fprintf fmt "(%a)" (print_list comma print_pat) pl
    | Papp (id, []) ->
       print_ident fmt id
    | Papp (id, [p]) ->
       fprintf fmt "%a %a" print_ident id print_pat p
    | Papp (id, pl) ->
       fprintf fmt "%a (%a)" print_ident id (print_list comma print_pat) pl
    | Precord fl ->
       let print_field fmt (id, p) =
         fprintf fmt "%a = %a" print_ident id print_pat p
       in
       fprintf fmt "{ %a }" (print_list semi print_field) fl

164
165
166
167
168
169
170
171
172
173
174
175
  let print_const fmt c =
    let n = Number.compute_int c in
    let m = BigInt.to_int n in
    fprintf fmt "%d" m

  (** Expressions *)

  let extract_op {id_string = s} =
    try Some (Strings.remove_prefix "infix " s) with Not_found ->
    try Some (Strings.remove_prefix "prefix " s) with Not_found ->
    None

176
177
  let pv_name pv = pv.pv_vs.vs_name

Mário Pereira's avatar
Mário Pereira committed
178
179
180
181
182
183
184
185
  let get_record info rs =
    match Mid.find_opt rs.rs_name info.info_mo_known_map with
    | Some {pd_node = PDtype itdl} ->
      let itd = List.find (fun {itd_constructors=constr} ->
          List.exists (rs_equal rs) constr) itdl in
      List.filter (fun e -> not (rs_ghost e)) itd.itd_fields
    | _ -> []

186
  let rec print_apply info fmt rs pvl =
187
    let isfield =
188
189
      match rs.rs_field with
      | None -> false
190
191
192
193
194
195
196
197
198
      | Some _ -> true in
    let isconstructor () =
      let open Pdecl in
      match Mid.find_opt rs.rs_name info.info_mo_known_map with
      | Some {pd_node = PDtype its} ->
        let is_constructor its =
          List.exists (rs_equal rs) its.itd_constructors in
        List.exists is_constructor its
      | _ -> false
199
    in
200
    match extract_op rs.rs_name, pvl with
201
202
    | Some o, [t1; t2] ->
       fprintf fmt "@[<hov 1>%a %s %a@]"
203
         (print_expr info) t1 o (print_expr info) t2
204
    | _, [] ->
205
       print_ident fmt rs.rs_name
206
    | _, [t1] when isfield ->
207
208
      fprintf fmt "%a.%a" (print_expr info) t1 print_ident rs.rs_name
    | _, tl when isconstructor () ->
Mário Pereira's avatar
Mário Pereira committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
      let pjl = get_record info rs in
      if pjl = [] then
        fprintf fmt "@[<hov 2>%a (%a)@]"
          print_ident rs.rs_name (print_list comma (print_expr info)) tl
      else
        let rec print_list2 sep sep_m print1 print2 fmt (l1, l2) =
          match l1, l2 with
          | x1 :: r1, x2 :: r2 ->
            printf "x1:%a@\n" print_ident x1.rs_name;
            print1 fmt x1; sep_m fmt (); print2 fmt x2; sep fmt ();
            print_list2 sep sep_m print1 print2 fmt (r1, r2)
          | _ -> ()
        in
        let print_rs info fmt rs =
          fprintf fmt "%a" (print_lident info) rs.rs_name
        in
        fprintf fmt "@[<hov 2>{ %a }@]"
          (print_list2 semi equal (print_rs info) (print_expr info)) (pjl, tl)
227
228
    | _, tl ->
       fprintf fmt "@[<hov 2>%a %a@]"
229
         print_ident rs.rs_name (print_list space (print_expr info)) tl
230

231
  and print_enode info fmt = function
232
233
    | Econst c ->
       fprintf fmt "%a" print_const c
234
    | Evar pvs ->
235
       (print_lident info) fmt (pv_name pvs)
236
    | Elet (pv, e1, e2) ->
Mário Pereira's avatar
Mário Pereira committed
237
       fprintf fmt "@[<hov 2>let @[%a@] =@ @[%a@]@] in@ %a"
238
         (print_lident info) (pv_name pv) (print_expr info) e1 (print_expr info) e2
239
240
    | Eabsurd ->
       fprintf fmt "assert false (* absurd *)"
241
242
243
244
245
246
    | Eapp (s, []) when rs_equal s rs_true ->
       fprintf fmt "true"
    | Eapp (s, []) when rs_equal s rs_false ->
       fprintf fmt "false"
    | Eapp (s, pvl) ->
       print_apply info fmt s pvl
247
    | Ematch (e, pl) ->
248
249
250
251
252
253
254
255
      fprintf fmt "@[begin match @[%a@] with@\n@[<hov>%a@] end@]"
        (print_expr info) e (print_list newline (print_branch info)) pl
    | Eassign [(rs, pv)] ->
      fprintf fmt "%a <-@ %a" print_ident rs.rs_name print_ident (pv_name pv)
    | Eif (e1, e2, e3) ->
      fprintf fmt
        "@[<hv>@[<hov 2>if@ %a@]@ then@;<1 2>@[%a@]@;<1 0>else@;<1 2>@[%a@]@]"
        (print_expr info) e1 (print_expr info) e2 (print_expr info) e3
256
    | Eblock [] ->
257
258
259
260
261
      fprintf fmt "()"
    | Eblock [e] ->
      print_expr info fmt e
    | Eblock el ->
      fprintf fmt "@[<hv>begin@;<1 2>@[%a@]@ end@]" (print_list semi (print_expr info)) el
262
    | _ -> (* TODO *) assert false
Mário Pereira's avatar
Mário Pereira committed
263

264
265
  and print_branch info fmt (p, e) =
    fprintf fmt "@[<hov 4>| %a ->@ %a@]" print_pat p (print_expr info) e
266

267
268
  and print_expr info fmt e =
    print_enode info fmt e.e_node
Mário Pereira's avatar
Mário Pereira committed
269

270
  let print_type_decl fmt its =
271
272
    let print_constr fmt (id, cs_args) =
      match cs_args with
273
274
275
276
277
278
279
      | [] ->
         fprintf fmt "@[<hov 4>| %a@]"
                 print_ident id (* FIXME: first letter must be uppercase
                                       -> print_uident *)
      | l ->
         fprintf fmt "@[<hov 4>| %a of %a@]"
                 print_ident id (* FIXME: print_uident *)
280
                 (print_list star (print_ty ~paren:false)) l in
281
282
283
284
    let print_field fmt (is_mutable, id, ty) =
      fprintf fmt "%s%a: %a;"
              (if is_mutable then "mutable " else "")
              print_ident id
285
              (print_ty ~paren:false) ty in
286
    let print_def fmt = function
287
288
289
290
291
292
293
294
295
296
297
      | None ->
        ()
      | Some (Ddata csl) ->
        fprintf fmt " =@\n%a" (print_list newline print_constr) csl
      | Some (Drecord fl) ->
        fprintf fmt " = %s{@\n%a@\n}"
          (if its.its_private then "private " else "")
          (print_list newline print_field) fl
      | Some (Dalias ty) ->
        fprintf fmt " =@ %a" (print_ty ~paren:false) ty
    in
298
    fprintf fmt "@[<hov 2>%s %a%a%a@]"
299
300
301
      (if true then "type" else "and") (* FIXME: mutual recursive types *)
      print_tv_args its.its_args
      print_ident its.its_name  (* FIXME: first letter must be lowercase
302
                                   -> print_lident *)
303
      print_def its.its_def
304

305
  let print_decl info fmt = function
306
    | Dlet (isrec, [rs, pvl, e]) ->
307
       fprintf fmt "@[<hov 2>%s %a@ %a@ =@ %a@]"
Mário Pereira's avatar
Mário Pereira committed
308
               (if isrec then "let rec" else "let")
309
310
               print_ident rs.rs_name
               (print_list space print_vs_arg) pvl
311
               (print_expr info) e;
Mário Pereira's avatar
Mário Pereira committed
312
313
       forget_vars pvl;
       forget_tvs ();
Mário Pereira's avatar
Mário Pereira committed
314
       fprintf fmt "@\n@\n"
315
316
317
    | Dtype dl ->
       print_list newline print_type_decl fmt dl;
       fprintf fmt "@\n@\n"
318
319
320
    | Dexn (xs, None) ->
       fprintf fmt "exception %a@\n@\n" print_ident xs.xs_name
    | Dexn (xs, Some t) ->
321
       fprintf fmt "@[<hov 2>exception %a of %a@]@\n@\n"
322
               print_ident xs.xs_name (print_ty ~paren:true) t
323
    | _ -> (* TODO *) assert false
Mário Pereira's avatar
Mário Pereira committed
324
325
326

end

327
328
329
330
331
332
333
334
335
336
337
338
339
let extract_module pargs ?old fmt ({mod_theory = th} as m) =
  ignore (pargs);
  ignore (old);
  ignore (m);
  let info = {
    info_syn          = pargs.Pdriver.syntax;
    info_convert      = pargs.Pdriver.converter;
    info_current_th   = th;
    info_current_mo   = Some m;
    info_th_known_map = th.th_known;
    info_mo_known_map = m.mod_known;
    info_fname        = None; (* TODO *)
  } in
340
  fprintf fmt "(*@\n%a@\n*)@\n@\n" print_module m;
Mário Pereira's avatar
Mário Pereira committed
341
342
343
  fprintf fmt
    "(* This file has been generated from Why3 module %a *)@\n@\n"
    Print.print_module_name m;
344
  let mdecls = Translate.module_ info m in
345
  print_list nothing (Print.print_decl info) fmt mdecls;
Mário Pereira's avatar
Mário Pereira committed
346
  fprintf fmt "@."
347

348

349
350
351
352
let fg ?fname m =
  let mod_name = m.Pmodule.mod_theory.Theory.th_name.id_string in
  match fname with
  | None   -> mod_name ^ ".ml"
353
354
355
356
357
358
359
360
  | Some f ->
    (* TODO: replace with Filename.remove_extension
     * after migration to OCaml 4.04+ *)
    let remove_extension s =
      try Filename.chop_extension s
      with Invalid_argument _ -> s
    in
    (remove_extension f) ^ "__" ^ mod_name ^ ".ml"
361

362
363
let () = Pdriver.register_printer "ocaml"
  ~desc:"printer for OCaml code" fg extract_module
364

365
366
(*
 * Local Variables:
367
 * compile-command: "make -C ../.. -j3 bin/why3extract.opt"
368
369
 * End:
 *)