Debian Codegraph @

engine/namegen.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 (* Created from contents that was formerly in termops.ml and
12 nameops.ml, Nov 2009 *)
13
14 (* This file is about generating new or fresh names and dealing with
15 alpha-renaming *)
16
17 open Util
18 open Names
19 open Sorts
20 open Constr
21 open Context
22 open Environ
23 open EConstr
24 open Vars
25 open Nameops
26 open Libnames
27 open Context.Rel.Declaration
28
29 module RelDecl = Context.Rel.Declaration
30
31 (** General evar naming using intro patterns *)
32 type intro_pattern_naming_expr =
33 | IntroIdentifier of Id.t
34 | IntroFresh of Id.t
35 | IntroAnonymous
36
37 let intro_pattern_naming_eq nam1 nam2 = match nam1, nam2 with
38 | IntroAnonymous, IntroAnonymous -> true
39 | IntroIdentifier id1, IntroIdentifier id2 -> Names.Id.equal id1 id2
40 | IntroFresh id1, IntroFresh id2 -> Names.Id.equal id1 id2
41 | _ -> false
42
43 (**********************************************************************)
44 (* Conventional names *)
45
46 let default_prop_string = "H"
47 let default_prop_ident = Id.of_string default_prop_string
48
49 let default_small_string = "H"
50 let default_small_ident = Id.of_string default_small_string
51
52 let default_type_string = "X"
53 let default_type_ident = Id.of_string default_type_string
54
55 let default_non_dependent_string = "H"
56 let default_non_dependent_ident = Id.of_string default_non_dependent_string
57
58 let default_dependent_ident = Id.of_string "x"
59
60 let default_generated_non_letter_string = "x"
61
62 (**********************************************************************)
63 (* Globality of identifiers *)
64
65 let is_imported_modpath = function
66 | MPfile dp ->
67 let rec find_prefix = function
68 |MPfile dp1 -> not (DirPath.equal dp1 dp)
69 |MPdot(mp,_) -> find_prefix mp
70 |MPbound(_) -> false
71 in find_prefix (Lib.current_mp ())
72 | _ -> false
73
74 let is_imported_ref = let open GlobRef in function
75 | VarRef _ -> false
76 | IndRef (kn,_)
77 | ConstructRef ((kn,_),_) ->
78 let mp = MutInd.modpath kn in is_imported_modpath mp
79 | ConstRef kn ->
80 let mp = Constant.modpath kn in is_imported_modpath mp
81
82 let locate id =
83 match Nametab.locate_extended_nowarn (qualid_of_ident id) with
84 | TrueGlobal r -> r
85 | Abbrev _ -> raise Not_found
86
87 let is_global id =
88 try
89 let ref = locate id in
90 not (is_imported_ref ref)
91 with Not_found ->
92 false
93
94 let is_constructor id =
95 try
96 match locate id with
97 | GlobRef.ConstructRef _ -> true
98 | _ -> false
99 with Not_found ->
100 false
101
102 let is_section_variable env id =
103 try let _ = Environ.lookup_named id env in true
104 with Not_found -> false
105
106 (**********************************************************************)
107 (* Generating "intuitive" names from its type *)
108
109 let global_of_constr = let open GlobRef in function
110 | Const (c, _) -> ConstRef c
111 | Ind (i, _) -> IndRef i
112 | Construct (c, _) -> ConstructRef c
113 | Var id -> VarRef id
114 | _ -> assert false
115
116 let head_name sigma c = (* Find the head constant of a constr if any *)
117 let rec hdrec c =
118 match EConstr.kind sigma c with
119 | Prod (_,_,c) | Lambda (_,_,c) | LetIn (_,_,_,c)
120 | Cast (c,_,_) | App (c,_) -> hdrec c
121 | Proj (kn,_,_) -> Some (Constant.label (Projection.constant kn))
122 | Const _ | Ind _ | Construct _ | Var _ as c ->
123 Some (Nametab.basename_of_global (global_of_constr c))
124 | Fix ((_,i),(lna,_,_)) | CoFix (i,(lna,_,_)) ->
125 Some (match lna.(i).binder_name with Name id -> id | _ -> assert false)
126 | Sort _ | Rel _ | Meta _ | Evar _ | Case _
127 | Int _ | Float _ | String _ | Array _ -> None
128 in
129 hdrec c
130
131 let lowercase_first_char id = (* First character of a constr *)
132 let s = Id.to_string id in
133 match Unicode.split_at_first_letter s with
134 | None ->
135 (* General case: nat -> n *)
136 Unicode.lowercase_first_char s
137 | Some (s,s') ->
138 if String.length s' = 0 then
139 (* No letter, e.g. __, or __'_, etc. *)
140 default_generated_non_letter_string
141 else
142 s ^ Unicode.lowercase_first_char s'
143
144 let sort_hdchar = function
145 | SProp -> "P"
146 | Prop -> "P"
147 | Set -> "S"
148 | Type _ | QSort _ -> "T"
149
150 let hdchar env sigma c =
151 let rec hdrec k c =
152 match EConstr.kind sigma c with
153 | Prod (_,_,c) | Lambda (_,_,c) | LetIn (_,_,_,c) -> hdrec (k+1) c
154 | Cast (c,_,_) | App (c,_) -> hdrec k c
155 | Proj (kn,_,_) -> lowercase_first_char (Constant.label (Projection.constant kn))
156 | Const (kn,_) -> lowercase_first_char (Constant.label kn)
157 | Ind (x,_) -> (try lowercase_first_char (Nametab.basename_of_global (GlobRef.IndRef x)) with Not_found when !Flags.in_debugger -> "zz")
158 | Construct (x,_) -> (try lowercase_first_char (Nametab.basename_of_global (GlobRef.ConstructRef x)) with Not_found when !Flags.in_debugger -> "zz")
159 | Var id -> lowercase_first_char id
160 | Sort s -> sort_hdchar (ESorts.kind sigma s)
161 | Rel n ->
162 (if n<=k then "p" (* the initial term is flexible product/function *)
163 else
164 try match let d = lookup_rel (n-k) env in get_name d, get_type d with
165 | Name id, _ -> lowercase_first_char id
166 | Anonymous, t -> hdrec 0 (lift (n-k) t)
167 with Not_found -> "y")
168 | Fix ((_,i),(lna,_,_)) | CoFix (i,(lna,_,_)) ->
169 let id = match lna.(i).binder_name with Name id -> id | _ -> assert false in
170 lowercase_first_char id
171 | Evar _ (* We could do better... *)
172 | Meta _ | Case _ -> "y"
173 | Int _ -> "i"
174 | Float _ -> "f"
175 | String _ -> "s"
176 | Array _ -> "a"
177 in
178 hdrec 0 c
179
180 let id_of_name_using_hdchar env sigma a = function
181 | Anonymous -> Id.of_string (hdchar env sigma a)
182 | Name id -> id
183
184 let named_hd env sigma a = function
185 | Anonymous -> Name (Id.of_string (hdchar env sigma a))
186 | x -> x
187
188 let mkProd_name env sigma (n,a,b) = mkProd (map_annot (named_hd env sigma a) n, a, b)
189 let mkLambda_name env sigma (n,a,b) = mkLambda (map_annot (named_hd env sigma a) n, a, b)
190
191 let lambda_name = mkLambda_name
192 let prod_name = mkProd_name
193
194 let prod_create env sigma (r,a,b) =
195 mkProd (make_annot (named_hd env sigma a Anonymous) r, a, b)
196 let lambda_create env sigma (r,a,b) =
197 mkLambda (make_annot (named_hd env sigma a Anonymous) r, a, b)
198
199 let name_assumption env sigma = function
200 | LocalAssum (na,t) -> LocalAssum (map_annot (named_hd env sigma t) na, t)
201 | LocalDef (na,c,t) -> LocalDef (map_annot (named_hd env sigma c) na, c, t)
202
203 let name_context env sigma hyps =
204 snd
205 (List.fold_left
206 (fun (env,hyps) d ->
207 let d' = name_assumption env sigma d in (push_rel d' env, d' :: hyps))
208 (env,[]) (List.rev hyps))
209
210 let mkProd_or_LetIn_name env sigma b d = mkProd_or_LetIn (name_assumption env sigma d) b
211 let mkLambda_or_LetIn_name env sigma b d = mkLambda_or_LetIn (name_assumption env sigma d) b
212
213 let it_mkProd_or_LetIn_name env sigma b hyps =
214 it_mkProd_or_LetIn b (name_context env sigma hyps)
215 let it_mkLambda_or_LetIn_name env sigma b hyps =
216 it_mkLambda_or_LetIn b (name_context env sigma hyps)
217
218 (**********************************************************************)
219 (* Fresh names *)
220
221 (* Introduce a mode where auto-generated names are mangled
222 to test dependence of scripts on auto-generated names.
223 We also supply a version which only adds a prefix. *)
224
225 let { Goptions.get = get_mangle_names } =
226 Goptions.declare_bool_option_and_ref
227 ~key:["Mangle";"Names"]
228 ~value:false
229 ()
230
231 let { Goptions.get = get_mangle_names_light } =
232 Goptions.declare_bool_option_and_ref
233 ~key:["Mangle";"Names";"Light"]
234 ~value:false
235 ()
236
237 let { Goptions.get = mangle_names_prefix } =
238 Goptions.declare_interpreted_string_option_and_ref
239 ~key:["Mangle";"Names";"Prefix"]
240 ~value:("_")
241 (fun x ->
242 Id.to_string
243 (try
244 Id.of_string x
245 with
246 | CErrors.UserError _ ->
247 CErrors.user_err Pp.(str ("Not a valid identifier: \"" ^ x ^ "\"."))
248 )
249 )
250 (fun x -> x)
251 ()
252
253 (** The name "foo" becomes "_0" if we get_mangle_names and "_foo" if
254 get_mangle_names_light is also set. Otherwise it is left alone. *)
255
256 let mangle_id id =
257 let prfx = mangle_names_prefix () in
258 if get_mangle_names () then
259 if get_mangle_names_light () then
260 Id.of_string (prfx ^ Id.to_string id)
261 else Id.of_string (prfx ^ "0")
262 else id
263
264 (* Looks for next "good" name by lifting subscript *)
265
266 let next_ident_away_from_post_mangling id bad =
267 let rec name_rec id = if bad id then name_rec (increment_subscript id) else id in
268 name_rec id
269
270 let next_ident_away_from id bad =
271 let id = mangle_id id in
272 next_ident_away_from_post_mangling id bad
273
274 (* Restart subscript from x0 if name starts with xN, or x00 if name
275 starts with x0N, etc *)
276
277 let restart_subscript id =
278 if not (has_subscript id) then id else
279 (* It would probably be better with something in the spirit of
280 *** make_ident id (Some 0) *** but compatibility would be lost... *)
281 forget_subscript id
282
283 module Generator =
284 struct
285
286 type _ t =
287 | Fresh : Fresh.t t
288 | IdSet : Id.Set.t t
289
290 type 'a input = 'a t * 'a
291
292 let fresh = Fresh
293 let idset = IdSet
294
295 let max_map (type a) (gen : a t) (avoid : a) =
296 match gen with
297 | Fresh -> Fresh.max_map avoid
298 | IdSet ->
299 let fold id accu =
300 let id, ss = get_subscript id in
301 match Id.Map.find_opt id accu with
302 | Some old_ss when Subscript.compare ss old_ss <= 0 -> accu
303 | _ -> Id.Map.add id ss accu
304 in
305 Id.Set.fold fold avoid Id.Map.empty
306
307 let is_fresh (type a) (gen : a t) id (avoid : a) = match gen with
308 | Fresh -> not (Fresh.mem id avoid)
309 | IdSet -> not (Id.Set.mem id avoid)
310
311 let gen_ident (type a) ?(mangle = true) ?(filter = (fun _ -> false)) (gen : a t) id (state : a) : Id.t * a =
312 let id = if mangle then mangle_id id else id in
313 match gen with
314 | Fresh ->
315 let rec gen state id =
316 let (id, state) = Fresh.fresh id state in
317 if filter id then gen state id else id
318 in
319 let id = gen state id in
320 (id, Fresh.add id state)
321 | IdSet ->
322 let rec gen id = if Id.Set.mem id state || filter id then gen (increment_subscript id) else id in
323 let id = gen id in
324 (id, Id.Set.add id state)
325
326 let next_name_away gen na avoid =
327 let id = match na with Name id -> id | Anonymous -> default_non_dependent_ident in
328 let id = mangle_id id in
329 let id = if is_fresh gen id avoid then id else restart_subscript id in
330 gen_ident ~mangle:false gen id avoid
331
332 end
333
334 let visible_ids sigma (nenv, c) =
335 let accu = ref (GlobRef.Set_env.empty, Int.Set.empty, Id.Set.empty) in
336 let rec visible_ids n c = match EConstr.kind sigma c with
337 | Const _ | Ind _ | Construct _ | Var _ as c ->
338 let (gseen, vseen, ids) = !accu in
339 let g = global_of_constr c in
340 if not (GlobRef.Set_env.mem g gseen) then
341 let gseen = GlobRef.Set_env.add g gseen in
342 let ids = match Nametab.shortest_qualid_of_global ~force_short:true Id.Set.empty g with
343 | short ->
344 let dir, id = repr_qualid short in
345 if DirPath.is_empty dir then Id.Set.add id ids else ids
346 | exception Not_found ->
347 (* This may happen if given pathological terms or when manipulating
348 open modules *)
349 ids
350 in
351 accu := (gseen, vseen, ids)
352 | Rel p ->
353 let (gseen, vseen, ids) = !accu in
354 if p > n && not (Int.Set.mem (p - n) vseen) then
355 let vseen = Int.Set.add (p - n) vseen in
356 let name =
357 try Some (List.nth nenv (p - n - 1))
358 with Invalid_argument _ | Failure _ ->
359 (* Unbound index: may happen in debug and actually also
360 while computing temporary implicit arguments of an
361 inductive type *)
362 None
363 in
364 let ids = match name with
365 | Some (Name id) -> Id.Set.add id ids
366 | _ -> ids
367 in
368 accu := (gseen, vseen, ids)
369 | Evar (_,args as ev) ->
370 (* Useful for at least debugger: do the same as in iter_with_binders *)
371 (* except that Not_found is not fatal *)
372 begin match Evd.expand_existential sigma ev with
373 | args -> List.iter (visible_ids n) args
374 | exception Not_found when !Flags.in_debugger ->
375 SList.Skip.iter (visible_ids n) args
376 end
377 | _ -> EConstr.iter_with_binders sigma succ visible_ids n c
378 in
379 let () = visible_ids 1 c in (* n = 1 to count the binder to rename *)
380 let (_, _, ids) = !accu in
381 ids
382
383 (* Now, there are different renaming strategies... *)
384
385 (* 1- Looks for a fresh name for printing in cases pattern *)
386
387 let next_name_away_in_cases_pattern gen sigma env_t na avoid =
388 let id = match na with Name id -> id | Anonymous -> default_dependent_ident in
389 let visible = visible_ids sigma env_t in
390 let bad id = is_constructor id || Id.Set.mem id visible in
391 Generator.gen_ident ~filter:bad gen id avoid
392
393 (* 2- Looks for a fresh name for introduction in goal *)
394
395 (* The legacy strategy for renaming introduction variables is not very uniform:
396 - if the name to use is fresh in the context but used as a global
397 name, then a fresh name is taken by finding a free subscript
398 starting from the current subscript;
399 - but if the name to use is not fresh in the current context, the fresh
400 name is taken by finding a free subscript starting from 0 *)
401
402 let next_ident_away_in_goal env id avoid =
403 let id = if Id.Set.mem id avoid then restart_subscript id else id in
404 let bad id = Id.Set.mem id avoid || (is_global id && not (is_section_variable env id)) in
405 next_ident_away_from id bad
406
407 let next_name_away_in_goal (type a) (gen : a Generator.t) env na (avoid : a) =
408 let id = match na with
409 | Name id -> id
410 | Anonymous -> default_non_dependent_ident in
411 let id = if Generator.is_fresh gen id avoid then id else restart_subscript id in
412 let bad id = is_global id && not (is_section_variable env id) in
413 Generator.gen_ident ~filter:bad gen id avoid
414
415 (* 3- Looks for next fresh name outside a list that is moreover valid
416 as a global identifier; the legacy algorithm is that if the name is
417 already used in the list, one looks for a name of same base with
418 lower available subscript; if the name is not in the list but is
419 used globally, one looks for a name of same base with lower subscript
420 beyond the current subscript *)
421
422 let next_global_ident_away senv id avoid =
423 let id = if Id.Set.mem id avoid then restart_subscript id else id in
424 let bad id = Id.Set.mem id avoid || Safe_typing.exists_objlabel id senv in
425 next_ident_away_from id bad
426
427 (* 4- Looks for next fresh name outside a list; if name already used,
428 looks for same name with lower available subscript *)
429
430 let next_ident_away id avoid =
431 let id = mangle_id id in
432 if Id.Set.mem id avoid then
433 next_ident_away_from_post_mangling (restart_subscript id) (fun id -> Id.Set.mem id avoid)
434 else id
435
436 let next_name_away_with_default default na avoid =
437 let id = match na with Name id -> id | Anonymous -> Id.of_string default in
438 next_ident_away id avoid
439
440 let reserved_type_name = ref (fun _ _ _ -> Anonymous)
441 let set_reserved_typed_name f = reserved_type_name := f
442
443 let next_name_away_with_default_using_types env sigma default na avoid t =
444 let id = match na with
445 | Name id -> id
446 | Anonymous -> match !reserved_type_name env sigma t with
447 | Name id -> id
448 | Anonymous -> Id.of_string default in
449 next_ident_away id avoid
450
451 let next_name_away = next_name_away_with_default default_non_dependent_string
452
453 let make_all_rel_context_name_different env sigma ctx =
454 let avoid = ref (Id.Set.union (Context.Rel.to_vars (Environ.rel_context env)) (ids_of_named_context_val (named_context_val env))) in
455 Context.Rel.fold_outside
456 (fun decl (newenv,ctx) ->
457 let na = named_hd newenv sigma (RelDecl.get_type decl) (RelDecl.get_name decl) in
458 let id = next_name_away na !avoid in
459 avoid := Id.Set.add id !avoid;
460 let decl = RelDecl.set_name (Name id) decl in
461 push_rel decl newenv, decl :: ctx)
462 ctx ~init:(env,[])
463
464 let make_all_name_different env sigma =
465 (* FIXME: this is inefficient, but only used in printing *)
466 let sign = named_context_val env in
467 let rels = rel_context env in
468 let env0 = reset_with_named_context sign env in
469 let env,_ = make_all_rel_context_name_different env0 sigma rels in
470 env
471
472 (* 5- Looks for next fresh name outside a list; avoids also to use names that
473 would clash with short name of global references; if name is already used,
474 looks for name of same base with lower available subscript beyond current
475 subscript *)
476
477 let next_ident_away_for_default_printing gen sigma env_t id avoid =
478 let visible = visible_ids sigma env_t in
479 let bad id = Id.Set.mem id visible in
480 Generator.gen_ident ~filter:bad gen id avoid
481
482 let next_name_away_for_default_printing gen sigma env_t na avoid =
483 let id = match na with
484 | Name id -> id
485 | Anonymous ->
486 (* In principle, an anonymous name is not dependent and will not be *)
487 (* taken into account by the function compute_displayed_name_in; *)
488 (* just in case, invent a valid name *)
489 default_non_dependent_ident in
490 next_ident_away_for_default_printing gen sigma env_t id avoid
491
492 (**********************************************************************)
493 (* Displaying terms avoiding bound variables clashes *)
494
495 (* Renaming strategy introduced in December 1998:
496
497 - Rule number 1: all names, even if unbound and not displayed, contribute
498 to the list of names to avoid
499 - Rule number 2: only the dependency status is used for deciding if
500 a name is displayed or not
501
502 Example:
503 bool_ind: "forall (P:bool->Prop)(f:(P true))(f:(P false))(b:bool), P b" is
504 displayed "forall P:bool->Prop, P true -> P false -> forall b:bool, P b"
505 but f and f0 contribute to the list of variables to avoid (knowing
506 that f and f0 are how the f's would be named if introduced, assuming
507 no other f and f0 are already used).
508 *)
509
510 type renaming_flags =
511 (* The term is the body of a binder and the environment excludes this binder *)
512 (* so, there is a missing binder in the environment *)
513 | RenamingForCasesPattern of (Name.t list * constr)
514 | RenamingForGoal
515 | RenamingElsewhereFor of (Name.t list * constr)
516
517 let next_name_for_display gen env sigma flags na avoid =
518 match flags with
519 | RenamingForCasesPattern env_t -> next_name_away_in_cases_pattern gen sigma env_t na avoid
520 | RenamingForGoal -> next_name_away_in_goal gen env na avoid
521 | RenamingElsewhereFor env_t -> next_name_away_for_default_printing gen sigma env_t na avoid
522
523 (* Remark: Anonymous var may be dependent in Evar's contexts *)
524 let compute_displayed_name_in_gen_poly gen noccurn_fun env sigma flags avoid na c =
525 let noccurs =
526 try noccurn_fun sigma 1 c
527 with _ when !Flags.in_debugger -> false
528 in
529 if noccurs then Anonymous, avoid
530 else
531 let fresh_id, avoid = next_name_for_display gen env sigma flags na avoid in
532 Name fresh_id, avoid
533
534 let compute_displayed_name_in gen = compute_displayed_name_in_gen_poly gen noccurn
535
536 let compute_displayed_name_in_gen gen f env sigma =
537 (* only flag which does not need a constr, maybe to be refined *)
538 let flag = RenamingForGoal in
539 compute_displayed_name_in_gen_poly gen f env sigma flag
540
541 let compute_displayed_let_name_in gen env sigma flags avoid na =
542 let fresh_id, avoid = next_name_for_display gen env sigma flags na avoid in
543 (Name fresh_id, avoid)