Debian Codegraph @

interp/notation.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 (*i*)
12 open CErrors
13 open Util
14 open Pp
15 open Names
16 open Libnames
17 open Globnames
18 open Libobject
19 open Constrexpr
20 open Notation_term
21 open Glob_term
22 open Glob_ops
23 open NumTok
24 open Notationextern
25 open PrimNotations
26
27 (*i*)
28
29 let notation_cat = Libobject.create_category "notations"
30
31
32 (*s A scope is a set of notations; it includes
33
34 - a set of ML interpreters/parsers for positive (e.g. 0, 1, 15, ...) and
35 negative numbers (e.g. -0, -2, -13, ...). These interpreters may
36 fail if a number has no interpretation in the scope (e.g. there is
37 no interpretation for negative numbers in [nat]); interpreters both for
38 terms and patterns can be set; these interpreters are in permanent table
39 [number_interpreter_tab]
40 - a set of ML printers for expressions denoting numbers parsable in
41 this scope
42 - a set of interpretations for infix (more generally distfix) notations
43 - an optional pair of delimiters which, when occurring in a syntactic
44 expression, set this scope to be the current scope
45 *)
46
47 let pr_notation (from,ntn) = qstring ntn ++ match from with InConstrEntry -> mt () | InCustomEntry s -> str " in custom " ++ Nametab.CustomEntries.pr s
48
49 module NotationOrd =
50 struct
51 type t = notation
52 let compare = Notationextern.notation_compare
53 end
54
55 module NotationSet = Set.Make(NotationOrd)
56 module NotationMap = CMap.Make(NotationOrd)
57
58 module SpecificNotationOrd =
59 struct
60 type t = specific_notation
61 let compare = Notationextern.specific_notation_compare
62 end
63
64 module SpecificNotationSet = Set.Make(SpecificNotationOrd)
65 module SpecificNotationMap = CMap.Make(SpecificNotationOrd)
66
67 (**********************************************************************)
68 (* Scope of symbols *)
69
70 type delimiters = string
71 type notation_location = (DirPath.t * DirPath.t) * string
72
73 type notation_data = {
74 not_interp : interpretation;
75 not_location : notation_location;
76 not_user_warns : UserWarn.t option;
77 }
78
79 type activation = bool
80
81 type extra_printing_notation_data =
82 (activation * notation_data) list
83
84 type parsing_notation_data =
85 | NoParsingData
86 | OnlyParsingData of activation * notation_data
87 | ParsingAndPrintingData of
88 activation (* for parsing*) *
89 activation (* for printing *) *
90 notation_data (* common data for both *)
91
92 type scope = {
93 notations: (parsing_notation_data * extra_printing_notation_data) NotationMap.t;
94 delimiters: delimiters option
95 }
96
97 (* Scopes table: scope_name -> symbol_interpretation *)
98 let scope_map = ref String.Map.empty
99
100 (* Delimiter table : delimiter -> scope_name *)
101 let delimiters_map = ref String.Map.empty
102
103 let empty_scope = {
104 notations = NotationMap.empty;
105 delimiters = None
106 }
107
108 let default_scope = "" (* empty name, not available from outside *)
109
110 let init_scope_map () =
111 scope_map := String.Map.add default_scope empty_scope !scope_map
112
113 (**********************************************************************)
114 (* Operations on scopes *)
115
116 let warn_scope_start_ =
117 CWarnings.create
118 ~name:"scope-underscore-start" ~category:CWarnings.CoreCategories.syntax
119 ~default:CWarnings.AsError
120 (fun () -> strbrk "Scope names should not start with an underscore.")
121
122 let warn_undeclared_scope =
123 CWarnings.create ~name:"undeclared-scope" ~category:Deprecation.Version.v8_10
124 (fun (scope) ->
125 strbrk "Declaring a scope implicitly is deprecated; use in advance an explicit "
126 ++ str "\"Declare Scope " ++ str scope ++ str ".\".")
127
128 let declare_scope scope =
129 if scope <> "" && scope.[0] = '_' then warn_scope_start_ ();
130 try let _ = String.Map.find scope !scope_map in ()
131 with Not_found ->
132 scope_map := String.Map.add scope empty_scope !scope_map
133
134 let error_unknown_scope ~info sc =
135 user_err ~info
136 (str "Scope " ++ str sc ++ str " is not declared.")
137
138 let find_scope ?(tolerant=false) scope =
139 try String.Map.find scope !scope_map
140 with Not_found as exn ->
141 let _, info = Exninfo.capture exn in
142 if tolerant then
143 (* tolerant mode to be turn off after deprecation phase *)
144 begin
145 warn_undeclared_scope scope;
146 scope_map := String.Map.add scope empty_scope !scope_map;
147 empty_scope
148 end
149 else
150 error_unknown_scope ~info scope
151
152 let check_scope ?(tolerant=false) scope =
153 let _ = find_scope ~tolerant scope in ()
154
155 let ensure_scope scope = check_scope ~tolerant:true scope
156
157 let find_scope scope = find_scope scope
158
159 let scope_delimiters scope = scope.delimiters
160
161 (* [sc] might be here a [scope_name] or a [delimiter]
162 (now allowed after Open Scope) *)
163
164 let normalize_scope sc =
165 try let _ = String.Map.find sc !scope_map in sc
166 with Not_found ->
167 try
168 let sc = String.Map.find sc !delimiters_map in
169 let _ = String.Map.find sc !scope_map in sc
170 with Not_found as exn ->
171 let _, info = Exninfo.capture exn in
172 error_unknown_scope ~info sc
173
174 (**********************************************************************)
175 (* The global stack of scopes *)
176
177 type scope_item = OpenScopeItem of scope_name | LonelyNotationItem of notation
178 type scopes = scope_item list
179
180 let scope_item_eq s1 s2 = match s1, s2 with
181 | OpenScopeItem s1, OpenScopeItem s2 -> String.equal s1 s2
182 | LonelyNotationItem s1, LonelyNotationItem s2 -> notation_eq s1 s2
183 | OpenScopeItem _, LonelyNotationItem _
184 | LonelyNotationItem _, OpenScopeItem _ -> false
185
186 let scope_stack = ref []
187
188 let current_scopes () = !scope_stack
189
190 let scope_is_open_in_scopes sc l =
191 List.exists (function OpenScopeItem sc' -> String.equal sc sc' | _ -> false) l
192
193 let scope_is_open sc = scope_is_open_in_scopes sc (!scope_stack)
194
195 (* TODO: push nat_scope, z_scope, ... in scopes summary *)
196
197 let open_scope sc = scope_stack := OpenScopeItem sc :: !scope_stack
198 let close_scope sc = scope_stack := List.remove scope_item_eq (OpenScopeItem sc) !scope_stack
199
200 let empty_scope_stack = []
201
202 let push_scope sc scopes = OpenScopeItem sc :: scopes
203
204 let push_scopes = List.fold_right push_scope
205
206 let make_current_scopes (tmp_scopes,scopes) =
207 push_scopes tmp_scopes (push_scopes scopes !scope_stack)
208
209 (**********************************************************************)
210 (* Delimiters *)
211
212 let warn_scope_delimiter_start_ =
213 CWarnings.create
214 ~name:"scope-delimiter-underscore-start"
215 ~category:CWarnings.CoreCategories.syntax
216 ~default:CWarnings.AsError
217 (fun () -> strbrk "Scope delimiters should not start with an underscore.")
218
219 let warn_hiding_key = CWarnings.create ~name:"hiding-delimiting-key" ~category:CWarnings.CoreCategories.parsing
220 Pp.(fun (key,oldscope) -> str "Hiding binding of key " ++ str key ++ str " to " ++ str oldscope)
221
222 let declare_delimiters scope key =
223 if key <> "" && key.[0] = '_' then warn_scope_delimiter_start_ ();
224 let sc = find_scope scope in
225 let newsc = { sc with delimiters = Some key } in
226 begin match sc.delimiters with
227 | None -> scope_map := String.Map.add scope newsc !scope_map
228 | Some oldkey when String.equal oldkey key -> ()
229 | Some oldkey -> scope_map := String.Map.add scope newsc !scope_map
230 end;
231 try
232 let oldscope = String.Map.find key !delimiters_map in
233 if String.equal oldscope scope then ()
234 else begin
235 warn_hiding_key (key,oldscope);
236 delimiters_map := String.Map.add key scope !delimiters_map
237 end
238 with Not_found -> delimiters_map := String.Map.add key scope !delimiters_map
239
240 let remove_delimiters scope =
241 let sc = find_scope scope in
242 let newsc = { sc with delimiters = None } in
243 match sc.delimiters with
244 | None -> CErrors.user_err (str "No bound key for scope " ++ str scope ++ str ".")
245 | Some key ->
246 scope_map := String.Map.add scope newsc !scope_map;
247 try
248 let _ = ignore (String.Map.find key !delimiters_map) in
249 delimiters_map := String.Map.remove key !delimiters_map
250 with Not_found as exn ->
251 let _, info = Exninfo.capture exn in
252 (* XXX info *)
253 CErrors.anomaly ~info (str "A delimiter for scope [scope] should exist")
254
255 let find_delimiters_scope ?loc key =
256 try String.Map.find key !delimiters_map
257 with Not_found ->
258 user_err ?loc
259 (str "Unknown scope delimiting key " ++ str key ++ str ".")
260
261 (** Dealing with precedences *)
262
263 let entry_relative_level_le child = function
264 | LevelLt parent -> child < parent
265 | LevelLe parent -> child <= parent
266 | LevelSome -> true
267
268 let notation_level_map = Summary.ref ~stage:Summary.Stage.Synterp ~name:"notation_level_map" NotationMap.empty
269
270 let declare_notation_level ntn level =
271 if NotationMap.mem ntn !notation_level_map then
272 anomaly (str "Notation " ++ pr_notation ntn ++ str " is already assigned a level.");
273 notation_level_map := NotationMap.add ntn level !notation_level_map
274
275 type required_module = full_path * string list
276
277 (* Table from scope_name to backtrack-able informations about interpreters
278 (in particular interpreter unique id). *)
279 let prim_token_interp_infos =
280 ref (String.Map.empty : (required_module * prim_token_interp_info) String.Map.t)
281
282 module GlobRefMap = Environ.QGlobRef.Map
283
284 (* Table from global_reference to backtrack-able informations about
285 prim_token uninterpretation (in particular uninterpreter unique id). *)
286 let prim_token_uninterp_infos =
287 ref (GlobRefMap.empty : ((scope_name * (prim_token_interp_info * bool)) list) GlobRefMap.t)
288
289 type prim_token_infos = {
290 pt_local : bool; (** Is this interpretation local? *)
291 pt_scope : scope_name; (** Concerned scope *)
292 pt_interp_info : prim_token_interp_info; (** Unique id "pointing" to (un)interp functions, OR a number notation object describing (un)interp functions *)
293 pt_required : required_module; (** Module that should be loaded first *)
294 pt_refs : GlobRef.t list; (** Entry points during uninterpretation *)
295 pt_in_match : bool (** Is this prim token legal in match patterns ? *)
296 }
297
298 let cache_prim_token_interpretation infos =
299 let env = Global.env () in
300 let ptii = infos.pt_interp_info in
301 let sc = infos.pt_scope in
302 check_scope ~tolerant:true sc;
303 prim_token_interp_infos :=
304 String.Map.add sc (infos.pt_required,ptii) !prim_token_interp_infos;
305 let add_uninterp r =
306 let l = try GlobRefMap.find env r !prim_token_uninterp_infos with Not_found -> [] in
307 prim_token_uninterp_infos :=
308 GlobRefMap.add env r ((sc,(ptii,infos.pt_in_match)) :: l)
309 !prim_token_uninterp_infos in
310 List.iter add_uninterp infos.pt_refs
311
312 let subst_prim_token_interpretation (subs,infos) =
313 { infos with
314 pt_refs = List.map (subst_global_reference subs) infos.pt_refs }
315
316 let classify_prim_token_interpretation infos =
317 if infos.pt_local then Dispose else Substitute
318
319 let inPrimTokenInterp : prim_token_infos -> obj =
320 declare_object {(default_object "PRIM-TOKEN-INTERP") with
321 open_function = simple_open ~cat:notation_cat cache_prim_token_interpretation;
322 cache_function = cache_prim_token_interpretation;
323 subst_function = subst_prim_token_interpretation;
324 classify_function = classify_prim_token_interpretation}
325
326 let enable_prim_token_interpretation infos =
327 Lib.add_leaf (inPrimTokenInterp infos)
328
329 (** Compatibility.
330 Avoid the next two functions, they will now store unnecessary
331 objects in the library segment. Instead, combine
332 [register_*_interpretation] and [enable_prim_token_interpretation]
333 (the latter inside a [Mltop.declare_cache_obj]).
334 *)
335
336 let glob_prim_constr_key c = match DAst.get c with
337 | GRef (ref, _) -> Some (canonical_gr ref)
338 | GApp (c, _) ->
339 begin match DAst.get c with
340 | GRef (ref, _) -> Some (canonical_gr ref)
341 | _ -> None
342 end
343 | GProj ((cst,_), _, _) -> Some (canonical_gr (GlobRef.ConstRef cst))
344 | _ -> None
345
346 let check_required_module ?loc sc (sp,d) =
347 try let _ = Nametab.global_of_path sp in ()
348 with Not_found as exn ->
349 let _, info = Exninfo.capture exn in
350 match d with
351 | [] ->
352 user_err ?loc ~info
353 (str "Cannot interpret in " ++ str sc ++ str " because " ++ pr_path sp ++
354 str " could not be found in the current environment.")
355 | _ ->
356 user_err ?loc ~info
357 (str "Cannot interpret in " ++ str sc ++ str " without requiring first module " ++
358 str (List.last d) ++ str ".")
359
360 (* Look if some notation or number printer in [scope] can be used in
361 the scope stack [scopes], and if yes, using delimiters or not *)
362
363 let find_with_delimiters = function
364 | LastLonelyNotation -> None
365 | NotationInScope scope ->
366 match (String.Map.find scope !scope_map).delimiters with
367 | Some key -> Some (Some scope, Some key)
368 | None -> None
369 | exception Not_found -> None
370
371 let rec find_without_delimiters find (ntn_scope,ntn) = function
372 | OpenScopeItem scope :: scopes ->
373 (* Is the expected ntn/numpr attached to the most recently open scope? *)
374 begin match ntn_scope with
375 | NotationInScope scope' when String.equal scope scope' ->
376 Some (None,None)
377 | _ ->
378 (* If the most recently open scope has a notation/number printer
379 but not the expected one then we need delimiters *)
380 if find scope then
381 find_with_delimiters ntn_scope
382 else
383 find_without_delimiters find (ntn_scope,ntn) scopes
384 end
385 | LonelyNotationItem ntn' :: scopes ->
386 begin match ntn with
387 | Some ntn'' when notation_eq ntn' ntn'' ->
388 begin match ntn_scope with
389 | LastLonelyNotation ->
390 (* If the first notation with same string in the visibility stack
391 is the one we want to print, then it can be used without
392 risking a collision *)
393 Some (None, None)
394 | NotationInScope _ ->
395 (* A lonely notation is liable to hide the scoped notation
396 to print, we check if the lonely notation is active to
397 know if the delimiter of the scoped notationis needed *)
398 if find default_scope then
399 find_with_delimiters ntn_scope
400 else
401 find_without_delimiters find (ntn_scope,ntn) scopes
402 end
403 | _ ->
404 (* A lonely notation which does not interfere with the notation to use *)
405 find_without_delimiters find (ntn_scope,ntn) scopes
406 end
407 | [] ->
408 (* Can we switch to [scope]? Yes if it has defined delimiters *)
409 find_with_delimiters ntn_scope
410
411 (* The mapping between notations and their interpretation *)
412
413 let pr_optional_scope = function
414 | LastLonelyNotation -> mt ()
415 | NotationInScope scope -> spc () ++ strbrk "in scope" ++ spc () ++ str scope
416
417 let warning_overridden_name = "notation-overridden"
418
419 let w_nota_overridden =
420 CWarnings.create_warning
421 ~from:[CWarnings.CoreCategories.parsing] ~name:warning_overridden_name ()
422
423 let warn_notation_overridden =
424 CWarnings.create_in w_nota_overridden
425 (fun (scope,ntn) ->
426 str "Notation" ++ spc () ++ pr_notation ntn ++ spc ()
427 ++ strbrk "was already used" ++ pr_optional_scope scope ++ str ".")
428
429 let warn_deprecation_overridden =
430 CWarnings.create_in w_nota_overridden
431 (fun ((scope,ntn),old,now) ->
432 match old, now with
433 | None, None -> assert false
434 | None, Some _ ->
435 (str "Notation" ++ spc () ++ pr_notation ntn ++ pr_optional_scope scope ++ spc ()
436 ++ strbrk "is now marked as deprecated" ++ str ".")
437 | Some _, None ->
438 (str "Cancelling previous deprecation of notation" ++ spc () ++
439 pr_notation ntn ++ pr_optional_scope scope ++ str ".")
440 | Some _, Some _ ->
441 (str "Amending deprecation of notation" ++ spc () ++
442 pr_notation ntn ++ pr_optional_scope scope ++ str "."))
443
444 let warn_override_if_needed (scopt,ntn) overridden data old_data =
445 if overridden then warn_notation_overridden (scopt,ntn)
446 else
447 if data.not_user_warns <> old_data.not_user_warns then
448 warn_deprecation_overridden ((scopt,ntn),old_data.not_user_warns,data.not_user_warns)
449
450 let check_parsing_override (scopt,ntn) data = function
451 | OnlyParsingData (_,old_data) ->
452 let overridden = not (interpretation_eq data.not_interp old_data.not_interp) in
453 warn_override_if_needed (scopt,ntn) overridden data old_data;
454 None
455 | ParsingAndPrintingData (_,on_printing,old_data) ->
456 let overridden = not (interpretation_eq data.not_interp old_data.not_interp) in
457 warn_override_if_needed (scopt,ntn) overridden data old_data;
458 if on_printing then Some old_data.not_interp else None
459 | NoParsingData -> None
460
461 let check_printing_override (scopt,ntn) data parsingdata printingdata =
462 let parsing_update = match parsingdata with
463 | OnlyParsingData _ | NoParsingData -> parsingdata
464 | ParsingAndPrintingData (_,on_printing,old_data) ->
465 let overridden = not (interpretation_eq data.not_interp old_data.not_interp) in
466 warn_override_if_needed (scopt,ntn) overridden data old_data;
467 if overridden then NoParsingData else parsingdata in
468 let exists = List.exists (fun (on_printing,old_data) ->
469 let exists = interpretation_eq data.not_interp old_data.not_interp in
470 if exists && data.not_user_warns <> old_data.not_user_warns then
471 warn_deprecation_overridden ((scopt,ntn),old_data.not_user_warns,data.not_user_warns);
472 exists) printingdata in
473 parsing_update, exists
474
475
476 let update_notation_data (scopt,ntn) use data table =
477 let (parsingdata,printingdata) =
478 try NotationMap.find ntn table with Not_found -> (NoParsingData, []) in
479 match use with
480 | OnlyParsing ->
481 let printing_update = check_parsing_override (scopt,ntn) data parsingdata in
482 NotationMap.add ntn (OnlyParsingData (true,data), printingdata) table, printing_update
483 | ParsingAndPrinting ->
484 let printing_update = check_parsing_override (scopt,ntn) data parsingdata in
485 NotationMap.add ntn (ParsingAndPrintingData (true,true,data), printingdata) table, printing_update
486 | OnlyPrinting ->
487 let parsingdata, exists = check_printing_override (scopt,ntn) data parsingdata printingdata in
488 let printingdata = if exists then printingdata else (true,data) :: printingdata in
489 NotationMap.add ntn (parsingdata, printingdata) table, None
490
491 let find_one_interpretation ntn find = function
492 | OpenScopeItem scope ->
493 (try let n = find scope in Some (n,Some scope)
494 with Not_found -> None)
495 | LonelyNotationItem ntn' when notation_eq ntn' ntn ->
496 (try let n = find default_scope in Some (n,None)
497 with Not_found ->
498 (* e.g. because single notation only for constr, not cases_pattern *)
499 None)
500 | LonelyNotationItem _ -> None
501
502 let find_interpretation ntn find scopes =
503 match List.find_map (find_one_interpretation ntn find) scopes with
504 | Some v -> v
505 | None -> raise Not_found
506
507 let find_notation ntn sc =
508 match fst (NotationMap.find ntn (find_scope sc).notations) with
509 | OnlyParsingData (true,data) | ParsingAndPrintingData (true,_,data) -> data
510 | _ -> raise Not_found
511
512 let notation_of_prim_token = function
513 | Constrexpr.Number (SPlus,n) -> InConstrEntry, NumTok.Unsigned.sprint n
514 | Constrexpr.Number (SMinus,n) -> InConstrEntry, "- "^NumTok.Unsigned.sprint n
515 | String s -> InConstrEntry, String.quote_coq_string s
516
517 let find_prim_token check_allowed ?loc p sc =
518 (* Try for a user-defined numerical notation *)
519 try
520 let n = find_notation (notation_of_prim_token p) sc in
521 let (_,c) = n.not_interp in
522 let pat = Notation_ops.glob_constr_of_notation_constr ?loc c in
523 check_allowed pat;
524 pat
525 with Not_found ->
526 (* Try for a primitive numerical notation *)
527 let (spdir,info) = String.Map.find sc !prim_token_interp_infos in
528 check_required_module ?loc sc spdir;
529 let pat = PrimNotations.do_interp ?loc info p in
530 check_allowed pat;
531 pat
532
533 let interp_prim_token_gen ?loc g p local_scopes =
534 let scopes = make_current_scopes local_scopes in
535 let p_as_ntn = try notation_of_prim_token p with Not_found -> InConstrEntry,"" in
536 try
537 let pat, sc = find_interpretation p_as_ntn (find_prim_token ?loc g p) scopes in
538 pat, sc
539 with Not_found as exn ->
540 let _, info = Exninfo.capture exn in
541 user_err ?loc ~info
542 ((match p with
543 | Number _ ->
544 str "No interpretation for number " ++ pr_notation (notation_of_prim_token p)
545 | String s -> str "No interpretation for string " ++ qs s) ++ str ".")
546
547 let interp_prim_token ?loc =
548 interp_prim_token_gen ?loc (fun _ -> ())
549
550 let interp_prim_token_cases_pattern_expr ?loc check_allowed p =
551 interp_prim_token_gen ?loc check_allowed p
552
553 let warn_notation =
554 UserWarn.create_depr_and_user_warnings ~object_name:"Notation" ~warning_name_base:"notation"
555 pr_notation ()
556
557 exception UnknownInterp of notation * scopes
558
559 let explain_unknown_interp ntn scopes =
560 let find_inactive sc =
561 match fst (NotationMap.find ntn (find_scope sc).notations) with
562 | OnlyParsingData (active,_) | ParsingAndPrintingData (active,_,_) -> assert (not active)
563 | NoParsingData -> raise Not_found
564 in
565 let inactive_in_scope = List.filter_map (fun sc ->
566 Option.map snd @@ find_one_interpretation ntn find_inactive sc)
567 scopes
568 in
569 let unused_scope_map = List.fold_left (fun scope_map -> function
570 | OpenScopeItem sc -> String.Map.remove sc scope_map
571 | LonelyNotationItem ntn' ->
572 if notation_eq ntn ntn' then String.Map.remove default_scope scope_map
573 else scope_map)
574 !scope_map scopes
575 in
576 let out_of_scope = String.Map.fold (fun sc data acc ->
577 match fst (NotationMap.find ntn data.notations) with
578 | OnlyParsingData _ | ParsingAndPrintingData _ ->
579 let sc = if String.equal sc default_scope then None else Some sc in
580 sc :: acc
581 | NoParsingData | exception Not_found -> acc)
582 unused_scope_map []
583 in
584 let pr_scope = function
585 | None -> str "the default scope"
586 | Some sc -> str sc
587 in
588 let out_of_scope =
589 if (CList.is_empty out_of_scope) then mt()
590 else
591 spc() ++ str "This notation is available in " ++
592 pr_enum pr_scope out_of_scope ++ str "."
593 in
594 let inactive_in_scope =
595 if CList.is_empty inactive_in_scope then mt()
596 else
597 spc() ++ str "This notation is currently disabled in " ++
598 pr_enum pr_scope inactive_in_scope ++ str "."
599 in
600 str "Unknown interpretation for notation " ++ pr_notation ntn ++ str "." ++
601 inactive_in_scope ++ out_of_scope
602
603 let () = CErrors.register_handler @@ function
604 | UnknownInterp (ntn,scopes) -> Some (explain_unknown_interp ntn scopes)
605 | _ -> None
606
607 let interp_notation ?loc ntn local_scopes =
608 let scopes = make_current_scopes local_scopes in
609 try
610 let (n,sc) = find_interpretation ntn (find_notation ntn) scopes in
611 Option.iter (fun d -> warn_notation ?loc ntn d) n.not_user_warns;
612 n.not_interp, (n.not_location, sc)
613 with Not_found as exn ->
614 let _, info = Exninfo.capture exn in
615 let info = Option.cata (Loc.add_loc info) info loc in
616 Exninfo.iraise (UnknownInterp (ntn,scopes), info)
617
618 let has_active_parsing_rule_in_scope ntn sc =
619 try
620 match NotationMap.find ntn (String.Map.find sc !scope_map).notations with
621 | OnlyParsingData (active,_),_ | ParsingAndPrintingData (active,_,_),_ -> active
622 | _ -> false
623 with Not_found -> false
624
625 let is_printing_active_in_scope (scope,ntn) pat =
626 let sc = match scope with NotationInScope sc -> sc | LastLonelyNotation -> default_scope in
627 let is_active extra =
628 try
629 let (_,(active,_)) = List.extract_first (fun (active,d) -> interpretation_eq d.not_interp pat) extra in
630 active
631 with Not_found -> false in
632 try
633 match NotationMap.find ntn (String.Map.find sc !scope_map).notations with
634 | ParsingAndPrintingData (_,active,d), extra ->
635 if interpretation_eq d.not_interp pat then active
636 else is_active extra
637 | _, extra -> is_active extra
638 with Not_found -> false
639
640 let is_printing_inactive_rule rule pat =
641 match rule with
642 | NotationRule (scope,ntn) ->
643 not (is_printing_active_in_scope (scope,ntn) pat)
644 | AbbrevRule kn ->
645 try let _ = Nametab.path_of_abbreviation kn in false with Not_found -> true
646
647 let availability_of_notation (ntn_scope,ntn) scopes =
648 find_without_delimiters (has_active_parsing_rule_in_scope ntn) (ntn_scope,Some ntn) (make_current_scopes scopes)
649
650 (* We support coercions from a custom entry at some level to an entry
651 at some level (possibly the same), and from and to the constr entry. E.g.:
652
653 Notation "[ expr ]" := expr (expr custom group at level 1).
654 Notation "( x )" := x (in custom group at level 0, x at level 1).
655 Notation "{ x }" := x (in custom group at level 0, x constr).
656
657 Supporting any level is maybe overkill in that coercions are
658 commonly from the lowest level of the source entry to the highest
659 level of the target entry. *)
660
661 type entry_coercion = (notation_with_optional_scope * notation) list
662
663 module EntryCoercionOrd =
664 struct
665 type t = notation_entry * notation_entry
666 let compare (e1,e2) (e1',e2') =
667 let c = Notationextern.notation_entry_compare e1 e1' in
668 if c <> 0 then c
669 else Notationextern.notation_entry_compare e2 e2'
670 end
671
672 module EntryCoercionMap = Map.Make(EntryCoercionOrd)
673
674 (* We index coercions by pairs of entry names to avoid a full linear search *)
675 let entry_coercion_map : (((entry_level * entry_relative_level) * entry_coercion) list EntryCoercionMap.t) ref =
676 ref EntryCoercionMap.empty
677
678 let sublevel_ord lev lev' =
679 match lev, lev' with
680 | _, LevelSome -> true
681 | LevelSome, _ -> false
682 | LevelLt n, LevelLt n' | LevelLe n, LevelLe n' -> n <= n'
683 | LevelLt n, LevelLe n' -> n < n'
684 | LevelLe n, LevelLt n' -> n <= n'-1
685
686 let is_coercion
687 { notation_entry = e1; notation_level = n1 }
688 { notation_subentry = e2; notation_relative_level = n2 } =
689 not (notation_entry_eq e1 e2) ||
690 match n2 with
691 | LevelLt n2 | LevelLe n2 -> n1 < n2
692 | LevelSome -> true (* unless n2 is the entry top level but we shall know it only dynamically *)
693
694 let included
695 { notation_entry = e1; notation_level = n1 }
696 { notation_subentry = e2; notation_relative_level = n2 } =
697 notation_entry_eq e1 e2 && entry_relative_level_le n1 n2
698
699 let rec search nfrom nto = function
700 | [] -> raise Not_found
701 | ((pfrom,pto),coe)::l ->
702 if entry_relative_level_le pfrom nfrom && entry_relative_level_le nto pto then coe else search nfrom nto l
703
704 let availability_of_entry_coercion ?(non_included=false)
705 ({ notation_subentry = entry; notation_relative_level = sublev } as entry_sublev)
706 ({ notation_entry = entry'; notation_level = lev' } as entry_lev) =
707 if included entry_lev entry_sublev && not non_included then
708 (* [entry] is by default included in [relative_entry] *)
709 Some []
710 else
711 try Some (search sublev lev' (EntryCoercionMap.find (entry,entry') !entry_coercion_map))
712 with Not_found -> None
713
714 let better_path ((lev1,sublev2),path) ((lev1',sublev2'),path') =
715 (* better = shorter and lower source and higher target *)
716 lev1 <= lev1' && sublevel_ord sublev2' sublev2 && List.length path <= List.length path'
717
718 let rec insert_coercion_path path = function
719 | [] -> [path]
720 | path'::paths as allpaths ->
721 (* If better or equal we keep the more recent one *)
722 if better_path path path' then path::paths
723 else if better_path path' path then allpaths
724 else path'::insert_coercion_path path paths
725
726 let declare_entry_coercion ntn entry_level entry_relative_level' =
727 let { notation_entry = entry; notation_level = lev } = entry_level in
728 let { notation_subentry = entry'; notation_relative_level = sublev' } = entry_relative_level' in
729 (* Transitive closure *)
730 let toaddleft =
731 EntryCoercionMap.fold (fun (entry'',entry''') paths l ->
732 List.fold_right (fun ((lev'',sublev'''),path) l ->
733 if included entry_level
734 { notation_subentry = entry'''; notation_relative_level = sublev'''; notation_position = None } &&
735 not (included { notation_entry = entry''; notation_level = lev'' } entry_relative_level')
736 then ((entry'',entry'),((lev'',sublev'),path@[ntn]))::l else l) paths l)
737 !entry_coercion_map [] in
738 let toaddright =
739 EntryCoercionMap.fold (fun (entry'',entry''') paths l ->
740 List.fold_right (fun ((lev'',sublev'''),path) l ->
741 if included { notation_entry = entry''; notation_level = lev'' } entry_relative_level' &&
742 not (included entry_level
743 { notation_subentry = entry'''; notation_relative_level = sublev'''; notation_position = None })
744 then ((entry,entry'''),((lev,sublev'''),ntn::path))::l else l) paths l)
745 !entry_coercion_map [] in
746 entry_coercion_map :=
747 List.fold_right (fun (pair,path) ->
748 let olds = try EntryCoercionMap.find pair !entry_coercion_map with Not_found -> [] in
749 EntryCoercionMap.add pair (insert_coercion_path path olds))
750 (((entry,entry'),((lev,sublev'),[ntn]))::toaddright@toaddleft)
751 !entry_coercion_map
752
753 (* Hard-wired coercion in constr corresponding to "( x )" *)
754 let _ = entry_coercion_map := (EntryCoercionMap.add (InConstrEntry,InConstrEntry) [(0,LevelSome),[]] !entry_coercion_map)
755
756 let entry_has_global_map = ref CustomName.Map.empty
757
758 let declare_custom_entry_has_global s n =
759 try
760 let p = CustomName.Map.find s !entry_has_global_map in
761 user_err (str "Custom entry " ++ Nametab.CustomEntries.pr s ++
762 str " has already a rule for global references at level " ++ int p ++ str ".")
763 with Not_found ->
764 entry_has_global_map := CustomName.Map.add s n !entry_has_global_map
765
766 let entry_has_global { notation_subentry = entry; notation_relative_level = n } =
767 match entry with
768 | InConstrEntry -> true
769 | InCustomEntry s ->
770 try entry_relative_level_le (CustomName.Map.find s !entry_has_global_map) n with Not_found -> false
771
772 let entry_has_ident_map = ref CustomName.Map.empty
773
774 let declare_custom_entry_has_ident s n =
775 try
776 let p = CustomName.Map.find s !entry_has_ident_map in
777 user_err (str "Custom entry " ++ Nametab.CustomEntries.pr s ++
778 str " has already a rule for global references at level " ++ int p ++ str ".")
779 with Not_found ->
780 entry_has_ident_map := CustomName.Map.add s n !entry_has_ident_map
781
782 let entry_has_ident { notation_subentry = entry; notation_relative_level = n } =
783 match entry with
784 | InConstrEntry -> true
785 | InCustomEntry s ->
786 try entry_relative_level_le (CustomName.Map.find s !entry_has_ident_map) n with Not_found -> false
787
788 let app_level = 10
789
790 let prec_less child = function
791 | LevelLt parent -> child < parent
792 | LevelLe parent -> child <= parent
793 | LevelSome -> true
794
795 let may_capture_cont_after child parent =
796 match child with
797 | None -> false
798 | Some lev_after -> prec_less lev_after parent
799
800 type entry_coercion_kind =
801 | IsEntryCoercion of notation_entry_level * notation_entry_relative_level
802 | IsEntryGlobal of CustomName.t * int
803 | IsEntryIdent of CustomName.t * int
804
805 let declare_notation (scopt,ntn) pat df ~use coe user_warns =
806 (* Register the interpretation *)
807 let scope = match scopt with NotationInScope s -> s | LastLonelyNotation -> default_scope in
808 let sc = find_scope scope in
809 let notdata = {
810 not_interp = pat;
811 not_location = df;
812 not_user_warns = user_warns;
813 } in
814 let notation_update,printing_update = update_notation_data (scopt,ntn) use notdata sc.notations in
815 let sc = { sc with notations = notation_update } in
816 scope_map := String.Map.add scope sc !scope_map;
817 (* Register visibility of lonely notations *)
818 begin match scopt with
819 | LastLonelyNotation -> scope_stack := LonelyNotationItem ntn :: !scope_stack
820 | NotationInScope _ -> ()
821 end;
822 (* Declare a possible coercion *)
823 if use <> OnlyParsing then begin match coe with
824 | Some (IsEntryCoercion (entry,subentry)) -> declare_entry_coercion (scopt,ntn) entry subentry
825 | Some (IsEntryGlobal (entry,n)) -> declare_custom_entry_has_global entry n
826 | Some (IsEntryIdent (entry,n)) -> declare_custom_entry_has_ident entry n
827 | None ->
828 (* Update the uninterpretation cache *)
829 begin match printing_update with
830 | Some pat -> remove_uninterpretation (Global.env ()) (NotationRule (scopt,ntn)) pat
831 | None -> ()
832 end;
833 declare_uninterpretation (Global.env ()) (NotationRule (scopt,ntn)) pat
834 end
835
836 let availability_of_prim_token n printer_scope local_scopes =
837 let f scope =
838 match String.Map.find_opt scope !prim_token_interp_infos with
839 | None -> false
840 | Some (_, uid) -> PrimNotations.can_interp uid n
841 in
842 let scopes = make_current_scopes local_scopes in
843 Option.map snd (find_without_delimiters f (NotationInScope printer_scope,None) scopes)
844
845 let rec find_uninterpretation need_delim def find = function
846 | [] ->
847 CList.find_map_exn
848 (fun (sc,_,_) -> try Some (find need_delim sc) with Not_found -> None)
849 def
850 | OpenScopeItem scope :: scopes ->
851 (try find need_delim scope
852 with Not_found -> find_uninterpretation need_delim def find scopes) (* TODO: here we should also update the need_delim list with all regular notations in scope [scope] that could shadow a number notation *)
853 | LonelyNotationItem ntn::scopes ->
854 find_uninterpretation (ntn::need_delim) def find scopes
855
856 let uninterp_prim_token ~print_float c local_scopes =
857 match glob_prim_constr_key c with
858 | None -> raise Notation_ops.No_match
859 | Some r ->
860 let uninterp (sc,(info,_)) =
861 match PrimNotations.do_uninterp ~print_float info c with
862 | None -> None
863 | Some n -> Some (sc,n)
864 in
865 let add_key (sc,n) =
866 Option.map (fun k -> sc,n,k) (availability_of_prim_token n sc local_scopes) in
867 let l =
868 try GlobRefMap.find (Global.env ()) r !prim_token_uninterp_infos
869 with Not_found -> raise Notation_ops.No_match in
870 let l = List.map_filter uninterp l in
871 let l = List.map_filter add_key l in
872 let find need_delim sc =
873 let _,n,k = List.find (fun (sc',_,_) -> String.equal sc' sc) l in
874 if k <> None then n,k else
875 let hidden =
876 List.exists
877 (fun n' -> notation_eq n' (notation_of_prim_token n))
878 need_delim in
879 if not hidden then n,k else
880 match (String.Map.find sc !scope_map).delimiters with
881 | Some k -> n,Some k
882 | None -> raise Not_found
883 in
884 let scopes = make_current_scopes local_scopes in
885 try find_uninterpretation [] l find scopes
886 with Not_found -> match l with (_,n,k)::_ -> n,k | [] -> raise Notation_ops.No_match
887
888 let uninterp_prim_token_cases_pattern ~print_float c local_scopes =
889 match glob_constr_of_closed_cases_pattern (Global.env()) c with
890 | exception Not_found -> raise Notation_ops.No_match
891 | na,c -> let (sc,n) = uninterp_prim_token ~print_float c local_scopes in (na,sc,n)
892
893 (* Miscellaneous *)
894
895 let isNVar_or_NHole = function NVar _ | NHole _ -> true | _ -> false
896
897 (**********************************************************************)
898 (* Mapping classes to scopes *)
899
900 open Coercionops
901
902 type scope_class = cl_typ
903
904 let scope_class_compare : scope_class -> scope_class -> int =
905 cl_typ_ord
906
907 let compute_scope_class env sigma t =
908 let (cl,_,_) = find_class_type env sigma t in
909 cl
910
911 module ScopeClassOrd =
912 struct
913 type t = scope_class
914 let compare = scope_class_compare
915 end
916
917 module ScopeClassMap = Map.Make(ScopeClassOrd)
918
919 (* pairs of Top and Bottom additions (Boolean is for locality) *)
920 type scope_class_map =
921 ((scope_name * bool) list * (scope_name * bool) list) ScopeClassMap.t
922
923 let initial_scope_class_map : scope_class_map =
924 ScopeClassMap.empty
925
926 let scope_class_map = ref initial_scope_class_map
927
928 type add_scope_where = AddScopeTop | AddScopeBottom
929
930 let declare_scope_class islocal sc ?where cl =
931 let map = match where with
932 | None ->
933 ScopeClassMap.add cl ([sc, islocal], []) !scope_class_map
934 | Some where ->
935 let add (scl1,scl2) = match where with AddScopeTop -> ((sc,islocal) :: scl1, scl2) | AddScopeBottom -> (scl1, scl2 @ [sc,islocal]) in
936 let scl = try ScopeClassMap.find cl !scope_class_map with Not_found -> ([],[]) in
937 ScopeClassMap.add cl (add scl) !scope_class_map in
938 scope_class_map := map
939
940 let find_scope_class_blocks_opt map = function
941 | None -> [], []
942 | Some cl ->
943 try
944 let ltop, lbot = ScopeClassMap.find cl map in
945 List.map fst ltop, List.map fst lbot
946 with Not_found -> [], []
947
948 let find_scope_class_opt map cl =
949 let ltop, lbot = find_scope_class_blocks_opt map cl in
950 ltop @ lbot
951
952 (**********************************************************************)
953 (* Special scopes associated to arguments of a global reference *)
954
955 let compute_telescope env sigma typ =
956 let open CClosure in
957 let infos = Evarutil.create_clos_infos env sigma RedFlags.betaiotazeta in
958 let tab = create_tab () in
959 let rec apply_rec typ accu =
960 let typ, stk = whd_stack infos tab typ [] in
961 match fterm_of typ with
962 | FProd (na, c1, c2, e) ->
963 let c1 = EConstr.of_constr @@ term_of_fconstr c1 in
964 let c2 = mk_clos (CClosure.usubs_lift e) c2 in
965 apply_rec c2 ((EConstr.of_binder_annot na, c1) :: accu)
966 | _ -> List.rev accu
967 in
968 apply_rec (CClosure.inject (EConstr.Unsafe.to_constr typ)) []
969
970 let compute_arguments_classes env sigma t =
971 let telescope = compute_telescope env sigma t in
972 let rec aux env = function
973 | (na, t) :: decls ->
974 let cl = try Some (compute_scope_class env sigma t) with Not_found -> None in
975 let env = EConstr.push_rel (Context.Rel.Declaration.LocalAssum (na, t)) env in
976 cl :: aux env decls
977 | [] -> []
978 in
979 aux env telescope
980
981 let compute_arguments_scope_full env sigma map t =
982 let cls = compute_arguments_classes env sigma t in
983 let scs = List.map (find_scope_class_opt map) cls in
984 scs, cls
985
986 let compute_arguments_scope env sigma t =
987 fst (compute_arguments_scope_full env sigma !scope_class_map t)
988
989 let compute_type_scope env sigma t =
990 find_scope_class_opt !scope_class_map (try Some (compute_scope_class env sigma t) with Not_found -> None)
991
992 let current_type_scope_names () =
993 find_scope_class_opt !scope_class_map (Some CL_SORT)
994
995 let compute_glob_type_scope t =
996 find_scope_class_opt !scope_class_map (try Some (find_class_glob_type t) with Not_found -> None)
997
998 let scope_class_of_class (x : cl_typ) : scope_class =
999 x
1000
1001 (** Updating a scope list, thanks to a list of argument classes
1002 and the current Bind Scope base. When some current scope
1003 have been manually given, the corresponding argument class
1004 is emptied below, so this manual scope will be preserved. That is,
1005 cls and scl have this form:
1006
1007 dynam. recomputed
1008 when out of sync manual
1009 /----------\ /-----------\
1010 scl = sc1 ... scn sc1' ... scn'
1011 cls = cl1 ... cln empty list
1012 \----------/
1013 static. computed
1014 at cache/rebuild time
1015 *)
1016
1017 let update_scope sco cl =
1018 let (sctop,scbot) = find_scope_class_blocks_opt !scope_class_map cl in
1019 let sco = List.filter (fun sc -> not (List.exists (String.equal sc) sctop || List.exists (String.equal sc) scbot)) sco in
1020 sctop@sco@scbot
1021
1022 let rec update_scopes cls scl = match cls, scl with
1023 | [], _ -> scl
1024 | _, [] -> List.map (update_scope []) cls
1025 | cl :: cls, sco :: scl -> update_scope sco cl :: update_scopes cls scl
1026
1027 let arguments_scope = ref GlobRefMap.empty
1028
1029 type arguments_scope_discharge_request =
1030 | ArgsScopeAuto
1031 | ArgsScopeManual
1032 | ArgsScopeNoDischarge
1033
1034 let load_arguments_scope _ (_,r,scl,cls,allscopes) =
1035 List.iter (List.iter check_scope) scl;
1036 (* force recomputation to take into account the possible extra "Bind
1037 Scope" of the current environment (e.g. so that after inlining of a
1038 parameter in a functor, it takes the current environment into account *)
1039 let initial_stamp = initial_scope_class_map in
1040 arguments_scope := GlobRefMap.add (Global.env ()) r (scl,cls,initial_stamp) !arguments_scope
1041
1042 let cache_arguments_scope o =
1043 load_arguments_scope 1 o
1044
1045 let subst_scope_class env subst cs =
1046 try Some (subst_cl_typ env subst cs) with Not_found -> None
1047
1048 let subst_arguments_scope (subst,(req,r,scl,cls,allscopes)) =
1049 let r' = fst (subst_global subst r) in
1050 let subst_cl ocl = match ocl with
1051 | None -> ocl
1052 | Some cl ->
1053 let env = Global.env () in
1054 match subst_scope_class env subst cl with
1055 | Some cl' as ocl' when cl' != cl -> ocl'
1056 | _ -> ocl in
1057 let cls' = List.Smart.map subst_cl cls in
1058 (ArgsScopeNoDischarge,r',scl,cls',allscopes)
1059
1060 let discharge_available_scopes map =
1061 (* Remove local scopes *)
1062 ScopeClassMap.filter_map (fun cl (ltop, lbot) ->
1063 let ltop = List.filter (fun x -> not (snd x)) ltop in
1064 let lbot = List.filter (fun x -> not (snd x)) lbot in
1065 if List.is_empty ltop && List.is_empty lbot then None else Some (ltop, lbot)) map
1066
1067 let discharge_arguments_scope (req,r,scs,_cls,available_scopes) =
1068 if req == ArgsScopeNoDischarge || (isVarRef r && Global.is_in_section r) then None
1069 else
1070 let n =
1071 try
1072 Array.length (Global.section_instance r)
1073 with
1074 Not_found (* Not a ref defined in this section *) -> 0 in
1075 let available_scopes = discharge_available_scopes available_scopes in
1076 (* Hack: use list cls to encode an integer to pass to rebuild for Manual case *)
1077 (* since cls is anyway recomputed in rebuild *)
1078 let n_as_cls = List.make n None in
1079 Some (req,r,scs,n_as_cls,available_scopes)
1080
1081 let classify_arguments_scope (req,_,_,_,_) =
1082 if req == ArgsScopeNoDischarge then Dispose else Substitute
1083
1084 let rebuild_arguments_scope (req,r,scs,n_as_cls,available_scopes) =
1085 match req with
1086 | ArgsScopeNoDischarge -> assert false
1087 | ArgsScopeAuto ->
1088 let env = Global.env () in
1089 let sigma = Evd.from_env env in
1090 let typ = EConstr.of_constr @@ fst (Typeops.type_of_global_in_context env r) in
1091 let scs,cls = compute_arguments_scope_full env sigma available_scopes typ in
1092 (* Note: cls is fixed, but scs can be recomputed in find_arguments_scope *)
1093 (req,r,scs,cls,available_scopes)
1094 | ArgsScopeManual ->
1095 (* Add to the manually given scopes the one found automatically
1096 for the extra parameters of the section. Discard the classes
1097 of the manually given scopes to avoid further re-computations. *)
1098 let env = Global.env () in
1099 let sigma = Evd.from_env env in
1100 let n = List.length n_as_cls in
1101 let typ = EConstr.of_constr @@ fst (Typeops.type_of_global_in_context env r) in
1102 let scs',cls = compute_arguments_scope_full env sigma available_scopes typ in
1103 let scs1 = List.firstn n scs' in
1104 let cls1 = List.firstn n cls in
1105 (* Note: the extra cls1 is fixed, but its associated scs can be recomputed *)
1106 (* on the undefined part of cls, scs is however fixed *)
1107 (req,r,scs1@scs,cls1,available_scopes)
1108
1109 type arguments_scope_obj =
1110 arguments_scope_discharge_request * GlobRef.t *
1111 scope_name list list * scope_class option list *
1112 scope_class_map
1113
1114 let inArgumentsScope : arguments_scope_obj -> obj =
1115 declare_object {(default_object "ARGUMENTS-SCOPE") with
1116 cache_function = cache_arguments_scope;
1117 load_function = load_arguments_scope;
1118 subst_function = subst_arguments_scope;
1119 classify_function = classify_arguments_scope;
1120 discharge_function = discharge_arguments_scope;
1121 rebuild_function = rebuild_arguments_scope }
1122
1123 let is_local local ref = local || isVarRef ref && Global.is_in_section ref
1124
1125 let declare_arguments_scope_gen req r (scl,cls) =
1126 Lib.add_leaf (inArgumentsScope (req,r,scl,cls,!scope_class_map))
1127
1128 let declare_arguments_scope local r scl =
1129 let req = if is_local local r then ArgsScopeNoDischarge else ArgsScopeManual in
1130 (* We empty the list of argument classes to disable further scope
1131 re-computations and keep these manually given scopes. *)
1132 declare_arguments_scope_gen req r (scl,[])
1133
1134 let find_arguments_scope env r =
1135 try
1136 let (scl,cls,stamp) = GlobRefMap.find env r !arguments_scope in
1137 let cur_stamp = !scope_class_map in
1138 if stamp == cur_stamp then scl
1139 else
1140 (* Recent changes in the Bind Scope base, we re-compute the scopes *)
1141 let scl' = update_scopes cls scl in
1142 arguments_scope := GlobRefMap.add env r (scl',cls,cur_stamp) !arguments_scope;
1143 scl'
1144 with Not_found -> []
1145
1146 let declare_ref_arguments_scope ref =
1147 let env = Global.env () in (* FIXME? *)
1148 let sigma = Evd.from_env env in
1149 let typ = EConstr.of_constr @@ fst @@ Typeops.type_of_global_in_context env ref in
1150 (* cls is fixed but scs is only an initial value that can be modified in find_arguments_scope *)
1151 let (scs,cls as o) = compute_arguments_scope_full env sigma !scope_class_map typ in
1152 declare_arguments_scope_gen ArgsScopeAuto ref o
1153
1154 (********************************)
1155 (* Encoding notations as string *)
1156
1157 type symbol =
1158 | Terminal of string
1159 | NonTerminal of Id.t
1160 | SProdList of Id.t * symbol list
1161 | Break of int
1162
1163 let rec symbol_eq s1 s2 = match s1, s2 with
1164 | Terminal s1, Terminal s2 -> String.equal s1 s2
1165 | NonTerminal id1, NonTerminal id2 -> Id.equal id1 id2
1166 | SProdList (id1, l1), SProdList (id2, l2) ->
1167 Id.equal id1 id2 && List.equal symbol_eq l1 l2
1168 | Break i1, Break i2 -> Int.equal i1 i2
1169 | _ -> false
1170
1171 let rec string_of_symbol = function
1172 | NonTerminal _ -> ["_"]
1173 | Terminal "_" -> ["'_'"]
1174 (* Symbols starting with a double quote without denoting a string are single quoted *)
1175 | Terminal s when s.[0] = '"' && (String.length s = 1 || s.[String.length s - 1] <> '"') -> ["'" ^ s ^ "'"]
1176 | Terminal s -> [s]
1177 | SProdList (_,l) ->
1178 let l = List.flatten (List.map string_of_symbol l) in "_"::l@".."::l@["_"]
1179 | Break _ -> []
1180
1181 let make_notation_key from symbols =
1182 (from,String.concat " " (List.flatten (List.map string_of_symbol symbols)))
1183
1184 let decompose_notation_pure_key s =
1185 let len = String.length s in
1186 let rec find_string_end n =
1187 let next =
1188 try String.index_from s (n+1) '"'
1189 with Not_found -> assert false
1190 in
1191 if next = len - 1 then next+1
1192 else if s.[next+1] = '"' then (* skip doubled double quotes: *) find_string_end (next+2)
1193 else next+1 in
1194 let rec decomp_ntn dirs n =
1195 if n>=len then List.rev dirs else
1196 let pos =
1197 if s.[n] = '"' then find_string_end n
1198 else
1199 try
1200 String.index_from s n ' '
1201 with Not_found -> len
1202 in
1203 let tok =
1204 match String.sub s n (pos-n) with
1205 | "_" -> NonTerminal (Id.of_string "_")
1206 | s -> Terminal (String.drop_simple_quotes s) in
1207 decomp_ntn (tok::dirs) (pos+1)
1208 in
1209 decomp_ntn [] 0
1210
1211 let decompose_notation_key (from,s) =
1212 from, decompose_notation_pure_key s
1213
1214 let is_prim_token_constant_in_constr (entry, symbs) =
1215 match entry, List.filter (function Break _ -> false | _ -> true) symbs with
1216 (* Is this a numeral? *)
1217 | InConstrEntry, ([Terminal "-"; Terminal x] | [Terminal x]) when NumTok.Unsigned.parse_string x <> None -> true
1218 (* Is this a string constant? *)
1219 | InConstrEntry, [Terminal x] when let n = String.length x in n > 1 && x.[0] = '"' && x.[n-1] = '"' -> true
1220 | _ -> false
1221
1222 let level_of_notation ntn =
1223 if is_prim_token_constant_in_constr (decompose_notation_key ntn) then
1224 (* A primitive notation *)
1225 ({ notation_entry = fst ntn; notation_level = 0}, []) (* TODO: string notations*)
1226 else
1227 NotationMap.find ntn !notation_level_map
1228
1229 (************)
1230 (* Printing *)
1231
1232 let pr_delimiters_info = function
1233 | None -> str "No delimiting key"
1234 | Some key -> str "Delimiting key is " ++ str key
1235
1236 let classes_of_scope sc =
1237 let map = !scope_class_map in
1238 ScopeClassMap.fold (fun cl (scltop,sclbot) l ->
1239 if List.exists (fun (sc',_) -> String.equal sc sc') scltop ||
1240 List.exists (fun (sc',_) -> String.equal sc sc') sclbot
1241 then cl::l else l) map []
1242
1243 let pr_scope_class = pr_class
1244
1245 let pr_scope_classes sc =
1246 let l = classes_of_scope sc in
1247 match l with
1248 | [] -> mt ()
1249 | _ :: ll ->
1250 let opt_s = match ll with [] -> mt () | _ -> str "es" in
1251 hov 0 (str "Bound to class" ++ opt_s ++
1252 spc() ++ prlist_with_sep spc pr_scope_class l)
1253
1254 let pr_notation_status on_parsing on_printing =
1255 let disabled b = if b then [] else ["disabled"] in
1256 let l = match on_parsing, on_printing with
1257 | Some on, None -> "only parsing" :: disabled on
1258 | None, Some on -> "only printing" :: disabled on
1259 | Some false, Some false -> ["disabled"]
1260 | Some true, Some false -> ["disabled for printing"]
1261 | Some false, Some true -> ["disabled for parsing"]
1262 | Some true, Some true -> []
1263 | None, None -> assert false in
1264 match l with
1265 | [] -> mt ()
1266 | l -> str "(" ++ prlist_with_sep pr_comma str l ++ str ")"
1267
1268 let pr_non_empty spc pp =
1269 if pp = mt () then mt () else spc ++ pp
1270
1271 let pr_notation_data prglob (on_parsing,on_printing,{ not_interp = (_, r); not_location = (_, df) }) =
1272 hov 0 (Notation_ops.pr_notation_info prglob df r ++ pr_non_empty (brk(1,2)) (pr_notation_status on_parsing on_printing))
1273
1274 let extract_notation_data (main,extra) =
1275 let main = match main with
1276 | NoParsingData -> []
1277 | ParsingAndPrintingData (on_parsing, on_printing, d) ->
1278 [Some on_parsing, Some on_printing, d]
1279 | OnlyParsingData (on_parsing, d) ->
1280 [Some on_parsing, None, d] in
1281 let extra = List.map (fun (on_printing, d) -> (None, Some on_printing, d)) extra in
1282 main @ extra
1283
1284 let pr_named_scope prglob (scope,sc) =
1285 (if String.equal scope default_scope then
1286 match NotationMap.cardinal sc.notations with
1287 | 0 -> str "No lonely notation"
1288 | n -> str (String.plural n "Lonely notation")
1289 else
1290 str "Scope " ++ str scope ++ fnl () ++ pr_delimiters_info sc.delimiters)
1291 ++ pr_non_empty (fnl ()) (pr_scope_classes scope)
1292 ++ prlist (fun a -> fnl () ++ pr_notation_data prglob a)
1293 (NotationMap.fold (fun ntn data l -> extract_notation_data data @ l) sc.notations [])
1294
1295 let pr_scope prglob scope = pr_named_scope prglob (scope, find_scope scope)
1296
1297 let pr_scopes prglob =
1298 let l = String.Map.bindings !scope_map in
1299 prlist_with_sep (fun () -> fnl () ++ fnl ()) (pr_named_scope prglob) l
1300
1301 let rec find_default ntn = function
1302 | [] -> None
1303 | OpenScopeItem scope :: scopes ->
1304 if has_active_parsing_rule_in_scope ntn scope then Some scope
1305 else find_default ntn scopes
1306 | LonelyNotationItem ntn' :: scopes ->
1307 if notation_eq ntn ntn' then Some default_scope
1308 else find_default ntn scopes
1309
1310 let factorize_entries = function
1311 | [] -> []
1312 | (ntn,sc',c)::l ->
1313 let (ntn,l_of_ntn,rest) =
1314 List.fold_left
1315 (fun (a',l,rest) (a,sc,c) ->
1316 if notation_eq a a' then (a',(sc,c)::l,rest) else (a,[sc,c],(a',l)::rest))
1317 (ntn,[sc',c],[]) l in
1318 (ntn,l_of_ntn)::rest
1319
1320 type symbol_token = WhiteSpace of int | String of string
1321
1322 let split_notation_string str =
1323 let push_token beg i l =
1324 if Int.equal beg i then l else
1325 let s = String.sub str beg (i - beg) in
1326 String s :: l
1327 in
1328 let push_whitespace beg i l =
1329 if Int.equal beg i then l else WhiteSpace (i-beg) :: l
1330 in
1331 let rec loop beg i =
1332 if i < String.length str then
1333 if str.[i] == ' ' then
1334 push_token beg i (loop_on_whitespace (i+1) (i+1))
1335 else if beg = i && str.[i] = '"' then
1336 loop_on_string i (i+1)
1337 else
1338 loop beg (i+1)
1339 else
1340 push_token beg i []
1341 and loop_on_whitespace beg i =
1342 if i < String.length str then
1343 if str.[i] != ' ' then
1344 push_whitespace beg i (loop i i)
1345 else
1346 loop_on_whitespace beg (i+1)
1347 else
1348 push_whitespace beg i []
1349 and loop_on_string beg i =
1350 (* we accept any string, possibly with spaces, single quotes, and
1351 doubled double quotes inside, but necessarily ended with a unique
1352 double quote followed either by a space or the end of the
1353 notation string *)
1354 if i < String.length str then
1355 if str.[i] = '"' then
1356 if i+1 < String.length str then
1357 if str.[i+1] = '"' then (* double quote in the string: *) loop_on_string beg (i+2)
1358 else if str.[i+1] = ' ' then (* end of the string: *) push_token beg (i+1) (loop_on_whitespace (i+2) (i+2))
1359 else user_err (Pp.str "End of quoted string not followed by a space in notation.")
1360 else push_token beg (i+1) []
1361 else loop_on_string beg (i+1)
1362 else user_err (Pp.str "Unterminated string in notation.")
1363 (* we accept any sequences of non-space symbols starting with a
1364 single quote, up to the next space or end of notation string;
1365 double quotes and single quotes not followed by a space or the
1366 end of notation string are allowed;
1367 note that if the resulting sequence ends with a single quote,
1368 the two extreme single quotes will eventually be removed *)
1369 in
1370 loop 0 0
1371
1372 let rec raw_analyze_notation_tokens = function
1373 | [] -> []
1374 | String ".." :: sl -> NonTerminal Notation_ops.ldots_var :: raw_analyze_notation_tokens sl
1375 | String "_" :: _ -> user_err Pp.(str "_ must be quoted.")
1376 | String x :: sl when Id.is_valid x ->
1377 NonTerminal (Names.Id.of_string x) :: raw_analyze_notation_tokens sl
1378 | String s :: sl ->
1379 Terminal (String.drop_simple_quotes s) :: raw_analyze_notation_tokens sl
1380 | WhiteSpace n :: sl ->
1381 Break n :: raw_analyze_notation_tokens sl
1382
1383 let rec raw_analyze_anonymous_notation_tokens = function
1384 | [] -> []
1385 | String ".." :: sl -> NonTerminal Notation_ops.ldots_var :: raw_analyze_anonymous_notation_tokens sl
1386 | String "_" :: sl -> NonTerminal (Id.of_string "dummy") :: raw_analyze_anonymous_notation_tokens sl
1387 | String s :: sl ->
1388 Terminal (String.drop_simple_quotes s) :: raw_analyze_anonymous_notation_tokens sl
1389 | WhiteSpace n :: sl -> raw_analyze_anonymous_notation_tokens sl
1390
1391 (* Interpret notations with a recursive component *)
1392
1393 type notation_symbols = {
1394 recvars : (Id.t * Id.t) list; (* pairs (x,y) as in [ x ; .. ; y ] *)
1395 mainvars : Id.t list; (* variables non involved in a recursive pattern *)
1396 symbols : symbol list; (* the decomposition of the notation into terminals and nonterminals *)
1397 }
1398
1399 let out_nt = function NonTerminal x -> x | _ -> assert false
1400
1401 let msg_expected_form_of_recursive_notation =
1402 "In the notation, the special symbol \"..\" must occur in\na configuration of the form \"x symbs .. symbs y\"."
1403
1404 let rec find_pattern nt xl = function
1405 | Break n as x :: l, Break n' :: l' when Int.equal n n' ->
1406 find_pattern nt (x::xl) (l,l')
1407 | Terminal s as x :: l, Terminal s' :: l' when String.equal s s' ->
1408 find_pattern nt (x::xl) (l,l')
1409 | [], NonTerminal x' :: l' ->
1410 (out_nt nt,x',List.rev xl),l'
1411 | _, Break s :: _ | Break s :: _, _ ->
1412 user_err Pp.(str ("A break occurs on one side of \"..\" but not on the other side."))
1413 | _, Terminal s :: _ | Terminal s :: _, _ ->
1414 user_err
1415 (str "The token \"" ++ str s ++ str "\" occurs on one side of \"..\" but not on the other side.")
1416 | _, [] ->
1417 user_err Pp.(str msg_expected_form_of_recursive_notation)
1418 | ((SProdList _ | NonTerminal _) :: _), _ | _, (SProdList _ :: _) ->
1419 anomaly (Pp.str "Only Terminal or Break expected on left, non-SProdList on right.")
1420
1421 let rec interp_list_parser hd = function
1422 | [] -> [], List.rev hd
1423 | NonTerminal id :: tl when Id.equal id Notation_ops.ldots_var ->
1424 if List.is_empty hd then user_err Pp.(str msg_expected_form_of_recursive_notation);
1425 let hd = List.rev hd in
1426 let ((x,y,sl),tl') = find_pattern (List.hd hd) [] (List.tl hd,tl) in
1427 let xyl,tl'' = interp_list_parser [] tl' in
1428 (* We remember each pair of variable denoting a recursive part to *)
1429 (* remove the second copy of it afterwards *)
1430 (x,y)::xyl, SProdList (x,sl) :: tl''
1431 | (Terminal _ | Break _) as s :: tl ->
1432 if List.is_empty hd then
1433 let yl,tl' = interp_list_parser [] tl in
1434 yl, s :: tl'
1435 else
1436 interp_list_parser (s::hd) tl
1437 | NonTerminal _ as x :: tl ->
1438 let xyl,tl' = interp_list_parser [x] tl in
1439 xyl, List.rev_append hd tl'
1440 | SProdList _ :: _ -> anomaly (Pp.str "Unexpected SProdList in interp_list_parser.")
1441
1442 let get_notation_vars l =
1443 List.map_filter (function NonTerminal id | SProdList (id,_) -> Some id | _ -> None) l
1444
1445 let decompose_raw_notation ntn =
1446 let l = split_notation_string ntn in
1447 let symbols = raw_analyze_notation_tokens l in
1448 let recvars, symbols = interp_list_parser [] symbols in
1449 let mainvars = get_notation_vars symbols in
1450 {recvars; mainvars; symbols}
1451
1452 let interpret_notation_string ntn =
1453 (* We collect the possible interpretations of a notation string depending on whether it is
1454 in "x 'U' y" or "_ U _" format *)
1455 let toks = split_notation_string ntn in
1456 let toks =
1457 if
1458 List.exists (function String "_" -> true | _ -> false) toks ||
1459 List.for_all (function String id -> Id.is_valid id | _ -> false) toks
1460 then
1461 (* Only "_ U _" format *)
1462 raw_analyze_anonymous_notation_tokens toks
1463 else
1464 (* Includes the case of only a subset of tokens or an "x 'U' y"-style format *)
1465 raw_analyze_notation_tokens toks
1466 in
1467 let _,toks = interp_list_parser [] toks in
1468 let _,ntn' = make_notation_key None toks in
1469 ntn'
1470
1471 (* Tell if a non-recursive notation is an instance of a recursive one *)
1472 let is_approximation ntn ntn' =
1473 let rec aux toks1 toks2 = match (toks1, toks2) with
1474 | Terminal s1 :: toks1, Terminal s2 :: toks2 -> String.equal s1 s2 && aux toks1 toks2
1475 | NonTerminal _ :: toks1, NonTerminal _ :: toks2 -> aux toks1 toks2
1476 | SProdList (_,l1) :: toks1, SProdList (_, l2) :: toks2 -> aux l1 l2 && aux toks1 toks2
1477 | NonTerminal _ :: toks1, SProdList (_,l2) :: toks2 -> aux' toks1 l2 l2 toks2 || aux toks1 toks2
1478 | [], [] -> true
1479 | (Break _ :: _, _) | (_, Break _ :: _) -> assert false
1480 | (Terminal _ | NonTerminal _ | SProdList _) :: _, _ -> false
1481 | [], _ -> false
1482 and aux' toks1 l2 l2full toks2 = match (toks1, l2) with
1483 | Terminal s1 :: toks1, Terminal s2 :: l2 when String.equal s1 s2 -> aux' toks1 l2 l2full toks2
1484 | NonTerminal _ :: toks1, [] -> aux' toks1 l2full l2full toks2 || aux toks1 toks2
1485 | _ -> false
1486 in
1487 let _,toks = interp_list_parser [] (raw_analyze_anonymous_notation_tokens (split_notation_string ntn)) in
1488 let _,toks' = interp_list_parser [] (raw_analyze_anonymous_notation_tokens (split_notation_string ntn')) in
1489 aux toks toks'
1490
1491 let match_notation_key strict ntn ntn' =
1492 if String.contains ntn ' ' then
1493 if String.string_contains ~where:ntn' ~what:".." then is_approximation ntn ntn'
1494 else String.equal ntn ntn'
1495 else
1496 let toks = decompose_notation_pure_key ntn' in
1497 let get_terminals = function Terminal ntn -> Some ntn | _ -> None in
1498 let trms = List.map_filter get_terminals toks in
1499 if strict then String.List.equal [ntn] trms
1500 else String.List.mem ntn trms
1501
1502 let browse_notation strict ntn map =
1503 let ntn = interpret_notation_string ntn in
1504 let find (from,ntn') = match_notation_key strict ntn ntn' in
1505 let l =
1506 String.Map.fold
1507 (fun scope_name sc ->
1508 NotationMap.fold (fun ntn data l ->
1509 if find ntn
1510 then List.map (fun d -> (ntn,scope_name,d)) (extract_notation_data data) @ l
1511 else l) sc.notations)
1512 map [] in
1513 List.sort (fun x y -> String.compare (snd (pi1 x)) (snd (pi1 y))) l
1514
1515 let global_reference_of_notation ~head test (ntn,sc,(on_parsing,on_printing,{not_interp = (_,c as interp); not_location = (_, df)})) =
1516 match c with
1517 | NRef (ref,_) when test ref -> Some (on_parsing,on_printing,ntn,df,sc,interp,ref)
1518 | NApp (NRef (ref,_), l) when head || List.for_all isNVar_or_NHole l && test ref ->
1519 Some (on_parsing,on_printing,ntn,df,sc,interp,ref)
1520 | _ -> None
1521
1522 type notation_as_reference_error =
1523 | AmbiguousNotationAsReference of notation_key
1524 | NotationNotReference of Environ.env * Evd.evar_map * notation_key * (notation_key * notation_constr) list
1525
1526 exception NotationAsReferenceError of notation_as_reference_error
1527
1528 let error_ambiguous_notation ?loc ntn =
1529 Loc.raise ?loc (NotationAsReferenceError (AmbiguousNotationAsReference ntn))
1530
1531 let error_notation_not_reference ?loc ntn ntns =
1532 let ntns = List.map (fun (_,_,(_,_,{ not_interp = (_, r); not_location = (_, df) })) -> df, r) ntns in
1533 let env = Global.env () in let sigma = Evd.from_env env in
1534 Loc.raise ?loc (NotationAsReferenceError (NotationNotReference (env, sigma, ntn, ntns)))
1535
1536 let interp_notation_as_global_reference_expanded ?loc ~head test ntn sc =
1537 let scopes = match sc with
1538 | Some sc ->
1539 let scope = find_delimiters_scope sc in
1540 String.Map.singleton scope (find_scope scope)
1541 | None -> !scope_map in
1542 let ntns = browse_notation true ntn scopes in
1543 let refs = List.map (global_reference_of_notation ~head test) ntns in
1544 let make_scope sc = if String.equal sc default_scope then LastLonelyNotation else NotationInScope sc in
1545 match Option.List.flatten refs with
1546 | [Some true,_ (* why not if the only one? *),ntn,df,sc,interp,ref] -> (ntn,df,make_scope sc,interp,ref)
1547 | [] -> error_notation_not_reference ?loc ntn ntns
1548 | refs ->
1549 let f (on_parsing,_,ntn,df,sc,_,ref) =
1550 let def = find_default ntn !scope_stack in
1551 match def with
1552 | None -> false
1553 | Some sc' -> on_parsing = Some true && String.equal sc sc'
1554 in
1555 match List.filter f refs with
1556 | [_,_,ntn,df,sc,interp,ref] -> (ntn,df,make_scope sc,interp,ref)
1557 | [] -> error_notation_not_reference ?loc ntn ntns
1558 | _ -> error_ambiguous_notation ?loc ntn
1559
1560 let interp_notation_as_global_reference ?loc ~head test ntn sc =
1561 let _,_,_,_,ref = interp_notation_as_global_reference_expanded ?loc ~head test ntn sc in ref
1562
1563 let pr_id_infos (id, ((level,(tmp_scopes, scopes)), under_binders, kind)) =
1564 let scopes = List.map (fun x -> "_"^x) tmp_scopes @ scopes in
1565 match scopes with
1566 | [] -> None
1567 | _ ->
1568 (* IDK how to insert delimiters in the constr for printing
1569 so instead use "in constr" modifier even though it's ignored
1570 (#20297)
1571 Also not sure if we can ever see multiple scopes but if we do we produce invalid syntax.
1572
1573 This is why we print comment syntax "(* x in scope foo *)" instead of "(x in scope foo)". *)
1574 let pp =
1575 Id.print id ++ str " in " ++ str (CString.lplural scopes "scope") ++ spc() ++
1576 prlist_with_sep spc str scopes
1577 in
1578 Some pp
1579
1580 let pr_ids_infos ids =
1581 let pp = List.filter_map pr_id_infos ids in
1582 match pp with
1583 | [] -> mt()
1584 | _ -> spc() ++ surround (str "*" ++ spc() ++ prlist_with_sep pr_comma (fun x -> x) pp ++ spc() ++ str "*")
1585
1586 let locate_notation prglob ntn scope =
1587 let ntns = factorize_entries (browse_notation false ntn !scope_map) in
1588 let scopes = Option.fold_right push_scope scope !scope_stack in
1589 match ntns with
1590 | [] -> str "Unknown notation"
1591 | _ ->
1592 prlist_with_sep fnl (fun (ntn,l) ->
1593 let scope = find_default ntn scopes in
1594 prlist_with_sep fnl
1595 (fun (sc,(on_parsing,on_printing,{ not_interp = (ids, r); not_location = ((libpath,secpath), df) })) ->
1596 let full_path = DirPath.make (DirPath.repr secpath @ DirPath.repr libpath) in
1597 hov 2 (
1598 str "Notation" ++ spc() ++
1599 Notation_ops.pr_notation_info prglob df r ++
1600 pr_ids_infos ids ++
1601 (if String.equal sc default_scope then mt ()
1602 else (spc() ++ str ": " ++ str sc)) ++
1603 (if Option.equal String.equal (Some sc) scope
1604 then spc() ++ str "(default interpretation)" else mt ()) ++
1605 pr_non_empty (spc()) (pr_notation_status on_parsing on_printing) ++
1606 spc() ++ surround (str "from " ++ DirPath.print full_path)
1607 ))
1608 l) ntns
1609
1610 let collect_notation_in_scope scope sc known =
1611 assert (not (String.equal scope default_scope));
1612 NotationMap.fold
1613 (fun ntn d (l,known as acc) ->
1614 if List.mem_f notation_eq ntn known then acc else (extract_notation_data d @ l,ntn::known))
1615 sc.notations ([],known)
1616
1617 let collect_notations stack =
1618 fst (List.fold_left
1619 (fun (all,knownntn as acc) -> function
1620 | OpenScopeItem scope ->
1621 if String.List.mem_assoc scope all then acc
1622 else
1623 let (l,knownntn) =
1624 collect_notation_in_scope scope (find_scope scope) knownntn in
1625 ((scope,l)::all,knownntn)
1626 | LonelyNotationItem ntn ->
1627 if List.mem_f notation_eq ntn knownntn then (all,knownntn)
1628 else
1629 try
1630 let datas = extract_notation_data
1631 (NotationMap.find ntn (find_scope default_scope).notations) in
1632 let all' = match all with
1633 | (s,lonelyntn)::rest when String.equal s default_scope ->
1634 (s,datas@lonelyntn)::rest
1635 | _ ->
1636 (default_scope,datas)::all in
1637 (all',ntn::knownntn)
1638 with Not_found -> (* e.g. if only printing *) (all,knownntn))
1639 ([],[]) stack)
1640
1641 let pr_visible_in_scope prglob (scope,ntns) =
1642 let strm =
1643 List.fold_right
1644 (fun d strm -> pr_notation_data prglob d ++ fnl () ++ strm)
1645 ntns (mt ()) in
1646 (if String.equal scope default_scope then
1647 str (String.plural (List.length ntns) "Lonely notation")
1648 else
1649 str "Visible in scope " ++ str scope)
1650 ++ fnl () ++ strm
1651
1652 let pr_scope_stack prglob stack =
1653 prlist_with_sep fnl (pr_visible_in_scope prglob) (collect_notations stack)
1654
1655 let pr_visibility prglob = function
1656 | Some scope -> pr_scope_stack prglob (push_scope scope !scope_stack)
1657 | None -> pr_scope_stack prglob !scope_stack
1658
1659 (* Enabling/disabling notations *)
1660
1661 let toggle_main_notation ~on ~use found test ntn_data main =
1662 let found d = found := (Inl (d.not_location, ntn_data), d.not_interp) :: !found in
1663 match main, use with
1664 | OnlyParsingData (is_on,d), OnlyPrinting when test d.not_interp ->
1665 user_err (strbrk "Unexpected only printing for an only parsing notation.")
1666 | OnlyParsingData (is_on,d) as x, (OnlyParsing | ParsingAndPrinting) when test d.not_interp ->
1667 if is_on <> on then begin found d; OnlyParsingData (on, d) end else x
1668 | ParsingAndPrintingData (is_parsing_on,is_printing_on,d) as x, _ when test d.not_interp ->
1669 let parsing_changed = match use with
1670 | OnlyPrinting -> false
1671 | OnlyParsing | ParsingAndPrinting -> is_parsing_on <> on in
1672 let printing_changed = match use with
1673 | OnlyParsing -> false
1674 | OnlyPrinting | ParsingAndPrinting -> is_printing_on <> on in
1675 if parsing_changed || printing_changed then
1676 let () = found d in
1677 ParsingAndPrintingData (is_parsing_on <> parsing_changed,is_printing_on <> printing_changed,d)
1678 else
1679 x
1680 | (NoParsingData | OnlyParsingData _ | ParsingAndPrintingData _), _ -> main
1681
1682 let toggle_extra_only_printing_notation ~on ~use found test ntn_data (is_on,d as x) =
1683 let found d = found := (Inl (d.not_location, ntn_data), d.not_interp) :: !found in
1684 match use with
1685 | OnlyParsing ->
1686 user_err (strbrk "Unexpected only parsing for an only printing notation.")
1687 | OnlyPrinting | ParsingAndPrinting ->
1688 if test d.not_interp then
1689 if is_on <> on then let () = found d in (on,d) else x
1690 else
1691 x
1692
1693 let toggle_notation_data ~on ~use found test ntn_data (main,extra as data) =
1694 let main' = toggle_main_notation ~on ~use found test ntn_data main in
1695 let extra' = List.Smart.map (toggle_extra_only_printing_notation ~on ~use found test ntn_data) extra in
1696 if main' == main && extra' == extra then data else (main',extra')
1697
1698 type 'a notation_query_pattern_gen = {
1699 notation_entry_pattern : notation_entry list;
1700 interp_rule_key_pattern : (notation_key, 'a) Util.union option;
1701 use_pattern : notation_use;
1702 scope_pattern : notation_with_optional_scope option;
1703 interpretation_pattern : interpretation option;
1704 }
1705
1706 type notation_query_pattern = qualid notation_query_pattern_gen
1707
1708 let match_notation_interpretation notation_interpretation pat =
1709 match notation_interpretation with
1710 | None -> true
1711 | Some pat' -> Notation_ops.finer_interpretation_than pat pat'
1712
1713 let match_notation_entry notation_entry_pattern notation_entry =
1714 List.is_empty notation_entry_pattern ||
1715 List.mem_f notation_entry_eq notation_entry notation_entry_pattern
1716
1717 let match_notation_rule interp_rule_key_pattern notation_key =
1718 match interp_rule_key_pattern with
1719 | None -> true
1720 | Some (Inl ntn) -> match_notation_key false ntn notation_key
1721 | Some (Inr _) -> false
1722
1723 let toggle_notations_by_interpretation ~on found ntn_pattern ntn_data (main,extra as data) =
1724 let use = ntn_pattern.use_pattern in
1725 let test = match_notation_interpretation ntn_pattern.interpretation_pattern in
1726 toggle_notation_data ~on ~use found test ntn_data data
1727
1728 let toggle_notations_in_scope ~on found inscope ntn_pattern ntns =
1729 match ntn_pattern.notation_entry_pattern, ntn_pattern.interp_rule_key_pattern with
1730 | _, Some (Inr kn) -> ntns (* This is the table of notations, not of abbreviations *)
1731 | _ :: _ as ntn_entries, Some (Inl ntn) ->
1732 (* shortcut *)
1733 List.fold_right (fun ntn_entry ntns ->
1734 try
1735 NotationMap.add (ntn_entry, ntn)
1736 (toggle_notations_by_interpretation ~on found ntn_pattern
1737 (inscope,(ntn_entry,ntn))
1738 (NotationMap.find (ntn_entry, ntn) ntns))
1739 ntns
1740 with Not_found -> ntns)
1741 ntn_entries ntns
1742 (* Deal with full notations *)
1743 | ntn_entries, ntn_rule -> (* This is the table of notations, not of abbreviations *)
1744 NotationMap.mapi (fun (ntn_entry,ntn_key' as ntn') data ->
1745 if match_notation_entry ntn_entries ntn_entry && match_notation_rule ntn_rule ntn_key' then
1746 toggle_notations_by_interpretation ~on found ntn_pattern
1747 (inscope,ntn')
1748 data
1749 else
1750 data) ntns
1751
1752 let warn_abbreviation_not_bound_to_entry =
1753 CWarnings.create ~name:"conflicting-abbreviation-entry" ~category:CWarnings.CoreCategories.syntax
1754 (fun () ->
1755 strbrk "Activation of abbreviations does not expect mentioning a grammar entry.")
1756
1757 let warn_abbreviation_not_bound_to_scope =
1758 CWarnings.create ~name:"conflicting-abbreviation-scope" ~category:CWarnings.CoreCategories.syntax
1759 (fun () ->
1760 strbrk "Activation of abbreviations does not expect mentioning a scope.")
1761
1762 let toggle_abbreviations ~on found ntn_pattern =
1763 try
1764 let qid =
1765 match ntn_pattern.interp_rule_key_pattern, ntn_pattern.notation_entry_pattern, ntn_pattern.scope_pattern with
1766 | Some (Inr qid), [], None -> Some qid
1767 | Some (Inr qid), entries, inscope ->
1768 if not (List.is_empty entries) then warn_abbreviation_not_bound_to_entry ();
1769 if Option.has_some inscope then warn_abbreviation_not_bound_to_scope ();
1770 raise Exit
1771 | Some (Inl _), _, _ | None, _::_, _ | None, _, Some _ -> raise Exit (* Not about abbreviation, shortcut *)
1772 | None, [], None -> None
1773 in
1774 let test _ abbrev =
1775 let sp = Abbreviation.full_path abbrev in
1776 let a = Abbreviation.interp abbrev in
1777 let res = match_notation_interpretation ntn_pattern.interpretation_pattern a in
1778 let res' = match qid with
1779 | Some qid -> Libnames.is_qualid_suffix_of_full_path qid sp
1780 | None -> true in
1781 let res'' = res && res' in
1782 if res'' then found := (Inr sp, a) :: !found; res'' in
1783 Abbreviation.toggle_if ~on ~use:ntn_pattern.use_pattern test
1784 with Exit -> ()
1785
1786 let warn_nothing_to_enable_or_disable =
1787 CWarnings.create ~name:"no-notation-to-enable-or-disable"
1788 ~category:CWarnings.CoreCategories.syntax
1789 (fun () -> strbrk "Found no matching notation to enable or disable.")
1790
1791 let toggle_notations ~on ~all ?(verbose=true) prglob ntn_pattern =
1792 let found = ref [] in
1793 (* Deal with (parsing) notations *)
1794 begin
1795 match ntn_pattern.scope_pattern with
1796 | None ->
1797 scope_map := String.Map.mapi (fun sc {notations;delimiters} ->
1798 let inscope = if String.equal sc default_scope then LastLonelyNotation else NotationInScope sc in
1799 {notations = toggle_notations_in_scope ~on found inscope ntn_pattern notations;delimiters}) !scope_map;
1800 | Some inscope ->
1801 (* shortcut when a scope is given *)
1802 let sc = match inscope with NotationInScope sc -> sc | LastLonelyNotation -> default_scope in
1803 scope_map := String.Map.add sc (let {notations;delimiters} = find_scope sc in {notations = toggle_notations_in_scope ~on found inscope ntn_pattern notations;delimiters}) !scope_map
1804 end;
1805 (* Deal with abbreviations *)
1806 toggle_abbreviations ~on found ntn_pattern;
1807 match !found with
1808 | [] -> warn_nothing_to_enable_or_disable ()
1809 | _::_::_ when not all ->
1810 user_err (strbrk "More than one interpretation bound to this notation, confirm with the \"all\" modifier.")
1811 | _ ->
1812 if verbose then Feedback.msg_info
1813 (str "The following notations have been " ++
1814 str (if on then "enabled" else "disabled") ++
1815 (match ntn_pattern.use_pattern with
1816 | OnlyParsing -> str " for parsing"
1817 | OnlyPrinting -> str " for printing"
1818 | ParsingAndPrinting -> mt ()) ++
1819 str ":" ++ fnl () ++
1820 prlist_with_sep fnl (fun (kind, (vars,a as i)) ->
1821 match kind with
1822 | Inl (l, (sc, (entry, _))) ->
1823 let sc = match sc with NotationInScope sc -> sc | LastLonelyNotation -> default_scope in
1824 let data = { not_interp = i; not_location = l; not_user_warns = None } in
1825 hov 0
1826 (str "Notation " ++ pr_notation_data prglob (Some true,Some true,data) ++
1827 (match entry with
1828 | InCustomEntry s ->
1829 str " (in custom " ++ Nametab.CustomEntries.pr s ++ str ")"
1830 | InConstrEntry -> mt ()) ++
1831 (if String.equal sc default_scope then mt () else (brk (1,2) ++ str ": " ++ str sc)))
1832 | Inr sp ->
1833 hov 0 (str "Notation " ++ Libnames.pr_path sp ++ prlist (fun (a,_) -> spc () ++ Id.print a) vars ++
1834 spc () ++ str ":=" ++ spc () ++ prglob (Notation_ops.glob_constr_of_notation_constr a)))
1835 !found)
1836
1837 (**********************************************************************)
1838 (* Synchronisation with reset *)
1839
1840 let freeze () =
1841 (!scope_map, !scope_stack, !arguments_scope,
1842 !delimiters_map, !scope_class_map,
1843 !prim_token_interp_infos, !prim_token_uninterp_infos,
1844 !entry_coercion_map, !entry_has_global_map,
1845 !entry_has_ident_map)
1846
1847 let unfreeze (scm,scs,asc,dlm,clsc,ptii,ptui,coe,globs,ids) =
1848 scope_map := scm;
1849 scope_stack := scs;
1850 delimiters_map := dlm;
1851 arguments_scope := asc;
1852 scope_class_map := clsc;
1853 prim_token_interp_infos := ptii;
1854 prim_token_uninterp_infos := ptui;
1855 entry_coercion_map := coe;
1856 entry_has_global_map := globs;
1857 entry_has_ident_map := ids
1858
1859 let init () =
1860 init_scope_map ();
1861 delimiters_map := String.Map.empty;
1862 scope_class_map := initial_scope_class_map;
1863 prim_token_interp_infos := String.Map.empty;
1864 prim_token_uninterp_infos := GlobRefMap.empty
1865
1866 let _ =
1867 Summary.declare_summary "symbols"
1868 { stage = Summary.Stage.Interp;
1869 Summary.freeze_function = freeze;
1870 Summary.unfreeze_function = unfreeze;
1871 Summary.init_function = init }
1872
1873 let with_notation_protection f x =
1874 let open Memprof_coq.Resource_bind in
1875 let& () = Util.protect_state ~freeze ~unfreeze in
1876 with_notation_uninterpretation_protection f x