Debian Codegraph @

plugins/extraction/ocaml.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (*s Production of Ocaml syntax. *)
12
13 open Pp
14 open CErrors
15 open Util
16 open Names
17 open ModPath
18 open Table
19 open Miniml
20 open Mlutil
21 open Modutil
22 open Common
23
24
25 (*s Some utility functions. *)
26
27 let pp_tvar id = str ("'" ^ Id.to_string id)
28
29 let pp_abst = function
30 | [] -> mt ()
31 | l ->
32 str "fun " ++ prlist_with_sep (fun () -> str " ") Id.print l ++
33 str " ->" ++ spc ()
34
35 let pp_parameters l =
36 (pp_boxed_tuple pp_tvar l ++ space_if (not (List.is_empty l)))
37
38 let pp_string_parameters l =
39 (pp_boxed_tuple str l ++ space_if (not (List.is_empty l)))
40
41 let pp_letin pat def body =
42 let fstline = str "let " ++ pat ++ str " =" ++ spc () ++ def in
43 hv 0 (hv 0 (hov 2 fstline ++ spc () ++ str "in") ++ spc () ++ hov 0 body)
44
45 (*s Ocaml renaming issues. *)
46
47 let keywords =
48 List.fold_right (fun s -> Id.Set.add (Id.of_string s))
49 [ "and"; "as"; "assert"; "begin"; "class"; "constraint"; "do"; "done";
50 "downto"; "effect"; "else"; "end"; "exception"; "external"; "false";
51 "for"; "fun"; "function"; "functor"; "if"; "in"; "include";
52 "inherit"; "initializer"; "lazy"; "let"; "match"; "method";
53 "module"; "mutable"; "new"; "nonrec"; "object"; "of"; "open"; "or";
54 "parser"; "private"; "rec"; "sig"; "struct"; "then"; "to"; "true";
55 "try"; "type"; "val"; "virtual"; "when"; "while"; "with"; "mod";
56 "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr" ; "unit" ; "_" ; "__" ]
57 Id.Set.empty
58
59 (* Note: do not shorten [str "foo" ++ fnl ()] into [str "foo\n"],
60 the '\n' character interacts badly with the Format boxing mechanism *)
61
62 let pp_open table dp = str ("open "^ string_of_modfile (State.get_table table) dp) ++ fnl ()
63
64 let pp_comment s = str "(* " ++ hov 0 s ++ str " *)"
65
66 let pp_header_comment = function
67 | None -> mt ()
68 | Some com -> pp_comment com ++ fnl2 ()
69
70 let then_nl pp = if Pp.ismt pp then mt () else pp ++ fnl ()
71
72 let pp_tdummy usf =
73 if usf.tdummy || usf.tunknown then str "type __ = Obj.t" ++ fnl () else mt ()
74
75 let pp_mldummy usf =
76 if usf.mldummy then
77 str "let __ = let rec f _ = Obj.repr f in Obj.repr f" ++ fnl ()
78 else mt ()
79
80 let preamble table _ comment used_modules usf =
81 pp_header_comment comment ++
82 then_nl (prlist (fun o -> pp_open table o) (DirPath.Set.elements used_modules)) ++
83 then_nl (pp_tdummy usf ++ pp_mldummy usf)
84
85 let sig_preamble table _ comment used_modules usf =
86 pp_header_comment comment ++
87 then_nl (prlist (fun o -> pp_open table o) (DirPath.Set.elements used_modules)) ++
88 then_nl (pp_tdummy usf)
89
90 (*s The pretty-printer for Ocaml syntax*)
91
92 (* Beware of the side-effects of [pp_global] and [pp_modname].
93 They are used to update table of content for modules. Many [let]
94 below should not be altered since they force evaluation order.
95 *)
96
97 let str_global_with_key table k key r =
98 if is_inline_custom r then find_custom r else Common.pp_global_with_key table k key r
99
100 let str_global table k r = str_global_with_key table k (repr_of_r r) r
101
102 let pp_global_with_key table k key r = str (str_global_with_key table k key r)
103
104 let pp_global table k r = str (str_global table k r)
105
106 let pp_global_name table k r = str (Common.pp_global table k r)
107
108 let pp_modname table mp = str (Common.pp_module table mp)
109
110 (* grammar from OCaml 4.06 manual, "Prefix and infix symbols" *)
111
112 let infix_symbols =
113 ['=' ; '<' ; '>' ; '@' ; '^' ; ';' ; '&' ; '+' ; '-' ; '*' ; '/' ; '$' ; '%' ]
114 let operator_chars =
115 [ '!' ; '$' ; '%' ; '&' ; '*' ; '+' ; '-' ; '.' ; '/' ; ':' ; '<' ; '=' ; '>' ; '?' ; '@' ; '^' ; '|' ; '~' ]
116
117 (* infix ops in OCaml, but disallowed by preceding grammar *)
118
119 let builtin_infixes =
120 [ "::" ; "," ]
121
122 let substring_all_opchars s start stop =
123 let rec check_char i =
124 if i >= stop then true
125 else
126 List.mem s.[i] operator_chars && check_char (i+1)
127 in
128 check_char start
129
130 let is_infix r =
131 is_inline_custom r &&
132 (let s = find_custom r in
133 let len = String.length s in
134 len >= 3 &&
135 (* parenthesized *)
136 (s.[0] == '(' && s.[len-1] == ')' &&
137 let inparens = String.trim (String.sub s 1 (len - 2)) in
138 let inparens_len = String.length inparens in
139 (* either, begins with infix symbol, any remainder is all operator chars *)
140 (List.mem inparens.[0] infix_symbols && substring_all_opchars inparens 1 inparens_len) ||
141 (* or, starts with #, at least one more char, all are operator chars *)
142 (inparens.[0] == '#' && inparens_len >= 2 && substring_all_opchars inparens 1 inparens_len) ||
143 (* or, is an OCaml built-in infix *)
144 (List.mem inparens builtin_infixes)))
145
146 let get_infix r =
147 let s = find_custom r in
148 String.sub s 1 (String.length s - 2)
149
150 let get_ind r = let open GlobRef in match r.glob with
151 | IndRef _ -> r
152 | ConstructRef (ind,_) -> { glob = IndRef ind; inst = r.inst }
153 | _ -> assert false
154
155 let kn_of_ind r = let open GlobRef in match r.glob with
156 | IndRef (kn,_) -> MutInd.user kn
157 | _ -> assert false
158
159 let pp_one_field table r i = function
160 | Some r' -> pp_global_with_key table Term (kn_of_ind (get_ind r)) r'
161 | None -> pp_global table Type (get_ind r) ++ str "__" ++ int i
162
163 let pp_field table r fields i = pp_one_field table r i (List.nth fields i)
164
165 let pp_fields table r fields = List.map_i (pp_one_field table r) 0 fields
166
167 (*s Pretty-printing of types. [par] is a boolean indicating whether parentheses
168 are needed or not. *)
169
170 let pp_type table par vl t =
171 let rec pp_rec par = function
172 | Tmeta _ | Tvar' _ | Taxiom -> assert false
173 | Tvar i -> (try pp_tvar (List.nth vl (pred i))
174 with Failure _ -> (str "'a" ++ int i))
175 | Tglob (r,[a1;a2]) when is_infix r ->
176 pp_par par (pp_rec true a1 ++ str (get_infix r) ++ pp_rec true a2)
177 | Tglob (r,[]) -> pp_global table Type r
178 | Tglob (gr,l)
179 when not (keep_singleton ()) && Rocqlib.check_ref sig_type_name gr.glob ->
180 pp_tuple_light pp_rec l
181 | Tglob (r,l) ->
182 pp_tuple_light pp_rec l ++ spc () ++ pp_global table Type r
183 | Tarr (t1,t2) ->
184 pp_par par
185 (pp_rec true t1 ++ spc () ++ str "->" ++ spc () ++ pp_rec false t2)
186 | Tdummy _ -> str "__"
187 | Tunknown -> str "__"
188 in
189 hov 0 (pp_rec par t)
190
191 (*s Pretty-printing of expressions. [par] indicates whether
192 parentheses are needed or not. [env] is the list of names for the
193 de Bruijn variables. [args] is the list of collected arguments
194 (already pretty-printed). *)
195
196 let is_bool_patt p s =
197 try
198 let r = match p with
199 | Pusual r -> r
200 | Pcons (r,[]) -> r
201 | _ -> raise Not_found
202 in
203 String.equal (find_custom r) s
204 with Not_found -> false
205
206
207 let is_ifthenelse = function
208 | [|([],p1,_);([],p2,_)|] -> is_bool_patt p1 "true" && is_bool_patt p2 "false"
209 | _ -> false
210
211 let expr_needs_par = function
212 | MLlam _ -> true
213 | MLcase (_,_,[|_|]) -> false
214 | MLcase (_,_,pv) -> not (is_ifthenelse pv)
215 | _ -> false
216
217 let rec pp_expr table par env args =
218 let apply st = pp_apply st par args
219 and apply2 st = pp_apply2 st par args in
220 function
221 | MLrel n ->
222 let id = get_db_name n env in
223 (* Try to survive to the occurrence of a Dummy rel.
224 TODO: we should get rid of this hack (cf. #592) *)
225 let id = if Id.equal id dummy_name then Id.of_string "__" else id in
226 apply (Id.print id)
227 | MLapp (f,args') ->
228 let stl = List.map (pp_expr table true env []) args' in
229 pp_expr table par env (stl @ args) f
230 | MLlam _ as a ->
231 let fl,a' = collect_lams a in
232 let fl = List.map id_of_mlid fl in
233 let fl,env' = push_vars fl env in
234 let st = pp_abst (List.rev fl) ++ pp_expr table false env' [] a' in
235 apply2 st
236 | MLletin (id,a1,a2) ->
237 let i,env' = push_vars [id_of_mlid id] env in
238 let pp_id = Id.print (List.hd i)
239 and pp_a1 = pp_expr table false env [] a1
240 and pp_a2 = pp_expr table (not par && expr_needs_par a2) env' [] a2 in
241 hv 0 (apply2 (pp_letin pp_id pp_a1 pp_a2))
242 | MLglob r -> apply (pp_global table Term r)
243 | MLfix (i,ids,defs) ->
244 let ids',env' = push_vars (List.rev (Array.to_list ids)) env in
245 pp_fix table par env' i (Array.of_list (List.rev ids'),defs) args
246 | MLexn s ->
247 (* An [MLexn] may be applied, but I don't really care. *)
248 pp_par par (str "assert false" ++ spc () ++ str ("(* "^s^" *)"))
249 | MLdummy k ->
250 (* An [MLdummy] may be applied, but I don't really care. *)
251 (match msg_of_implicit k with
252 | "" -> str "__"
253 | s -> str "__" ++ spc () ++ str ("(* "^s^" *)"))
254 | MLmagic a ->
255 pp_apply (str "Obj.magic") par (pp_expr table true env [] a :: args)
256 | MLaxiom s ->
257 pp_par par (str "failwith \"AXIOM TO BE REALIZED (" ++ str s ++ str ")\"")
258 | MLcons (_,r,a) as c ->
259 assert (List.is_empty args);
260 begin match a with
261 | _ when is_native_char c -> pp_native_char c
262 | _ when is_native_string c -> pp_native_string c
263 | [a1;a2] when is_infix r ->
264 let pp = pp_expr table true env [] in
265 pp_par par (pp a1 ++ str (get_infix r) ++ pp a2)
266 | _ when is_coinductive (State.get_table table) r ->
267 let ne = not (List.is_empty a) in
268 let tuple = space_if ne ++ pp_tuple (pp_expr table true env []) a in
269 pp_par par (str "lazy " ++ pp_par ne (pp_global table Cons r ++ tuple))
270 | [] -> pp_global table Cons r
271 | _ ->
272 let fds = get_record_fields (State.get_table table) r in
273 if not (List.is_empty fds) then
274 pp_record_pat (pp_fields table r fds, List.map (pp_expr table true env []) a)
275 else
276 let tuple = pp_tuple (pp_expr table true env []) a in
277 if String.is_empty (str_global table Cons r) (* hack Extract Inductive prod *)
278 then tuple
279 else pp_par par (pp_global table Cons r ++ spc () ++ tuple)
280 end
281 | MLtuple l ->
282 assert (List.is_empty args);
283 pp_boxed_tuple (pp_expr table true env []) l
284 | MLcase (_, t, pv) when is_custom_match pv ->
285 if not (is_regular_match pv) then
286 user_err Pp.(str "Cannot mix yet user-given match and general patterns.");
287 let mkfun (ids,_,e) =
288 if not (List.is_empty ids) then named_lams (List.rev ids) e
289 else dummy_lams (ast_lift 1 e) 1
290 in
291 let pp_branch tr = pp_expr table true env [] (mkfun tr) ++ fnl () in
292 let inner =
293 str (find_custom_match pv) ++ fnl () ++
294 prvect pp_branch pv ++
295 pp_expr table true env [] t
296 in
297 apply2 (hov 2 inner)
298 | MLcase (typ, t, pv) ->
299 let head =
300 if not (is_coinductive_type (State.get_table table) typ) then pp_expr table false env [] t
301 else (str "Lazy.force" ++ spc () ++ pp_expr table true env [] t)
302 in
303 (* First, can this match be printed as a mere record projection ? *)
304 (try pp_record_proj table par env typ t pv args
305 with Impossible ->
306 (* Second, can this match be printed as a let-in ? *)
307 if Int.equal (Array.length pv) 1 then
308 let s1,s2 = pp_one_pat table env pv.(0) in
309 hv 0 (apply2 (pp_letin s1 head s2))
310 else
311 (* Third, can this match be printed as [if ... then ... else] ? *)
312 (try apply2 (pp_ifthenelse table env head pv)
313 with Not_found ->
314 (* Otherwise, standard match *)
315 apply2
316 (v 0 (str "match " ++ head ++ str " with" ++ fnl () ++
317 pp_pat table env pv))))
318 | MLuint i ->
319 assert (args=[]);
320 str "(" ++ str (Uint63.compile i) ++ str ")"
321 | MLfloat f ->
322 assert (args=[]);
323 str "(" ++ str (Float64.compile f) ++ str ")"
324 | MLstring s ->
325 assert (args=[]);
326 str "(" ++ str (Pstring.compile s) ++ str ")"
327 | MLparray(t,def) ->
328 assert (args=[]);
329 let tuple = pp_array (pp_expr table true env []) (Array.to_list t) in
330 let def = pp_expr table true env [] def in
331 str "(ExtrNative.of_array [|" ++ tuple ++ str "|]" ++ spc () ++ def ++ str")"
332
333
334 and pp_record_proj table par env typ t pv args =
335 (* Can a match be printed as a mere record projection ? *)
336 let fields = record_fields_of_type (State.get_table table) typ in
337 if List.is_empty fields then raise Impossible;
338 if not (Int.equal (Array.length pv) 1) then raise Impossible;
339 if has_deep_pattern pv then raise Impossible;
340 let (ids,pat,body) = pv.(0) in
341 let n = List.length ids in
342 let no_patvar a = not (List.exists (ast_occurs_itvl 1 n) a) in
343 let rel_i,a = match body with
344 | MLrel i | MLmagic(MLrel i) when i <= n -> i,[]
345 | MLapp(MLrel i, a) | MLmagic(MLapp(MLrel i, a))
346 | MLapp(MLmagic(MLrel i), a) when i<=n && no_patvar a -> i,a
347 | _ -> raise Impossible
348 in
349 let magic =
350 match body with MLmagic _ | MLapp(MLmagic _, _) -> true | _ -> false
351 in
352 let rec lookup_rel i idx = function
353 | Prel j :: l -> if Int.equal i j then idx else lookup_rel i (idx+1) l
354 | Pwild :: l -> lookup_rel i (idx+1) l
355 | _ -> raise Impossible
356 in
357 let r,idx = match pat with
358 | Pusual r -> r, n-rel_i
359 | Pcons (r,l) -> r, lookup_rel rel_i 0 l
360 | _ -> raise Impossible
361 in
362 if is_infix r then raise Impossible;
363 let env' = snd (push_vars (List.rev_map id_of_mlid ids) env) in
364 let pp_args = (List.map (pp_expr table true env' []) a) @ args in
365 let pp_head = pp_expr table true env [] t ++ str "." ++ pp_field table r fields idx
366 in
367 if magic then
368 pp_apply (str "Obj.magic") par (pp_head :: pp_args)
369 else
370 pp_apply pp_head par pp_args
371
372 and pp_record_pat (fields, args) =
373 str "{ " ++
374 prlist_with_sep (fun () -> str ";" ++ spc ())
375 (fun (f,a) -> f ++ str " =" ++ spc () ++ a)
376 (List.combine fields args) ++
377 str " }"
378
379 and pp_cons_pat table r ppl =
380 if is_infix r && Int.equal (List.length ppl) 2 then
381 List.hd ppl ++ str (get_infix r) ++ List.hd (List.tl ppl)
382 else
383 let fields = get_record_fields (State.get_table table) r in
384 if not (List.is_empty fields) then pp_record_pat (pp_fields table r fields, ppl)
385 else if String.is_empty (str_global table Cons r) then
386 pp_boxed_tuple identity ppl (* Hack Extract Inductive prod *)
387 else
388 pp_global table Cons r ++ space_if (not (List.is_empty ppl)) ++ pp_boxed_tuple identity ppl
389
390 and pp_gen_pat table ids env = function
391 | Pcons (r, l) -> pp_cons_pat table r (List.map (pp_gen_pat table ids env) l)
392 | Pusual r -> pp_cons_pat table r (List.map Id.print ids)
393 | Ptuple l -> pp_boxed_tuple (pp_gen_pat table ids env) l
394 | Pwild -> str "_"
395 | Prel n -> Id.print (get_db_name n env)
396
397 and pp_ifthenelse table env expr pv = match pv with
398 | [|([],tru,the);([],fal,els)|] when
399 (is_bool_patt tru "true") && (is_bool_patt fal "false")
400 ->
401 hv 0 (hov 2 (str "if " ++ expr) ++ spc () ++
402 hov 2 (str "then " ++
403 hov 2 (pp_expr table (expr_needs_par the) env [] the)) ++ spc () ++
404 hov 2 (str "else " ++
405 hov 2 (pp_expr table (expr_needs_par els) env [] els)))
406 | _ -> raise Not_found
407
408 and pp_one_pat table env (ids,p,t) =
409 let ids',env' = push_vars (List.rev_map id_of_mlid ids) env in
410 pp_gen_pat table (List.rev ids') env' p,
411 pp_expr table (expr_needs_par t) env' [] t
412
413 and pp_pat table env pv =
414 prvecti
415 (fun i x ->
416 let s1,s2 = pp_one_pat table env x in
417 hv 2 (hov 4 (str "| " ++ s1 ++ str " ->") ++ spc () ++ hov 2 s2) ++
418 if Int.equal i (Array.length pv - 1) then mt () else fnl ())
419 pv
420
421 and pp_function table env t =
422 let bl,t' = collect_lams t in
423 let bl,env' = push_vars (List.map id_of_mlid bl) env in
424 match t' with
425 | MLcase(Tglob(r,_),MLrel 1,pv) when
426 not (is_coinductive (State.get_table table) r) && List.is_empty (get_record_fields (State.get_table table) r) &&
427 not (is_custom_match pv) ->
428 if not (ast_occurs 1 (MLcase(Tunknown,MLaxiom "",pv))) then
429 pr_binding (List.rev (List.tl bl)) ++
430 str " = function" ++ fnl () ++
431 v 0 (pp_pat table env' pv)
432 else
433 pr_binding (List.rev bl) ++
434 str " = match " ++ Id.print (List.hd bl) ++ str " with" ++ fnl () ++
435 v 0 (pp_pat table env' pv)
436 | _ ->
437 pr_binding (List.rev bl) ++
438 str " =" ++ fnl () ++ str " " ++
439 hov 2 (pp_expr table false env' [] t')
440
441 (*s names of the functions ([ids]) are already pushed in [env],
442 and passed here just for convenience. *)
443
444 and pp_fix table par env i (ids,bl) args =
445 pp_par par
446 (v 0 (str "let rec " ++
447 prvect_with_sep
448 (fun () -> fnl () ++ str "and ")
449 (fun (fi,ti) -> Id.print fi ++ pp_function table env ti)
450 (Array.map2 (fun id b -> (id,b)) ids bl) ++
451 fnl () ++
452 hov 2 (str "in " ++ pp_apply (Id.print ids.(i)) false args)))
453
454 (* Ad-hoc double-newline in v boxes, with enough negative whitespace
455 to avoid indenting the intermediate blank line *)
456
457 let cut2 () = brk (0,-100000) ++ brk (0,0)
458
459 let pp_val table e typ =
460 hov 4 (str "(** val " ++ e ++ str " :" ++ spc () ++ pp_type table false [] typ ++
461 str " **)") ++ cut2 ()
462
463 (*s Pretty-printing of [Dfix] *)
464
465 let pp_Dfix table (rv,c,t) =
466 let names = Array.map
467 (fun r -> if is_inline_custom r then mt () else pp_global_name table Term r) rv
468 in
469 let rec pp init i =
470 if i >= Array.length rv then mt ()
471 else
472 let void = is_inline_custom rv.(i) ||
473 (not (is_custom rv.(i)) &&
474 match c.(i) with MLexn "UNUSED" -> true | _ -> false)
475 in
476 if void then pp init (i+1)
477 else
478 let def =
479 if is_custom rv.(i) then str " = " ++ str (find_custom rv.(i))
480 else pp_function table (empty_env table ()) c.(i)
481 in
482 (if init then mt () else cut2 ()) ++
483 pp_val table names.(i) t.(i) ++
484 str (if init then "let rec " else "and ") ++ names.(i) ++ def ++
485 pp false (i+1)
486 in pp true 0
487
488 (*s Pretty-printing of inductive types declaration. *)
489
490 let pp_equiv table param_list name inst = function
491 | NoEquiv, _ -> mt ()
492 | Equiv kn, i ->
493 let r = { glob = GlobRef.IndRef (MutInd.make1 kn, i); inst } in
494 str " = " ++ pp_parameters param_list ++ pp_global table Type r
495 | RenEquiv ren, _ ->
496 str " = " ++ pp_parameters param_list ++ str (ren^".") ++ name
497
498
499 let pp_one_ind table prefix inst ip_equiv pl name cnames ctyps =
500 let pl = rename_tvars keywords pl in
501 let pp_constructor i typs =
502 (if Int.equal i 0 then mt () else fnl ()) ++
503 hov 3 (str "| " ++ cnames.(i) ++
504 (if List.is_empty typs then mt () else str " of ") ++
505 prlist_with_sep
506 (fun () -> spc () ++ str "* ") (pp_type table true pl) typs)
507 in
508 pp_parameters pl ++ str prefix ++ name ++
509 pp_equiv table pl name inst ip_equiv ++ str " =" ++
510 if Int.equal (Array.length ctyps) 0 then str " |"
511 else fnl () ++ v 0 (prvecti pp_constructor ctyps)
512
513 let pp_logical_ind packet =
514 pp_comment (Id.print packet.ip_typename ++ str " : logical inductive") ++
515 fnl () ++
516 pp_comment (str "with constructors : " ++
517 prvect_with_sep spc Id.print packet.ip_consnames) ++
518 fnl ()
519
520 let pp_singleton table packet =
521 let name = pp_global_name table Type packet.ip_typename_ref in
522 let l = rename_tvars keywords packet.ip_vars in
523 hov 2 (str "type " ++ pp_parameters l ++ name ++ str " =" ++ spc () ++
524 pp_type table false l (List.hd packet.ip_types.(0)) ++ fnl () ++
525 pp_comment (str "singleton inductive, whose constructor was " ++
526 Id.print packet.ip_consnames.(0)))
527
528 let pp_record table fields ip_equiv packet =
529 let ind = packet.ip_typename_ref in
530 let name = pp_global_name table Type ind in
531 let fieldnames = pp_fields table ind fields in
532 let l = List.combine fieldnames packet.ip_types.(0) in
533 let pl = rename_tvars keywords packet.ip_vars in
534 str "type " ++ pp_parameters pl ++ name ++
535 pp_equiv table pl name ind.inst ip_equiv ++ str " = { "++
536 hov 0 (prlist_with_sep (fun () -> str ";" ++ spc ())
537 (fun (p,t) -> p ++ str " : " ++ pp_type table true pl t) l)
538 ++ str " }"
539
540 let pp_coind pl name =
541 let pl = rename_tvars keywords pl in
542 pp_parameters pl ++ name ++ str " = " ++
543 pp_parameters pl ++ str "__" ++ name ++ str " Lazy.t" ++
544 fnl() ++ str "and "
545
546 let pp_ind table co ind =
547 let prefix = if co then "__" else "" in
548 let initkwd = str "type " in
549 let nextkwd = fnl () ++ str "and " in
550 let names =
551 Array.mapi (fun i p -> if p.ip_logical then mt () else
552 pp_global_name table Type p.ip_typename_ref)
553 ind.ind_packets
554 in
555 let cnames =
556 Array.mapi
557 (fun i p -> if p.ip_logical then [||] else
558 Array.mapi (fun j _ -> pp_global table Cons p.ip_consnames_ref.(j))
559 p.ip_types)
560 ind.ind_packets
561 in
562 let rec pp i kwd =
563 if i >= Array.length ind.ind_packets then mt ()
564 else
565 let ip = ind.ind_packets.(i).ip_typename_ref in
566 let ip_equiv = ind.ind_equiv, i in
567 let p = ind.ind_packets.(i) in
568 if is_custom ip then pp (i+1) kwd
569 else if p.ip_logical then pp_logical_ind p ++ pp (i+1) kwd
570 else
571 let inst = p.ip_typename_ref.inst in
572 kwd ++ (if co then pp_coind p.ip_vars names.(i) else mt ()) ++
573 pp_one_ind table prefix inst ip_equiv p.ip_vars names.(i) cnames.(i) p.ip_types ++
574 pp (i+1) nextkwd
575 in
576 pp 0 initkwd
577
578
579 (*s Pretty-printing of a declaration. *)
580
581 let pp_mind table i =
582 match i.ind_kind with
583 | Singleton -> pp_singleton table i.ind_packets.(0)
584 | Coinductive -> pp_ind table true i
585 | Record fields -> pp_record table fields (i.ind_equiv,0) i.ind_packets.(0)
586 | Standard -> pp_ind table false i
587
588 let pp_decl table = function
589 | Dtype (r,_,_) when is_inline_custom r -> mt ()
590 | Dterm (r,_,_) when is_inline_custom r -> mt ()
591 | Dind i -> pp_mind table i
592 | Dtype (r, l, t) ->
593 let name = pp_global_name table Type r in
594 let l = rename_tvars keywords l in
595 let ids, def =
596 try
597 let ids,s = find_type_custom r in
598 pp_string_parameters ids, str " =" ++ spc () ++ str s
599 with Not_found ->
600 pp_parameters l,
601 if t == Taxiom then str " (* AXIOM TO BE REALIZED *)"
602 else str " =" ++ spc () ++ pp_type table false l t
603 in
604 hov 2 (str "type " ++ ids ++ name ++ def)
605 | Dterm (r, a, t) ->
606 let def =
607 (* If it it is an foreign custom, set the def to ': type = <quote>foreign_fun_name<quote> '.
608 TODO: I'm not sure, but could we use pp_native_string for quoting the custom name of r?
609 *)
610 if is_foreign_custom r then str ": " ++ pp_type table false [] t ++ str " = \"" ++ str (find_custom r) ++ str "\""
611 (* Otherwise, check if it is a regular custom term. *)
612 else if is_custom r then str (" = " ^ find_custom r)
613 else pp_function table (empty_env table ()) a
614 in
615 let name = pp_global_name table Term r in
616 (* If it is an foreign custom, begin the expression with 'external'/'foreign' instead of 'let' *)
617 let expr_begin = if is_foreign_custom r then str "external " else str "let " in
618 (* Make sure that a callback registration is synthesised, if specified for that term. *)
619 let callback_def =
620 try
621 let alias =
622 match find_callback r with
623 | Some s -> str s
624 | None -> name (* No alias specified, use the qualid name. *)
625 in
626 cut2 () ++ hov 0 ((str "let () = Stdlib.Callback.register \"") ++ alias ++ (str "\" ") ++ name)
627 with Not_found -> (* No callback registration specified for qualid. *)
628 mt()
629 in pp_val table name t ++ hov 0 (expr_begin ++ name ++ def ++ mt ()) ++ callback_def;
630
631 | Dfix (rv,defs,typs) ->
632 pp_Dfix table (rv,defs,typs)
633
634 let pp_spec table = function
635 | Sval (r,_) when is_inline_custom r -> mt ()
636 | Stype (r,_,_) when is_inline_custom r -> mt ()
637 | Sind i -> pp_mind table i
638 | Sval (r,t) ->
639 let def = pp_type table false [] t in
640 let name = pp_global_name table Term r in
641 hov 2 (str "val " ++ name ++ str " :" ++ spc () ++ def)
642 | Stype (r,vl,ot) ->
643 let name = pp_global_name table Type r in
644 let l = rename_tvars keywords vl in
645 let ids, def =
646 try
647 let ids, s = find_type_custom r in
648 pp_string_parameters ids, str " =" ++ spc () ++ str s
649 with Not_found ->
650 let ids = pp_parameters l in
651 match ot with
652 | None -> ids, mt ()
653 | Some Taxiom -> ids, str " (* AXIOM TO BE REALIZED *)"
654 | Some t -> ids, str " =" ++ spc () ++ pp_type table false l t
655 in
656 hov 2 (str "type " ++ ids ++ name ++ def)
657
658 let rec pp_specif table = function
659 | (_,Spec (Sval _ as s)) -> pp_spec table s
660 | (l,Spec s) ->
661 (match Common.State.get_duplicate table (State.get_top_visible_mp table) l with
662 | None -> pp_spec table s
663 | Some ren ->
664 hov 1 (str ("module "^ren^" : sig") ++ fnl () ++ pp_spec table s) ++
665 fnl () ++ str "end" ++ fnl () ++
666 str ("include module type of struct include "^ren^" end"))
667 | (l,Smodule mt) ->
668 let def = pp_module_type table [] mt in
669 let name = pp_modname table (MPdot (State.get_top_visible_mp table, l)) in
670 hov 1 (str "module " ++ name ++ str " :" ++ fnl () ++ def) ++
671 (match Common.State.get_duplicate table (State.get_top_visible_mp table) l with
672 | None -> Pp.mt ()
673 | Some ren ->
674 fnl () ++
675 hov 1 (str ("module "^ren^" :") ++ spc () ++
676 str "module type of struct include " ++ name ++ str " end"))
677 | (l,Smodtype mt) ->
678 let def = pp_module_type table [] mt in
679 let name = pp_modname table (MPdot (State.get_top_visible_mp table, l)) in
680 hov 1 (str "module type " ++ name ++ str " =" ++ fnl () ++ def) ++
681 (match Common.State.get_duplicate table (State.get_top_visible_mp table) l with
682 | None -> Pp.mt ()
683 | Some ren -> fnl () ++ str ("module type "^ren^" = ") ++ name)
684
685 and pp_module_type table params = function
686 | MTident kn ->
687 pp_modname table kn
688 | MTfunsig (mbid, mt, mt') ->
689 let typ = pp_module_type table [] mt in
690 let name = pp_modname table (MPbound mbid) in
691 let def = pp_module_type table (mbid :: params) mt' in
692 str "functor (" ++ name ++ str ":" ++ typ ++ str ") ->" ++ fnl () ++ def
693 | MTsig (mp, sign) ->
694 let l = State.with_visibility table mp params begin fun table ->
695 let try_pp_specif l x =
696 let px = pp_specif table x in
697 if Pp.ismt px then l else px::l
698 in
699 (* We cannot use fold_right here due to side effects in pp_specif *)
700 let l = List.fold_left try_pp_specif [] sign in
701 List.rev l
702 end in
703 str "sig" ++ fnl () ++
704 (if List.is_empty l then mt ()
705 else
706 v 1 (str " " ++ prlist_with_sep cut2 identity l) ++ fnl ())
707 ++ str "end"
708 | MTwith(mt,ML_With_type (rlv, idl, vl, typ)) ->
709 let ids = pp_parameters (rename_tvars keywords vl) in
710 let mp_mt = msid_of_mt mt in
711 let l,idl' = List.sep_last idl in
712 let mp_w =
713 List.fold_left (fun mp l -> MPdot(mp, l)) mp_mt idl'
714 in
715 let r = { glob = GlobRef.ConstRef (Constant.make2 mp_w l); inst = rlv } in
716 let pp_w = State.with_visibility table mp_mt [] begin fun table ->
717 str " with type " ++ ids ++ pp_global table Type r
718 end in
719 pp_module_type table [] mt ++ pp_w ++ str " = " ++ pp_type table false vl typ
720 | MTwith(mt,ML_With_module(idl,mp)) ->
721 let mp_mt = msid_of_mt mt in
722 let mp_w =
723 List.fold_left (fun mp id -> MPdot(mp, id)) mp_mt idl
724 in
725 let pp_w = State.with_visibility table mp_mt [] begin fun table ->
726 str " with module " ++ pp_modname table mp_w
727 end in
728 pp_module_type table [] mt ++ pp_w ++ str " = " ++ pp_modname table mp
729
730 let is_short = function MEident _ | MEapply _ -> true | _ -> false
731
732 let rec pp_structure_elem table = function
733 | (l,SEdecl d) ->
734 (match Common.State.get_duplicate table (State.get_top_visible_mp table) l with
735 | None -> pp_decl table d
736 | Some ren ->
737 v 1 (str ("module "^ren^" = struct") ++ fnl () ++ pp_decl table d) ++
738 fnl () ++ str "end" ++ fnl () ++ str ("include "^ren))
739 | (l,SEmodule m) ->
740 let typ =
741 (* virtual printing of the type, in order to have a correct mli later*)
742 if Common.State.get_phase table == Pre then
743 str ": " ++ pp_module_type table [] m.ml_mod_type
744 else mt ()
745 in
746 let def = pp_module_expr table [] m.ml_mod_expr in
747 let name = pp_modname table (MPdot (State.get_top_visible_mp table, l)) in
748 hov 1
749 (str "module " ++ name ++ typ ++ str " =" ++
750 (if is_short m.ml_mod_expr then spc () else fnl ()) ++ def) ++
751 (match Common.State.get_duplicate table (State.get_top_visible_mp table) l with
752 | Some ren -> fnl () ++ str ("module "^ren^" = ") ++ name
753 | None -> mt ())
754 | (l,SEmodtype m) ->
755 let def = pp_module_type table [] m in
756 let name = pp_modname table (MPdot (State.get_top_visible_mp table, l)) in
757 hov 1 (str "module type " ++ name ++ str " =" ++ fnl () ++ def) ++
758 (match Common.State.get_duplicate table (State.get_top_visible_mp table) l with
759 | None -> mt ()
760 | Some ren -> fnl () ++ str ("module type "^ren^" = ") ++ name)
761
762 and pp_module_expr table params = function
763 | MEident mp -> pp_modname table mp
764 | MEapply (me, me') ->
765 pp_module_expr table [] me ++ str "(" ++ pp_module_expr table [] me' ++ str ")"
766 | MEfunctor (mbid, mt, me) ->
767 let name = pp_modname table (MPbound mbid) in
768 let typ = pp_module_type table [] mt in
769 let def = pp_module_expr table (mbid :: params) me in
770 str "functor (" ++ name ++ str ":" ++ typ ++ str ") ->" ++ fnl () ++ def
771 | MEstruct (mp, sel) ->
772 let l = State.with_visibility table mp params begin fun table ->
773 let try_pp_structure_elem l x =
774 let px = pp_structure_elem table x in
775 if Pp.ismt px then l else px::l
776 in
777 (* We cannot use fold_right here due to side effects in pp_structure_elem *)
778 let l = List.fold_left try_pp_structure_elem [] sel in
779 List.rev l
780 end in
781 str "struct" ++ fnl () ++
782 (if List.is_empty l then mt ()
783 else
784 v 1 (str " " ++ prlist_with_sep cut2 identity l) ++ fnl ())
785 ++ str "end"
786
787 let rec prlist_sep_nonempty sep f = function
788 | [] -> mt ()
789 | [h] -> f h
790 | h::t ->
791 let e = f h in
792 let r = prlist_sep_nonempty sep f t in
793 if Pp.ismt e then r
794 else e ++ sep () ++ r
795
796 let do_struct table f s =
797 let modular = State.get_modular table in
798 let p =
799 (* for monolithic extraction, we try to simulate the unavailability
800 of [MPfile] in names by artificially nesting these [MPfile] *)
801 if modular then
802 let ppl (mp, sel) = State.with_visibility table mp [] begin fun table ->
803 prlist_sep_nonempty cut2 (fun s -> f table s) sel
804 end in
805 List.map_left ppl s
806 else
807 let rec eval table = function
808 | [] -> []
809 | (mp, sel) :: l ->
810 State.with_visibility table mp [] begin fun table ->
811 let h = prlist_sep_nonempty cut2 (fun s -> f table s) sel in
812 h :: eval table l
813 end
814 in
815 eval table s
816 in
817 let p = prlist_sep_nonempty cut2 (fun x -> x) p in
818 v 0 p ++ fnl ()
819
820 let pp_struct table s = do_struct table (fun table e -> pp_structure_elem table e) s
821
822 let pp_signature table s = do_struct table (fun table e -> pp_specif table e) s
823
824 let file_naming state mp = file_of_modfile (State.get_table state) mp
825
826 let ocaml_descr = {
827 keywords = keywords;
828 file_suffix = ".ml";
829 file_naming = file_naming;
830 preamble = preamble;
831 pp_struct = pp_struct;
832 sig_suffix = Some ".mli";
833 sig_preamble = sig_preamble;
834 pp_sig = pp_signature;
835 pp_decl = pp_decl;
836 }