Debian Codegraph @

plugins/extraction/common.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 open Pp
12 open Util
13 open Names
14 open ModPath
15 open Namegen
16 open Nameops
17 open Table
18 open Miniml
19 open Mlutil
20
21 let ascii_of_id id =
22 let s = Id.to_string id in
23 for i = 0 to String.length s - 2 do
24 if s.[i] == '_' && s.[i+1] == '_' then warning_id s
25 done;
26 Unicode.ascii_of_ident s
27
28 let is_mp_bound = function MPbound _ -> true | _ -> false
29
30 (*s Some pretty-print utility functions. *)
31
32 let pp_par par st = if par then str "(" ++ st ++ str ")" else st
33
34 (** [pp_apply] : a head part applied to arguments, possibly with parenthesis *)
35
36 let pp_apply st par args = match args with
37 | [] -> st
38 | _ -> hov 2 (pp_par par (st ++ spc () ++ prlist_with_sep spc identity args))
39
40 (** Same as [pp_apply], but with also protection of the head by parenthesis *)
41
42 let pp_apply2 st par args =
43 let par' = not (List.is_empty args) || par in
44 pp_apply (pp_par par' st) par args
45
46 let pr_binding = function
47 | [] -> mt ()
48 | l -> str " " ++ prlist_with_sep (fun () -> str " ") Id.print l
49
50 let pp_tuple_light f = function
51 | [] -> mt ()
52 | [x] -> f true x
53 | l ->
54 pp_par true (prlist_with_sep (fun () -> str "," ++ spc ()) (f false) l)
55
56 let pp_tuple f = function
57 | [] -> mt ()
58 | [x] -> f x
59 | l -> pp_par true (prlist_with_sep (fun () -> str "," ++ spc ()) f l)
60
61 let pp_boxed_tuple f = function
62 | [] -> mt ()
63 | [x] -> f x
64 | l -> pp_par true (hov 0 (prlist_with_sep (fun () -> str "," ++ spc ()) f l))
65
66 let pp_array f = function
67 | [] -> mt ()
68 | [x] -> f x
69 | l -> pp_par true (prlist_with_sep (fun () -> str ";" ++ spc ()) f l)
70
71 (** By default, in module Format, you can do horizontal placing of blocks
72 even if they include newlines, as long as the number of chars in the
73 blocks is less that a line length. To avoid this awkward situation,
74 we attach a big virtual size to [fnl] newlines. *)
75
76 (* EG: This looks quite suspicious... but beware of bugs *)
77 (* let fnl () = stras (1000000,"") ++ fnl () *)
78 let fnl () = fnl ()
79
80 let fnl2 () = fnl () ++ fnl ()
81
82 let space_if = function true -> str " " | false -> mt ()
83
84 let begins_with s prefix =
85 let len = String.length prefix in
86 String.length s >= len && String.equal (String.sub s 0 len) prefix
87
88 let begins_with_CoqXX s =
89 let n = String.length s in
90 n >= 4 && s.[0] == 'C' && s.[1] == 'o' && s.[2] == 'q' &&
91 let i = ref 3 in
92 try while !i < n do
93 match s.[!i] with
94 | '_' -> i:=n (*Stop*)
95 | '0'..'9' -> incr i
96 | _ -> raise Not_found
97 done; true
98 with Not_found -> false
99
100 let unquote s =
101 if lang () != Scheme then s
102 else String.map (fun c -> if c == '\'' then '~' else c) s
103
104 let rec qualify delim = function
105 | [] -> assert false
106 | [s] -> s
107 | ""::l -> qualify delim l
108 | s::l -> s^delim^(qualify delim l)
109
110 let dottify = qualify "."
111 let pseudo_qualify = qualify "__"
112
113 (*s Uppercase/lowercase renamings. *)
114
115 let is_upper s = match s.[0] with 'A' .. 'Z' -> true | _ -> false
116 let is_lower s = match s.[0] with 'a' .. 'z' | '_' -> true | _ -> false
117
118 let lowercase_id id = Id.of_string (String.uncapitalize_ascii (ascii_of_id id))
119 let uppercase_id id =
120 let s = ascii_of_id id in
121 assert (not (String.is_empty s));
122 if s.[0] == '_' then Id.of_string ("Coq_"^s)
123 else Id.of_string (String.capitalize_ascii s)
124
125 type kind = Term | Type | Cons | Mod
126
127 module KOrd =
128 struct
129 type t = kind * string
130 let compare (k1, s1) (k2, s2) =
131 let c = Stdlib.compare k1 k2 (* OK *) in
132 if c = 0 then String.compare s1 s2
133 else c
134 end
135
136 module KMap = CMap.Make(KOrd)
137
138 let upperkind = function
139 | Type -> lang () == Haskell
140 | Term -> false
141 | Cons | Mod -> true
142
143 let kindcase_id k id =
144 if upperkind k then uppercase_id id else lowercase_id id
145
146 (*s de Bruijn environments for programs *)
147
148 type env = Id.t list * Id.Set.t
149
150 (*s Generic renaming issues for local variable names. *)
151
152 let rec rename_id id avoid =
153 if Id.Set.mem id avoid then rename_id (increment_subscript id) avoid else id
154
155 let rec rename_vars avoid = function
156 | [] ->
157 [], avoid
158 | id :: idl when id == dummy_name ->
159 (* we don't rename dummy binders *)
160 let (idl', avoid') = rename_vars avoid idl in
161 (id :: idl', avoid')
162 | id :: idl ->
163 let (idl, avoid) = rename_vars avoid idl in
164 let id = rename_id (lowercase_id id) avoid in
165 (id :: idl, Id.Set.add id avoid)
166
167 let rename_tvars avoid l =
168 let rec rename avoid = function
169 | [] -> [],avoid
170 | id :: idl ->
171 let id = rename_id (lowercase_id id) avoid in
172 let idl, avoid = rename (Id.Set.add id avoid) idl in
173 (id :: idl, avoid) in
174 fst (rename avoid l)
175
176 let push_vars ids (db,avoid) =
177 let ids',avoid' = rename_vars avoid ids in
178 ids', (ids' @ db, avoid')
179
180 let get_db_name n (db,_) = List.nth db (pred n)
181
182 type phase = Pre | Impl | Intf
183
184 module DupOrd =
185 struct
186 type t = ModPath.t * Id.t
187 let compare (mp1, l1) (mp2, l2) =
188 let c = Id.compare l1 l2 in
189 if Int.equal c 0 then ModPath.compare mp1 mp2 else c
190 end
191
192 module DupMap = CMap.Make(DupOrd)
193
194 (* We might have built [global_reference] whose canonical part is
195 inaccurate. We must hence compare only the user part,
196 hence using a Hashtbl might be incorrect *)
197
198 (*s table indicating the visible horizon at a precise moment,
199 i.e. the stack of structures we are inside.
200
201 - The sequence of [mp] parts should have the following form:
202 a [MPfile] at the beginning, and then more and more [MPdot]
203 over this [MPfile], or [MPbound] when inside the type of a
204 module parameter.
205
206 - the [params] are the [MPbound] when [mp] is a functor,
207 the innermost [MPbound] coming first in the list.
208
209 - The [content] part is used to record all the names already
210 seen at this level.
211 *)
212
213 type visible_layer = { mp : ModPath.t;
214 params : MBId.t list;
215 content : Id.t KMap.t; }
216
217 module State =
218 struct
219
220 type state = {
221 global_ids : Id.Set.t;
222 mod_index : int Id.Map.t;
223 ref_renaming : string list Refmap'.t;
224 mp_renaming : string list ModPath.Map.t;
225 params_ren : MBId.Set.t; (* List of module parameters that we should alpha-rename *)
226 duplicates : int * string DupMap.t; (* table of local module wrappers used to provide non-ambiguous names *)
227 }
228
229 type modular = {
230 mutable mpfiles : DirPath.Set.t; (* List of external modules that will be opened initially *)
231 mutable mpfiles_content : Id.t KMap.t DirPath.Map.t; (* table recording objects in the first level of all MPfile *)
232 }
233
234 let empty_modular () = {
235 mpfiles = DirPath.Set.empty;
236 mpfiles_content = DirPath.Map.empty;
237 }
238
239 type t = {
240 table : Table.t;
241 state : state ref;
242 visibility : visible_layer ref list;
243 modular : modular option;
244 (* fields below are read-only *)
245 library : bool;
246 (*s Extraction modes: modular or monolithic, library or minimal ?
247
248 Nota:
249 - Recursive Extraction : monolithic, minimal
250 - Separate Extraction : modular, minimal
251 - Extraction Library : modular, library
252 *)
253 keywords : Id.Set.t;
254 phase : phase;
255 }
256
257 let make_state kw = {
258 global_ids = kw;
259 mod_index = Id.Map.empty;
260 ref_renaming = Refmap'.empty;
261 mp_renaming = ModPath.Map.empty;
262 params_ren = MBId.Set.empty;
263 duplicates = (0, DupMap.empty);
264 }
265
266 let make ~modular ~library ~keywords () = {
267 table = Table.make_table ();
268 state = ref (make_state keywords);
269 modular = if modular then Some (empty_modular ()) else None;
270 library;
271 keywords;
272 phase = Impl;
273 visibility = [];
274 }
275
276 let get_table s = s.table
277
278 let get_modular s = match s.modular with
279 | None -> false
280 | Some _ -> true
281
282 let get_modular_state s = s.modular
283
284 let get_library s = s.library
285
286 let get_keywords s = s.keywords
287
288 let get_phase s = s.phase
289
290 let set_phase s phase = { s with phase }
291
292 (* Reader-like *)
293
294 let with_visibility s mp mps k =
295 let v = ref { mp = mp; params = mps; content = KMap.empty } in
296 let ans = k { s with visibility = v :: s.visibility } in
297 (* we save the 1st-level-content of MPfile for later use *)
298 let () =
299 if s.phase == Impl then match mp, s.modular with
300 | MPfile dp, Some mdl ->
301 mdl.mpfiles_content <- DirPath.Map.add dp !v.content mdl.mpfiles_content
302 | (MPbound _ | MPdot _ | MPfile _), (None | Some _) -> ()
303 in
304 ans
305
306 let add_visible s ks l = match s.visibility with
307 | [] -> assert false
308 | v :: r -> v := { !v with content = KMap.add ks l !v.content }
309
310 let get_visible s =
311 List.map (!) s.visibility
312
313 let get_visible_mps s =
314 List.map (function v -> !v.mp) s.visibility
315
316 let get_top_visible_mp s = match s.visibility with
317 | [] -> assert false
318 | v :: _ -> !v.mp
319
320 (* Mutable primitives *)
321
322 let add_global_ids s id =
323 let state = s.state.contents in
324 s.state := { state with global_ids = Id.Set.add id state.global_ids }
325
326 let get_global_ids s =
327 s.state.contents.global_ids
328
329 let add_mod_index s id i =
330 let state = s.state.contents in
331 s.state := { state with mod_index = Id.Map.add id i state.mod_index }
332
333 let get_mod_index s id =
334 Id.Map.find id s.state.contents.mod_index
335
336 let add_ref_renaming s r l =
337 let state = s.state.contents in
338 s.state := { state with ref_renaming = Refmap'.add r l state.ref_renaming }
339
340 let get_ref_renaming s r =
341 Refmap'.find r s.state.contents.ref_renaming
342
343 let get_mp_renaming s mp =
344 ModPath.Map.find_opt mp s.state.contents.mp_renaming
345
346 let add_mp_renaming s mp l =
347 let state = s.state.contents in
348 s.state := { state with mp_renaming = ModPath.Map.add mp l state.mp_renaming }
349
350 let add_params_ren s mp =
351 let state = s.state.contents in
352 s.state := { state with params_ren = MBId.Set.add mp state.params_ren }
353
354 let mem_params_ren s mp =
355 MBId.Set.mem mp s.state.contents.params_ren
356
357 let get_mpfiles s =
358 s.mpfiles
359
360 let add_mpfiles s mp =
361 s.mpfiles <- DirPath.Set.add mp s.mpfiles
362
363 let clear_mpfiles s =
364 s.mpfiles <- DirPath.Set.empty
365
366 let add_duplicate s mp l =
367 let state = s.state.contents in
368 let (index, dups) = state.duplicates in
369 let ren = "Coq__" ^ string_of_int (index + 1) in
370 let dups = DupMap.add (mp, l) ren dups in
371 s.state := { state with duplicates = (index + 1, dups) }
372
373 let get_duplicate s mp l =
374 DupMap.find_opt (mp, l) (snd s.state.contents.duplicates)
375
376 let get_mpfiles_content mdl mp = DirPath.Map.find mp mdl.mpfiles_content
377
378 (* Reset *)
379
380 let reset s =
381 let () = assert (List.is_empty s.visibility) in
382 let state = {
383 global_ids = s.keywords;
384 mod_index = Id.Map.empty;
385 ref_renaming = Refmap'.empty;
386 mp_renaming = ModPath.Map.empty;
387 params_ren = MBId.Set.empty;
388 duplicates = (0, DupMap.empty);
389 } in
390 (* don't reset modular files content *)
391 let () = match s.modular with
392 | None -> ()
393 | Some mdl -> mdl.mpfiles <- DirPath.Set.empty
394 in
395 s.state := state
396
397 end
398
399 (*S Renamings of global objects. *)
400
401 (*s Tables of global renamings *)
402
403 let empty_env state () = [], State.get_global_ids state
404
405 let get_mpfiles_content s mp =
406 try State.get_mpfiles_content s mp
407 with Not_found -> failwith "get_mpfiles_content"
408
409 (*S Renaming functions *)
410
411 (* This function creates from [id] a correct uppercase/lowercase identifier.
412 This is done by adding a [Coq_] or [coq_] prefix. To avoid potential clashes
413 with previous [Coq_id] variable, these prefixes are duplicated if already
414 existing. *)
415
416 let modular_rename table k id =
417 let s = ascii_of_id id in
418 let prefix,is_ok = if upperkind k then "Coq_",is_upper else "coq_",is_lower
419 in
420 if not (is_ok s) || Id.Set.mem id (State.get_keywords table) || begins_with s prefix
421 then prefix ^ s
422 else s
423
424 (*s For monolithic extraction, first-level modules might have to be renamed
425 with unique numbers *)
426
427 let modfstlev_rename table id =
428 try
429 let n = State.get_mod_index table id in
430 let () = State.add_mod_index table id (n+1) in
431 let s = if n == 0 then "" else string_of_int (n-1) in
432 "Coq"^s^"_"^(ascii_of_id id)
433 with Not_found ->
434 let s = ascii_of_id id in
435 if is_lower s || begins_with_CoqXX s then
436 let () = State.add_mod_index table id 1 in
437 "Coq_" ^ s
438 else
439 let () = State.add_mod_index table id 0 in
440 s
441
442 (*s Creating renaming for a [module_path] : first, the real function ... *)
443
444 let rec mp_renaming_fun table mp = match mp with
445 | _ when not (State.get_modular table) && at_toplevel mp -> [""]
446 | MPdot (mp,l) ->
447 let lmp = mp_renaming table mp in
448 let mp = match lmp with
449 | [""] -> modfstlev_rename table l
450 | _ -> modular_rename table Mod l
451 in
452 mp ::lmp
453 | MPbound mbid ->
454 let s = modular_rename table Mod (MBId.to_id mbid) in
455 if not (State.mem_params_ren table mbid) then [s]
456 else let i,_,_ = MBId.repr mbid in [s^"__"^string_of_int i]
457 | MPfile f ->
458 let mdl = match State.get_modular_state table with
459 | None -> assert false (* see [at_toplevel] above *)
460 | Some mdl -> mdl
461 in
462 let () = assert (State.get_phase table == Pre) in
463 let current_mpfile = (List.last (State.get_visible table)).mp in
464 let () = if not (ModPath.equal mp current_mpfile) then State.add_mpfiles mdl f in
465 [string_of_modfile (State.get_table table) f]
466
467 (* ... and its version using a cache *)
468
469 and mp_renaming table x =
470 if is_mp_bound (base_mp x) then mp_renaming_fun table x
471 else match State.get_mp_renaming table x with
472 | Some v -> v
473 | None ->
474 let ans = mp_renaming_fun table x in
475 let () = State.add_mp_renaming table x ans in
476 ans
477
478 (*s Renamings creation for a [global_reference]: we build its fully-qualified
479 name in a [string list] form (head is the short name). *)
480
481 let ref_renaming_fun table (k,r) =
482 let mp = modpath_of_r r in
483 let l = mp_renaming table mp in
484 let l = if lang () != Ocaml && not (State.get_modular table) then [""] else l in
485 let s =
486 let idg = safe_basename_of_global (State.get_table table) r in
487 let app_suf s = match InfvInst.encode r.inst with
488 | None -> s
489 | Some suf -> s ^ "__" ^ suf
490 in
491 match l with
492 | [""] -> (* this happens only at toplevel of the monolithic case *)
493 let globs = State.get_global_ids table in
494 let id = next_ident_away (kindcase_id k idg) globs in
495 app_suf (Id.to_string id)
496 | _ -> app_suf (modular_rename table k idg)
497 in
498 let () = State.add_global_ids table (Id.of_string s) in
499 s::l
500
501 (* Cached version of the last function *)
502
503 let ref_renaming table ((k,r) as x) =
504 try if is_mp_bound (base_mp (modpath_of_r r)) then raise Not_found; State.get_ref_renaming table r
505 with Not_found -> let y = ref_renaming_fun table x in State.add_ref_renaming table r y; y
506
507 (* [visible_clash mp0 (k,s)] checks if [mp0-s] of kind [k]
508 can be printed as [s] in the current context of visible
509 modules. More precisely, we check if there exists a
510 visible [mp] that contains [s].
511 The verification stops if we encounter [mp=mp0]. *)
512
513 let rec clash mem mp0 ks = function
514 | [] -> false
515 | mp :: _ when ModPath.equal (MPfile mp) mp0 -> false
516 | mp :: _ when mem mp ks -> true
517 | _ :: mpl -> clash mem mp0 ks mpl
518
519 let mpfiles_clash mdl mp0 ks =
520 clash (fun mp k -> KMap.mem k (get_mpfiles_content mdl mp)) mp0 ks
521 (List.rev (DirPath.Set.elements (State.get_mpfiles mdl)))
522
523 let rec params_lookup table mp0 ks = function
524 | [] -> false
525 | param :: _ when ModPath.equal mp0 (MPbound param) -> true
526 | param :: params ->
527 let () = match ks with
528 | (Mod, mp) when String.equal (List.hd (mp_renaming table (MPbound param))) mp -> State.add_params_ren table param
529 | _ -> ()
530 in
531 params_lookup table mp0 ks params
532
533 let visible_clash table mp0 ks =
534 let rec clash = function
535 | [] -> false
536 | v :: _ when ModPath.equal v.mp mp0 -> false
537 | v :: vis ->
538 let b = KMap.mem ks v.content in
539 if b && not (is_mp_bound mp0) then true
540 else begin
541 let () = if b then match mp0 with
542 | MPbound mbid -> State.add_params_ren table mbid
543 | MPfile _ | MPdot _ -> assert false
544 in
545 if params_lookup table mp0 ks v.params then false
546 else clash vis
547 end
548 in clash (State.get_visible table)
549
550 (* Same, but with verbose output (and mp0 shouldn't be a MPbound) *)
551
552 let visible_clash_dbg table mp0 ks =
553 let rec clash = function
554 | [] -> None
555 | v :: _ when ModPath.equal v.mp mp0 -> None
556 | v :: vis ->
557 try Some (v.mp,KMap.find ks v.content)
558 with Not_found ->
559 if params_lookup table mp0 ks v.params then None
560 else clash vis
561 in clash (State.get_visible table)
562
563 (* After the 1st pass, we can decide which modules will be opened initially *)
564
565 let opened_libraries table =
566 match State.get_modular_state table with
567 | None -> DirPath.Set.empty
568 | Some mdl ->
569 let used_files = DirPath.Set.elements (State.get_mpfiles mdl) in
570 let used_ks = List.map (fun dp -> Mod, string_of_modfile (State.get_table table) dp) used_files in
571 (* By default, we open all used files. Ambiguities will be resolved later
572 by using qualified names. Nonetheless, we don't open any file A that
573 contains an immediate submodule A.B hiding another file B : otherwise,
574 after such an open, there's no unambiguous way to refer to objects of B. *)
575 let to_open =
576 List.filter
577 (fun dp ->
578 not (List.exists (fun k -> KMap.mem k (get_mpfiles_content mdl dp)) used_ks))
579 used_files
580 in
581 let () = State.clear_mpfiles mdl in
582 let () = List.iter (fun mp -> State.add_mpfiles mdl mp) to_open in
583 State.get_mpfiles mdl
584
585 (*s On-the-fly qualification issues for both monolithic or modular extraction. *)
586
587 (* [pp_ocaml_gen] below is a function that factorize the printing of both
588 [global_reference] and module names for ocaml. When [k=Mod] then [olab=None],
589 otherwise it contains the label of the reference to print.
590 [rls] is the string list giving the qualified name, short name at the end. *)
591
592 (* In Rocq, we can qualify [M.t] even if we are inside [M], but in Ocaml we
593 cannot do that. So, if [t] gets hidden and we need a long name for it,
594 we duplicate the _definition_ of t in a Coq__XXX module, and similarly
595 for a sub-module [M.N] *)
596
597 let pp_duplicate table k' prefix mp rls olab =
598 let rls', lbl =
599 if k' != Mod then
600 (* Here rls=[s], the ref to print is <prefix>.<s>, and olab<>None *)
601 rls, Option.get olab
602 else
603 (* Here rls=s::rls', we search the label for s inside mp *)
604 List.tl rls, get_nth_label_mp (mp_length mp - mp_length prefix) mp
605 in
606 match State.get_duplicate table prefix lbl with
607 | Some ren -> dottify (ren :: rls')
608 | None ->
609 assert (State.get_phase table == Pre); (* otherwise it's too late *)
610 State.add_duplicate table prefix lbl; dottify rls
611
612 let fstlev_ks k = function
613 | [] -> assert false
614 | [s] -> k,s
615 | s::_ -> Mod,s
616
617 (* [pp_ocaml_local] : [mp] has something in common with [top_visible ()]
618 but isn't equal to it *)
619
620 let pp_ocaml_local table k prefix mp rls olab =
621 (* what is the largest prefix of [mp] that belongs to [visible]? *)
622 assert (k != Mod || not (ModPath.equal mp prefix)); (* mp as whole module isn't in itself *)
623 let rls' = List.skipn (mp_length prefix) rls in
624 let k's = fstlev_ks k rls' in
625 (* Reference r / module path mp is of the form [<prefix>.s.<...>]. *)
626 if not (visible_clash table prefix k's) then dottify rls'
627 else pp_duplicate table (fst k's) prefix mp rls' olab
628
629 (* [pp_ocaml_bound] : [mp] starts with a [MPbound], and we are not inside
630 (i.e. we are not printing the type of the module parameter) *)
631
632 let pp_ocaml_bound table base rls =
633 (* clash with a MPbound will be detected and fixed by renaming this MPbound *)
634 if State.get_phase table == Pre then ignore (visible_clash table base (Mod,List.hd rls));
635 dottify rls
636
637 (* [pp_ocaml_extern] : [mp] isn't local, it is defined in another [MPfile]. *)
638
639 let pp_ocaml_extern table k base rls = match rls with
640 | [] -> assert false
641 | base_s :: rls' ->
642 if match State.get_modular_state table with
643 | None -> true (* Pseudo qualification with "" *)
644 | Some mdl ->
645 (List.is_empty rls') (* Case of a file A.v used as a module later *)
646 || (not (match base with MPfile dp -> DirPath.Set.mem dp (State.get_mpfiles mdl) | MPbound _ | MPdot _ -> false)) (* Module not opened *)
647 || (mpfiles_clash mdl base (fstlev_ks k rls')) (* Conflict in opened files *)
648 || (visible_clash table base (fstlev_ks k rls')) (* Local conflict *)
649 then
650 (* We need to fully qualify. Last clash situation is unsupported *)
651 match visible_clash_dbg table base (Mod,base_s) with
652 | None -> dottify rls
653 | Some (mp,l) -> error_module_clash base (MPdot (mp,l))
654 else
655 (* Standard situation : object in an opened file *)
656 dottify rls'
657
658 (* [pp_ocaml_gen] : choosing between [pp_ocaml_local] or [pp_ocaml_extern] *)
659
660 let pp_ocaml_gen table k mp rls olab =
661 match common_prefix_from_list mp (State.get_visible_mps table) with
662 | Some prefix -> pp_ocaml_local table k prefix mp rls olab
663 | None ->
664 let base = base_mp mp in
665 if is_mp_bound base then pp_ocaml_bound table base rls
666 else pp_ocaml_extern table k base rls
667
668 (* For Haskell, things are simpler: we have removed (almost) all structures *)
669
670 let pp_haskell_gen table k mp rls = match rls with
671 | [] -> assert false
672 | s::rls' ->
673 let str = pseudo_qualify rls' in
674 let str = if is_upper str && not (upperkind k) then ("_"^str) else str in
675 if ModPath.equal (base_mp mp) (State.get_top_visible_mp table) then str else s^"."^str
676
677 (* Main name printing function for a reference *)
678
679 let pp_global_with_key table k key r =
680 let ls = ref_renaming table (k,r) in
681 assert (List.length ls > 1);
682 let s = List.hd ls in
683 let mp,l = KerName.repr key in
684 if ModPath.equal mp (State.get_top_visible_mp table) then
685 (* simplest situation: definition of r (or use in the same context) *)
686 (* we update the visible environment *)
687 let () = State.add_visible table (k, s) l in
688 unquote s
689 else
690 let rls = List.rev ls in (* for what come next it's easier this way *)
691 match lang () with
692 | Scheme -> unquote s (* no modular Scheme extraction... *)
693 | JSON -> dottify (List.map unquote rls)
694 | Haskell -> if State.get_modular table then pp_haskell_gen table k mp rls else s
695 | Ocaml -> pp_ocaml_gen table k mp rls (Some l)
696
697 let pp_global table k r =
698 pp_global_with_key table k (repr_of_r r) r
699
700 (* Main name printing function for declaring a reference *)
701
702 let pp_global_name table k r =
703 let ls = ref_renaming table (k,r) in
704 assert (List.length ls > 1);
705 List.hd ls
706
707 (* The next function is used only in Ocaml extraction...*)
708
709 let pp_module table mp =
710 let ls = mp_renaming table mp in
711 match mp with
712 | MPdot (mp0,l) when ModPath.equal mp0 (State.get_top_visible_mp table) ->
713 (* simplest situation: definition of mp (or use in the same context) *)
714 (* we update the visible environment *)
715 let s = List.hd ls in
716 let () = State.add_visible table (Mod, s) l in
717 s
718 | _ -> pp_ocaml_gen table Mod mp (List.rev ls) None
719
720 (** Special hack for constants of type Ascii.ascii : if an
721 [Extract Inductive ascii => char] has been declared, then
722 the constants are directly turned into chars *)
723
724 let ascii_type_name = "core.ascii.type"
725 let ascii_constructor_name = "core.ascii.ascii"
726
727 let is_ascii_registered () =
728 Rocqlib.has_ref ascii_type_name
729 && Rocqlib.has_ref ascii_constructor_name
730
731 let ascii_type_ref () =
732 (* FIXME: support sort poly? *)
733 { glob = Rocqlib.lib_ref ascii_type_name; inst = InfvInst.empty }
734
735 let check_extract_ascii () =
736 try
737 let char_type = match lang () with
738 | Ocaml -> "char"
739 | Haskell -> "Prelude.Char"
740 | _ -> raise Not_found
741 in
742 String.equal (find_custom @@ ascii_type_ref ()) (char_type)
743 with Not_found -> false
744
745 let is_constructor r = match r.glob with GlobRef.ConstructRef _ -> true | _ -> false
746
747 let is_list_cons l =
748 List.for_all (function MLcons (_, r, []) -> is_constructor r | _ -> false) l
749
750 let is_native_char = function
751 | MLcons(_,gr,l) ->
752 is_ascii_registered ()
753 && Rocqlib.check_ref ascii_constructor_name gr.glob
754 && check_extract_ascii ()
755 && is_list_cons l
756 | _ -> false
757
758 let get_constructor r = match r.glob with
759 | GlobRef.ConstructRef(_, j) -> j
760 | _ -> assert false
761
762 let get_native_char c =
763 let rec cumul = function
764 | [] -> 0
765 | MLcons(_, r, [])::l -> (2 - get_constructor r) + 2 * (cumul l)
766 | _ -> assert false
767 in
768 let l = match c with MLcons(_,_,l) -> l | _ -> assert false in
769 Char.chr (cumul l)
770
771 let pp_native_char c = str ("'"^Char.escaped (get_native_char c)^"'")
772
773 (** Special hack for constants of type String.string : if an
774 [Extract Inductive string => string] has been declared, then
775 the constants are directly turned into string literals *)
776
777 let string_type_name = "core.string.type"
778 let empty_string_name = "core.string.empty"
779 let string_constructor_name = "core.string.string"
780
781 let is_string_registered () =
782 Rocqlib.has_ref string_type_name
783 && Rocqlib.has_ref empty_string_name
784 && Rocqlib.has_ref string_constructor_name
785
786 let string_type_ref () =
787 (* FIXME: support sort poly? *)
788 { glob = Rocqlib.lib_ref string_type_name; inst = InfvInst.empty }
789
790 let check_extract_string () =
791 try
792 let string_type = match lang () with
793 | Ocaml -> "string"
794 | Haskell -> "Prelude.String"
795 | _ -> raise Not_found
796 in
797 String.equal (find_custom @@ string_type_ref ()) string_type
798 with Not_found -> false
799
800 (* The argument is known to be of type Strings.String.string.
801 Check that it is built from constructors EmptyString and String
802 with constant ascii arguments. *)
803
804 let rec is_native_string_rec empty_string_ref string_constructor_ref = function
805 (* "EmptyString" constructor *)
806 | MLcons(_, gr, []) -> Rocqlib.check_ref empty_string_ref gr.glob
807 (* "String" constructor *)
808 | MLcons(_, gr, [hd; tl]) ->
809 Rocqlib.check_ref string_constructor_ref gr.glob
810 && is_native_char hd
811 && is_native_string_rec empty_string_ref string_constructor_ref tl
812 (* others *)
813 | _ -> false
814
815 (* Here we first check that the argument is the type registered as
816 core.string.type and that extraction to native strings was
817 requested. Then we check every character via
818 [is_native_string_rec]. *)
819
820 let is_string_constructor = function
821 | GlobRef.ConstructRef (ind, _) -> Rocqlib.check_ref string_type_name (GlobRef.IndRef ind)
822 | _ -> false
823
824 let is_native_string c =
825 match c with
826 | MLcons(_, gr, l) ->
827 is_string_registered ()
828 && is_string_constructor gr.glob
829 && check_extract_string ()
830 && is_native_string_rec empty_string_name string_constructor_name c
831 | _ -> false
832
833 (* Extract the underlying string. *)
834
835 let get_native_string c =
836 let buf = Buffer.create 64 in
837 let rec get = function
838 (* "EmptyString" constructor *)
839 | MLcons(_, gr, []) when Rocqlib.check_ref empty_string_name gr.glob ->
840 Buffer.contents buf
841 (* "String" constructor *)
842 | MLcons(_, gr, [hd; tl]) when Rocqlib.check_ref string_constructor_name gr.glob ->
843 Buffer.add_char buf (get_native_char hd);
844 get tl
845 (* others *)
846 | _ -> assert false
847 in get c
848
849 (* Printing the underlying string. *)
850
851 let pp_native_string c =
852 str ("\"" ^ String.escaped (get_native_string c) ^ "\"")
853
854 (* Registered sig type *)
855
856 let sig_type_name = "core.sig.type"