Debian Codegraph @

vernac/metasyntax.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Pp
12 open CErrors
13 open Util
14 open Names
15 open Constrexpr
16 open Constrexpr_ops
17 open Vernacexpr
18 open Notation_term
19 open Notationextern
20 open Notation_gram
21 open Notation_ops
22 open Ppextend
23 open Extend
24 open Libobject
25 open Constrintern
26 open Libnames
27 open Notation
28 open Nameops
29 open Globnames
30
31 (** Intern custom entry names (with compat layer) *)
32
33 exception UnknownCustomEntry of qualid
34
35 let () = CErrors.register_handler @@ function
36 | UnknownCustomEntry entry -> Some Pp.(str "Unknown custom entry: " ++ pr_qualid entry ++ str ".")
37 | _ -> None
38
39 let compat_custom_names = Summary.ref ~stage:Synterp ~name:"compat-custom-names" Id.Map.empty
40
41 let add_custom_compat kn =
42 let id = CustomName.label kn in
43 compat_custom_names :=
44 Id.Map.update id (fun existing -> Some (kn :: Option.default [] existing))
45 !compat_custom_names
46
47 let warn_compat_custom = CWarnings.create ~name:"deprecated-unqualified-custom-entry"
48 ~category:Deprecation.Version.v9_2
49 ~quickfix:(fun ~loc custom -> [Quickfix.make ~loc (Nametab.CustomEntries.pr custom)])
50 Pp.(fun custom ->
51 str "Accessing custom entry " ++ Nametab.CustomEntries.pr custom ++
52 str " by its unqualified name is deprecated.")
53
54 let intern_custom_name qid =
55 match Nametab.CustomEntries.locate qid with
56 | v -> v
57 | exception Not_found ->
58 let compat =
59 if qualid_is_ident qid then
60 Id.Map.find_opt (qualid_basename qid) !compat_custom_names
61 else None
62 in
63 match compat with
64 | None -> Loc.raise ?loc:qid.loc (UnknownCustomEntry qid)
65 | Some [] -> assert false
66 | Some [custom] ->
67 warn_compat_custom ?loc:qid.loc custom;
68 custom
69 | Some customs ->
70 user_err ?loc:qid.loc
71 Pp.(pr_qualid qid ++ str " is ambiguous: it may refer to any of "
72 ++ pr_choice Nametab.CustomEntries.pr customs ++ str ".")
73
74 let intern_notation_entry = function
75 | InConstrEntry -> InConstrEntry
76 | InCustomEntry qid -> InCustomEntry (intern_custom_name qid)
77
78 (** **************************************************************** **)
79 (** Printing grammar entries **)
80
81 let entry_buf = Buffer.create 64
82
83 let pr_entry e =
84 let () = Buffer.clear entry_buf in
85 let ft = Format.formatter_of_buffer entry_buf in
86 let () = Procq.Entry.print ft e in
87 str (Buffer.contents entry_buf)
88
89 let error_unknown_entry ?loc name =
90 user_err ?loc Pp.(str "Unknown or unprintable grammar entry " ++ str name ++ str".")
91
92 let pr_grammar_subset grammar =
93 let pp = String.Map.mapi (fun name l -> match l with
94 | [] -> assert false
95 | entries ->
96 str "Entry " ++ str name ++ str " is" ++ fnl() ++
97 prlist_with_sep (fun () -> str "or" ++ fnl())
98 (fun (Procq.Entry.Any e) -> pr_entry e)
99 entries)
100 grammar
101 in
102 let pp = CString.Map.bindings pp in
103 prlist_with_sep fnl (fun (_,pp) -> pp) pp
104
105 let is_known = let open Procq.Entry in function
106 | "constr" | "term" | "binder_constr" ->
107 Some [ Any Procq.Constr.constr;
108 Any Procq.Constr.lconstr;
109 Any Procq.Constr.binder_constr;
110 Any Procq.Constr.term;
111 ]
112 | "vernac" ->
113 Some Pvernac.Vernac_.[
114 Any vernac_control;
115 (* main_entry="vernac", included not because it's interesting but because otherwise it's shadowed by the "vernac" group defined here *)
116 Any main_entry;
117 Any command;
118 Any syntax;
119 Any gallina;
120 Any gallina_ext;
121 ]
122 | name ->
123 let gram = Procq.find_grammars_by_name name in
124 match gram with
125 | [] -> None
126 | entries -> Some entries
127
128 let full_grammar () =
129 let open Pvernac.Vernac_ in
130 let open Procq.Entry in
131 let proof_modes = List.map (fun (_,Pvernac.ProofMode e) -> Any e.command_entry)
132 (CString.Map.bindings (Pvernac.list_proof_modes()))
133 in
134 let entries = (Any main_entry) :: (Any noedit_mode) :: proof_modes in
135 Procq.Entry.accumulate_in entries
136
137 let same_entry (Procq.Entry.Any e) (Procq.Entry.Any e') = (Obj.magic e) == (Obj.magic e')
138
139 let pr_grammar = function
140 | [] ->
141 let grammar = full_grammar () in
142 pr_grammar_subset grammar
143 | ["Full"] ->
144 let grammar = Procq.Entry.all_in () in
145 pr_grammar_subset grammar
146 | names ->
147 let known, other = List.fold_left (fun (known,other) name ->
148 match is_known name with
149 | Some v -> v @ known, other
150 | None -> known, name::other)
151 ([],[])
152 names
153 in
154 let grammar = if List.is_empty other then String.Map.empty else full_grammar () in
155 let () = List.iter (fun name ->
156 if not (String.Map.mem name grammar)
157 then error_unknown_entry name)
158 other
159 in
160 let other = String.Set.of_list other in
161 let grammar = String.Map.filter (fun name _ -> String.Set.mem name other) grammar in
162 let grammar = List.fold_left (fun grammar (Procq.Entry.Any e as any) ->
163 String.Map.update (Procq.Entry.name e) (function
164 | None -> Some [any]
165 | Some vl as v ->
166 if List.mem_f same_entry any vl
167 then v else Some (any :: vl))
168 grammar)
169 grammar known
170 in
171 pr_grammar_subset grammar
172
173 let custom_grammars = ref []
174
175 let register_custom_grammar_for_print h = custom_grammars := h :: !custom_grammars
176
177 let () = register_custom_grammar_for_print @@ fun name ->
178 try
179 let name = intern_custom_name name in
180 let constr_entry, _ = Egramrocq.find_custom_entry name in
181 Some [Procq.Entry.Any constr_entry]
182 with UnknownCustomEntry _ ->
183 None
184
185 let get_custom_grammars name =
186 let entries = List.filter_map (fun f -> f name) !custom_grammars in
187 match entries with
188 | [] -> raise (UnknownCustomEntry name)
189 | _ :: _ -> List.flatten entries
190
191 let pr_custom_grammar name =
192 let entries = get_custom_grammars name in
193 let add_entry map (Procq.Entry.Any e as any) =
194 String.Map.update (Procq.Entry.name e)
195 (fun entries -> Some (any :: Option.default [] entries))
196 map
197 in
198 let map = List.fold_left add_entry String.Map.empty entries in
199 pr_grammar_subset map
200
201 let pr_keywords () =
202 Pp.prlist_with_sep Pp.fnl Pp.str (CString.Set.elements (CLexer.keywords (Procq.get_keyword_state())))
203
204 (** **************************************************************** **)
205 (** Parse a format (every terminal starting with a letter or a single
206 quote (except a single quote alone) must be quoted) **)
207
208 let parse_format ({CAst.loc;v=str} : lstring) =
209 let len = String.length str in
210 (* TODO: update the line of the location when the string contains newlines *)
211 let make_loc i j = Option.map (Loc.shift_loc (i+1) (j-len)) loc in
212 let push_token loc a = function
213 | (i,cur)::l -> (i,(loc,a)::cur)::l
214 | [] -> assert false in
215 let push_white i n l =
216 if Int.equal n 0 then l else push_token (make_loc i (i+n)) (UnpTerminal (String.make n ' ')) l in
217 let close_box start stop b = function
218 | (_,a)::(_::_ as l) -> push_token (make_loc start stop) (UnpBox (b,a)) l
219 | [a] -> user_err ?loc:(make_loc start stop) Pp.(str "Non terminated box in format.")
220 | [] -> assert false in
221 let close_quotation start i =
222 if i < len && str.[i] == '\'' then
223 if (Int.equal (i+1) len || str.[i+1] == ' ')
224 then i+1
225 else user_err ?loc:(make_loc (i+1) (i+1)) Pp.(str "Space expected after quoted expression.")
226 else
227 user_err ?loc:(make_loc start (i-1)) Pp.(str "Beginning of quoted expression expected to be ended by a quote.") in
228 let rec spaces n i =
229 if i < len && str.[i] == ' ' then spaces (n+1) (i+1)
230 else n in
231 let rec nonspaces quoted n i =
232 if i < len && str.[i] != ' ' then
233 if str.[i] == '\'' && quoted &&
234 (i+1 >= len || str.[i+1] == ' ')
235 then if Int.equal n 0 then user_err ?loc:(make_loc (i-1) i) Pp.(str "Empty quoted token.") else n
236 else nonspaces quoted (n+1) (i+1)
237 else
238 if quoted then user_err ?loc:(make_loc i i) Pp.(str "Spaces are not allowed in (quoted) symbols.")
239 else n in
240 let rec parse_non_format i =
241 let n = nonspaces false 0 i in
242 push_token (make_loc i (i+n-1)) (UnpTerminal (String.sub str i n)) (parse_token 1 (i+n))
243 and parse_quoted n k i =
244 if i < len then match str.[i] with
245 (* Parse " // " *)
246 | '/' when i+1 < len && str.[i+1] == '/' ->
247 (* We discard the useless n spaces... *)
248 push_token (make_loc (i-n) (i+1)) (UnpCut PpFnl)
249 (parse_token 1 (close_quotation i (i+2)))
250 (* Parse " .. / .. " *)
251 | '/' when i+1 < len ->
252 let p = spaces 0 (i+1) in
253 push_token (make_loc (i-n) (i+p)) (UnpCut (PpBrk (n,p)))
254 (parse_token 1 (close_quotation i (i+p+1)))
255 | c ->
256 (* The spaces are real spaces *)
257 push_white (i-n-1-k) n (match c with
258 | '[' ->
259 if i+1 < len then match str.[i+1] with
260 (* Parse " [h .. ", *)
261 | 'h' when i+1 <= len && str.[i+2] == 'v' ->
262 (parse_box i (fun n -> PpHVB n) (i+3))
263 (* Parse " [v .. ", *)
264 | 'v' ->
265 parse_box i (fun n -> PpVB n) (i+2)
266 (* Parse " [ .. ", *)
267 | ' ' | '\'' ->
268 parse_box i (fun n -> PpHOVB n) (i+1)
269 | _ -> user_err ?loc:(make_loc i i) Pp.(str "\"v\", \"hv\", \" \" expected after \"[\" in format.")
270 else user_err ?loc:(make_loc i i) Pp.(str "\"v\", \"hv\" or \" \" expected after \"[\" in format.")
271 (* Parse "]" *)
272 | ']' ->
273 ((i,[]) :: parse_token 1 (close_quotation i (i+1)))
274 (* Parse a non formatting token *)
275 | c ->
276 let n = nonspaces true 0 i in
277 push_token (make_loc i (i+n-1)) (UnpTerminal (String.sub str (i-1) (n+2)))
278 (parse_token 1 (close_quotation i (i+n))))
279 else
280 if Int.equal n 0 then []
281 else user_err ?loc:(make_loc (len-n) len) Pp.(str "Ending spaces non part of a format annotation.")
282 and parse_box start box i =
283 let n = spaces 0 i in
284 close_box start (i+n-1) (box n) (parse_token 1 (close_quotation i (i+n)))
285 and parse_token k i =
286 let n = spaces 0 i in
287 let i = i+n in
288 if i < len then match str.[i] with
289 (* Parse a ' *)
290 | '\'' when i+1 >= len || str.[i+1] == ' ' ->
291 push_white (i-n) (n-k) (push_token (make_loc i (i+1)) (UnpTerminal "'") (parse_token 1 (i+1)))
292 (* Parse the beginning of a quoted expression *)
293 | '\'' ->
294 parse_quoted (n-k) k (i+1)
295 (* Otherwise *)
296 | _ ->
297 push_white (i-n) (n-k) (parse_non_format i)
298 else push_white (i-n) n [(len,[])]
299 in
300 if not (String.is_empty str) then
301 match parse_token 0 0 with
302 | [_,l] -> l
303 | (i,_)::_ -> user_err ?loc:(make_loc i i) Pp.(str "Box closed without being opened.")
304 | [] -> assert false
305 else
306 []
307
308 (** **************************************************************** **)
309 (** Analyzing notations **)
310
311 (* Find non-terminal tokens of notation *)
312
313 (* To protect alphabetic tokens and quotes from being seen as variables *)
314 let quote_notation_token x =
315 let n = String.length x in
316 let norm = CLexer.is_ident x in
317 if (n > 0 && norm) || (n > 2 && x.[0] == '\'') then "'"^x^"'"
318 else x
319
320 let analyze_notation_tokens ~onlyprinting ~infix entry df =
321 let df = if infix then quote_notation_token df else df in
322 let { recvars; mainvars; symbols } as res = decompose_raw_notation df in
323 (* don't check for nonlinearity if printing only, see Bug 5526 *)
324 (if not onlyprinting then
325 match List.duplicates Id.equal (mainvars @ List.map snd recvars) with
326 | id :: _ ->
327 user_err
328 (str "Variable " ++ Id.print id ++ str " occurs more than once.")
329 | _ -> ());
330 let is_prim_token = is_prim_token_constant_in_constr (entry, symbols) in
331 res, is_prim_token
332
333 let adjust_symbols vars notation_symbols =
334 let x = Namegen.next_ident_away (Id.of_string "x") vars in
335 let y = Namegen.next_ident_away (Id.of_string "y") (Id.Set.add x vars) in
336 let notation_symbols = {
337 recvars = notation_symbols.recvars; mainvars = x::notation_symbols.mainvars@[y];
338 symbols = NonTerminal x :: notation_symbols.symbols @ [NonTerminal y];
339 } in
340 x, y, notation_symbols
341
342 let adjust_reserved_infix_notation notation_symbols =
343 let vars = Id.Set.of_list (List.map_filter (function NonTerminal x -> Some x | _ -> None) notation_symbols.symbols) in
344 let _, _, notation_symbols = adjust_symbols vars notation_symbols in
345 notation_symbols
346
347 let adjust_infix_notation df notation_symbols c =
348 let vars = names_of_constr_expr c in
349 let x, y, notation_symbols = adjust_symbols vars notation_symbols in
350 let df = Id.to_string x ^ " " ^ df ^ " " ^ Id.to_string y in
351 let inject_var x = CAst.make @@ CRef (qualid_of_ident x,None) in
352 let metas = [inject_var x; inject_var y] in
353 let c = mkAppC (c,metas) in
354 df, notation_symbols, c
355
356 let warn_unexpected_primitive_token_modifier =
357 CWarnings.create ~name:"primitive-token-modifier" ~category:CWarnings.CoreCategories.parsing
358 (fun () -> str "Notations for numbers or strings are primitive; skipping this modifier.")
359
360 let check_no_syntax_modifiers_for_numeral = function
361 | [] -> ()
362 | l -> List.iter (function {CAst.loc} -> warn_unexpected_primitive_token_modifier ?loc ()) l
363
364 let error_not_same_scope x y =
365 user_err
366 (str "Variables " ++ Id.print x ++ str " and " ++ Id.print y ++ str " must be in the same scope.")
367
368 (** **************************************************************** **)
369 (** Build pretty-printing rules **)
370
371 let pr_notation_entry = function
372 | InConstrEntry -> str "constr"
373 | InCustomEntry s -> str "custom " ++ Nametab.CustomEntries.pr s
374
375 let side = function
376 | BorderProd (b,_) -> Some b
377 | _ -> None
378
379 let precedence_of_position_and_level from_level = function
380 | NumLevel n, BorderProd (b,Some a) ->
381 let prec =
382 let open Gramlib.Gramext in
383 match a, b with
384 | RightA, Left -> LevelLt n
385 | RightA, Right -> LevelLe n
386 | LeftA, Left -> LevelLe n
387 | LeftA, Right -> LevelLt n
388 | NonA, _ -> LevelLt n
389 | BothA, _ -> assert false in
390 {notation_subentry = InConstrEntry; notation_relative_level = prec; notation_position = Some b}
391 | NumLevel n, b -> {notation_subentry = InConstrEntry; notation_relative_level = LevelLe n; notation_position = side b}
392 | NextLevel, b -> {notation_subentry = InConstrEntry; notation_relative_level = LevelLt from_level; notation_position = side b}
393 | DefaultLevel, b -> {notation_subentry = InConstrEntry; notation_relative_level = LevelSome; notation_position = side b}
394
395 (** Computing precedences of non-terminals for parsing *)
396 let precedence_of_entry_type { notation_entry = from_custom; notation_level = from_level } = function
397 | ETConstr (custom,_,x) when notation_entry_eq custom from_custom ->
398 (precedence_of_position_and_level from_level x).notation_relative_level
399 | ETConstr (custom,_,(NumLevel n,_)) -> LevelLe n
400 | ETConstr (custom,_,(NextLevel,_)) ->
401 user_err (strbrk "\"next level\" is only for sub-expressions in the same entry as where the notation is (" ++
402 quote (pr_notation_entry custom) ++ strbrk " is different from " ++
403 quote (pr_notation_entry from_custom) ++ str ").")
404 | ETPattern (_,n) -> let n = match n with None -> 0 | Some n -> n in LevelLe n
405 | _ -> LevelSome (* should not matter *)
406
407 let pattern_entry_level = function None -> 0 | Some n -> n
408
409 (** Computing precedences for future insertion of parentheses at
410 the time of printing using hard-wired constr levels *)
411 let unparsing_precedence_of_entry_type from_level = function
412 | ETConstr (InConstrEntry,_,x) ->
413 (* Possible insertion of parentheses at printing time to deal
414 with precedence in a constr entry is managed using [prec_less]
415 in [ppconstr.ml] *)
416 precedence_of_position_and_level from_level x
417 | ETConstr (custom,_,(_,b)) ->
418 (* Precedence of printing for a custom entry is managed using
419 explicit insertion of entry coercions at the time of building
420 a [constr_expr] *)
421 {notation_subentry = custom; notation_relative_level = LevelSome; notation_position = side b}
422 | ETPattern (_,n) -> (* in constr *)
423 {notation_subentry = InConstrEntry; notation_relative_level = LevelLe (pattern_entry_level n); notation_position = None}
424 | _ -> (* should not matter *)
425 {notation_subentry = InConstrEntry; notation_relative_level = LevelSome; notation_position = None}
426
427 (** Utilities for building default printing rules *)
428
429 (* Some breaking examples *)
430 (* "x = y" : "x /1 = y" (breaks before any symbol) *)
431 (* "x =S y" : "x /1 =S /1 y" (protect from confusion; each side for symmetry)*)
432 (* "+ {" : "+ {" may breaks reversibility without space but oth. not elegant *)
433 (* "x y" : "x spc y" *)
434 (* "{ x } + { y }" : "{ x } / + { y }" *)
435 (* "< x , y > { z , t }" : "< x , / y > / { z , / t }" *)
436
437 let starts_with_left_bracket s =
438 let l = String.length s in not (Int.equal l 0) &&
439 (s.[0] == '{' || s.[0] == '[' || s.[0] == '(')
440
441 let ends_with_right_bracket s =
442 let l = String.length s in not (Int.equal l 0) &&
443 (s.[l-1] == '}' || s.[l-1] == ']' || s.[l-1] == ')')
444
445 let is_left_bracket s =
446 starts_with_left_bracket s && not (ends_with_right_bracket s)
447
448 let is_right_bracket s =
449 not (starts_with_left_bracket s) && ends_with_right_bracket s
450
451 let is_comma s =
452 let l = String.length s in not (Int.equal l 0) &&
453 (s.[0] == ',' || s.[0] == ';')
454
455 let is_operator s =
456 let l = String.length s in not (Int.equal l 0) &&
457 (s.[0] == '+' || s.[0] == '*' || s.[0] == '=' ||
458 s.[0] == '-' || s.[0] == '/' || s.[0] == '<' || s.[0] == '>' ||
459 s.[0] == '@' || s.[0] == '\\' || s.[0] == '&' || s.[0] == '~' || s.[0] == '$')
460
461 let is_non_terminal = function
462 | NonTerminal _ | SProdList _ -> true
463 | _ -> false
464
465 let is_next_non_terminal b = function
466 | [] -> b
467 | pr :: _ -> is_non_terminal pr
468
469 let is_next_terminal = function Terminal _ :: _ -> true | _ -> false
470
471 let is_next_break = function Break _ :: _ -> true | _ -> false
472
473 let add_break n l = (None,UnpCut (PpBrk(n,0))) :: l
474
475 let add_break_if_none n b = function
476 | (_,UnpCut (PpBrk _)) :: _ as l -> l
477 | [] when not b -> []
478 | l -> (None,UnpCut (PpBrk(n,0))) :: l
479
480 let check_open_binder isopen sl m =
481 let pr_token = function
482 | Terminal s -> str s
483 | Break n -> str "␣"
484 | _ -> assert false
485 in
486 if isopen && not (List.is_empty sl) then
487 user_err (str "as " ++ Id.print m ++
488 str " is a non-closed binder, no such \"" ++
489 prlist_with_sep spc pr_token sl
490 ++ strbrk "\" is allowed to occur.")
491
492 let unparsing_metavar i from typs =
493 let x = List.nth typs (i-1) in
494 let subentry = unparsing_precedence_of_entry_type from x in
495 match x with
496 | ETConstr _ | ETGlobal | ETBigint ->
497 UnpMetaVar subentry
498 | ETPattern _ | ETName | ETIdent ->
499 UnpBinderMetaVar (subentry,NotQuotedPattern)
500 | ETBinder isopen ->
501 UnpBinderMetaVar (subentry,QuotedPattern)
502
503 (** Heuristics for building default printing rules *)
504
505 let index_id id l = List.index Id.equal id l
506
507 let make_hunks etyps symbols from_level =
508 let vars,typs = List.split etyps in
509 let rec make b = function
510 | NonTerminal m :: prods ->
511 let i = index_id m vars in
512 let u = unparsing_metavar i from_level typs in
513 if is_next_non_terminal b prods then
514 (None, u) :: add_break_if_none 1 b (make b prods)
515 else
516 (None, u) :: make_with_space b prods
517 | Terminal s :: prods
518 when (* true to simulate presence of non-terminal *) b || List.exists is_non_terminal prods ->
519 if (is_comma s || is_operator s) then
520 (* Always a breakable space after comma or separator *)
521 (None, UnpTerminal s) :: add_break_if_none 1 b (make b prods)
522 else if is_right_bracket s && is_next_terminal prods then
523 (* Always no space after right bracked, but possibly a break *)
524 (None, UnpTerminal s) :: add_break_if_none 0 b (make b prods)
525 else if is_left_bracket s && is_next_non_terminal b prods then
526 (None, UnpTerminal s) :: make b prods
527 else if not (is_next_break prods) then
528 (* Add rigid space, no break, unless user asked for something *)
529 (None, UnpTerminal (s^" ")) :: make b prods
530 else
531 (* Rely on user spaces *)
532 (None, UnpTerminal s) :: make b prods
533
534 | Terminal s :: prods ->
535 (* Separate but do not cut a trailing sequence of terminal *)
536 (match prods with
537 | Terminal _ :: _ -> (None,UnpTerminal (s^" ")) :: make b prods
538 | _ -> (None,UnpTerminal s) :: make b prods)
539
540 | Break n :: prods ->
541 add_break n (make b prods)
542
543 | SProdList (m,sl) :: prods ->
544 let i = index_id m vars in
545 let typ = List.nth typs (i-1) in
546 let subentry = unparsing_precedence_of_entry_type from_level typ in
547 let sl' =
548 (* If no separator: add a break *)
549 if List.is_empty sl then add_break 1 []
550 (* We add NonTerminal for simulation but remove it afterwards *)
551 else make true sl in
552 let hunk = match typ with
553 | ETConstr _ -> UnpListMetaVar (subentry,List.map snd sl')
554 | ETBinder isopen ->
555 check_open_binder isopen sl m;
556 UnpBinderListMetaVar (isopen,true,List.map snd sl')
557 | ETName | ETIdent ->
558 UnpBinderListMetaVar (false,true,List.map snd sl')
559 | ETPattern _ ->
560 UnpBinderListMetaVar (false,false,List.map snd sl')
561 | _ -> assert false in
562 (None, hunk) :: make_with_space b prods
563
564 | [] -> []
565
566 and make_with_space b prods =
567 match prods with
568 | Terminal s' :: prods'->
569 if is_operator s' then
570 (* A rigid space before operator and a breakable after *)
571 (None,UnpTerminal (" "^s')) :: add_break_if_none 1 b (make b prods')
572 else if is_comma s' then
573 (* No space whatsoever before comma *)
574 make b prods
575 else if is_right_bracket s' then
576 make b prods
577 else
578 (* A breakable space between any other two terminals *)
579 add_break_if_none 1 b (make b prods)
580 | (NonTerminal _ | SProdList _) :: _ ->
581 (* A breakable space before a non-terminal *)
582 add_break_if_none 1 b (make b prods)
583 | Break _ :: _ ->
584 (* Rely on user wish *)
585 make b prods
586 | [] -> []
587
588 in make false symbols
589
590 (** Build default printing rules from explicit format *)
591
592 let error_format ?loc () = user_err ?loc Pp.(str "The format does not match the notation.")
593
594 let warn_format_break =
595 CWarnings.create ~name:"notation-both-format-and-spaces" ~category:CWarnings.CoreCategories.parsing
596 (fun () ->
597 strbrk "Discarding format implicitly indicated by multiple spaces in notation because an explicit format modifier is given.")
598
599 let has_ldots l =
600 List.exists (function (_,UnpTerminal s) -> String.equal s (Id.to_string Notation_ops.ldots_var) | _ -> false) l
601
602 let rec split_format_at_ldots hd = function
603 | (loc,UnpTerminal s) :: fmt when String.equal s (Id.to_string Notation_ops.ldots_var) -> loc, List.rev hd, fmt
604 | u :: fmt ->
605 check_no_ldots_in_box u;
606 split_format_at_ldots (u::hd) fmt
607 | [] -> raise_notrace Exit
608
609 and check_no_ldots_in_box = function
610 | (_,UnpBox (_,fmt)) ->
611 (try
612 let loc,_,_ = split_format_at_ldots [] fmt in
613 user_err ?loc Pp.(str ("The special symbol \"..\" must occur at the same formatting depth than the variables of which it is the ellipse."))
614 with Exit -> ())
615 | _ -> ()
616
617 let error_not_same ?loc () =
618 user_err ?loc Pp.(str "The format is not the same on the right- and left-hand sides of the special token \"..\".")
619
620 let find_prod_list_loc sfmt fmt =
621 (* [fmt] is some [UnpTerminal x :: sfmt @ UnpTerminal ".." :: sfmt @ UnpTerminal y :: rest] *)
622 if List.is_empty sfmt then
623 (* No separators; we highlight the sequence "x .." *)
624 Loc.merge_opt (fst (List.hd fmt)) (fst (List.hd (List.tl fmt)))
625 else
626 (* A separator; we highlight the separating sequence *)
627 Loc.merge_opt (fst (List.hd sfmt)) (fst (List.last sfmt))
628
629 let is_blank s =
630 let n = String.length s in
631 let rec aux i s = i >= n || s.[i] = ' ' && aux (i+1) s in
632 aux 0 s
633
634 let is_formatting = function
635 | (_,UnpCut _) -> true
636 | (_,UnpTerminal s) -> is_blank s
637 | _ -> false
638
639 let rec is_var_in_recursive_format = function
640 | (_,UnpTerminal s) when not (is_blank s) -> true
641 | (loc,UnpBox (b,l)) ->
642 (match List.filter (fun a -> not (is_formatting a)) l with
643 | [a] -> is_var_in_recursive_format a
644 | _ -> error_not_same ?loc ())
645 | _ -> false
646
647 let rec check_eq_var_upto_name = function
648 | (_,UnpTerminal s1), (_,UnpTerminal s2) when not (is_blank s1 && is_blank s2) || s1 = s2 -> ()
649 | (_,UnpBox (b1,l1)), (_,UnpBox (b2,l2)) when b1 = b2 -> List.iter check_eq_var_upto_name (List.combine l1 l2)
650 | (_,UnpCut b1), (_,UnpCut b2) when b1 = b2 -> ()
651 | _, (loc,_) -> error_not_same ?loc ()
652
653 let skip_var_in_recursive_format = function
654 | a :: sl when is_var_in_recursive_format a -> a, sl
655 | (loc,_) :: _ -> error_not_same ?loc ()
656 | [] -> assert false
657
658 let read_recursive_format sl fmt =
659 (* Turn [[UnpTerminal s :: some-list @ UnpTerminal ".." :: same-some-list @ UnpTerminal s' :: rest] *)
660 (* into [(some-list,rest)] *)
661 let get_head fmt =
662 let var,sl = skip_var_in_recursive_format fmt in
663 try var, split_format_at_ldots [] sl
664 with Exit -> error_not_same ?loc:(fst (List.last (if sl = [] then fmt else sl))) () in
665 let rec get_tail = function
666 | (loc,a) :: sepfmt, (_,b) :: fmt when (=) a b -> get_tail (sepfmt, fmt) (* FIXME *)
667 | [], tail -> skip_var_in_recursive_format tail
668 | (loc,_) :: _, ([] | (_,UnpTerminal _) :: _)-> error_not_same ?loc ()
669 | _, (loc,_)::_ -> error_not_same ?loc () in
670 let var1, (loc, slfmt, fmt) = get_head fmt in
671 let var2, res = get_tail (slfmt, fmt) in
672 check_eq_var_upto_name (var1,var2);
673 (* To do, though not so important: check that the names match
674 the names in the notation *)
675 slfmt, res
676
677 let hunks_of_format (from_level,(vars,typs)) symfmt =
678 let rec aux = function
679 | symbs, (_,(UnpTerminal s' as u)) :: fmt
680 when String.equal s' (String.make (String.length s') ' ') ->
681 let symbs, l = aux (symbs,fmt) in symbs, u :: l
682 | Terminal s :: symbs, (_,UnpTerminal s') :: fmt
683 when String.equal s (String.drop_simple_quotes s') ->
684 let symbs, l = aux (symbs,fmt) in symbs, UnpTerminal s :: l
685 | NonTerminal s :: symbs, (_,UnpTerminal s') :: fmt when Id.equal s (Id.of_string s') ->
686 let i = index_id s vars in
687 let symbs, l = aux (symbs,fmt) in symbs, unparsing_metavar i from_level typs :: l
688 | symbs, (_,(UnpCut _ as u)) :: fmt ->
689 let symbs, l = aux (symbs,fmt) in symbs, u :: l
690 | SProdList (m,sl) :: symbs, fmt when has_ldots fmt ->
691 let i = index_id m vars in
692 let typ = List.nth typs (i-1) in
693 let subentry = unparsing_precedence_of_entry_type from_level typ in
694 let loc_slfmt,rfmt = read_recursive_format sl fmt in
695 let sl, slfmt = aux (sl,loc_slfmt) in
696 if not (List.is_empty sl) then error_format ?loc:(find_prod_list_loc loc_slfmt fmt) ();
697 let symbs, l = aux (symbs,rfmt) in
698 let hunk = match typ with
699 | ETConstr _ -> UnpListMetaVar (subentry,slfmt)
700 | ETBinder isopen ->
701 check_open_binder isopen sl m;
702 UnpBinderListMetaVar (isopen,true,slfmt)
703 | ETName | ETIdent ->
704 UnpBinderListMetaVar (false,true,slfmt)
705 | ETPattern _ ->
706 UnpBinderListMetaVar (false,false,slfmt)
707 | _ -> assert false in
708 symbs, hunk :: l
709 | symbs, (_,UnpBox (a,b)) :: fmt ->
710 let symbs', b' = aux (symbs,b) in
711 let symbs', l = aux (symbs',fmt) in
712 symbs', UnpBox (a,List.map (fun x -> (None,x)) b') :: l
713 | symbs, [] -> symbs, []
714 | Break _ :: symbs, fmt -> warn_format_break (); aux (symbs,fmt)
715 | _, fmt -> error_format ?loc:(fst (List.hd fmt)) ()
716 in
717 match aux symfmt with
718 | [], l -> l
719 | _ -> error_format ()
720
721 (** **************************************************************** **)
722 (** Build parsing rules **)
723
724 let assoc_of_type from n (_,typ) = precedence_of_entry_type {notation_entry = from; notation_level = n} typ
725
726 let is_not_small_constr = function
727 ETProdConstr _ -> true
728 | _ -> false
729
730 let distribute a ll = List.map (fun l -> a @ l) ll
731
732 (* Expand LIST1(t,sep);sep;t;...;t (with the trailing pattern
733 occurring p times, possibly p=0) into the combination of
734 t;sep;t;...;t;sep;t (p+1 times)
735 t;sep;t;...;t;sep;t;sep;t (p+2 times)
736 ...
737 t;sep;t;...;t;sep;t;...;t;sep;t (p+n times)
738 t;sep;t;...;t;sep;t;...;t;sep;t;LIST1(t,sep) *)
739
740 let expand_list_rule s typ tkl x n p ll =
741 let camlp5_message_name = Some (add_suffix x ("_"^string_of_int n)) in
742 let main = GramConstrNonTerminal (ETProdConstr (s,typ), camlp5_message_name) in
743 let tks = List.map (fun (kw,s) -> GramConstrTerminal (kw, s)) tkl in
744 let rec aux i hds ll =
745 if i < p then aux (i+1) (main :: tks @ hds) ll
746 else if Int.equal i (p+n) then
747 let hds =
748 GramConstrListMark (p+n,true,p) :: hds
749 @ [GramConstrNonTerminal (ETProdConstrList (s, typ,tkl), Some x)] in
750 distribute hds ll
751 else
752 distribute (GramConstrListMark (i+1,false,p) :: hds @ [main]) ll @
753 aux (i+1) (main :: tks @ hds) ll in
754 aux 0 [] ll
755
756 let is_constr_typ (s,lev) x etyps =
757 match List.assoc x etyps with
758 (* TODO: factorize these rules with the ones computing the effective
759 sublevel sent to camlp5, so as to include the case of
760 DefaultLevel which are valid *)
761 | ETConstr (s',_,(lev',InternalProd | (NumLevel _ | NextLevel as lev'), _)) ->
762 notation_entry_eq s s' && production_level_eq lev lev'
763 | _ -> false
764
765 let include_possible_similar_trailing_pattern typ etyps sl l =
766 let rec aux n = function
767 | Terminal s :: sl, Terminal s'::l' when s = s' -> aux n (sl,l')
768 | [], NonTerminal x ::l' when is_constr_typ typ x etyps -> try_aux n l'
769 | Break _ :: sl, l -> aux n (sl,l)
770 | sl, Break _ :: l -> aux n (sl,l)
771 | _ -> raise_notrace Exit
772 and try_aux n l =
773 try aux (n+1) (sl,l)
774 with Exit -> n,l in
775 try_aux 0 l
776
777 let prod_entry_type = function
778 | ETIdent -> ETProdIdent
779 | ETName -> ETProdName
780 | ETGlobal -> ETProdGlobal
781 | ETBigint -> ETProdBigint
782 | ETBinder o -> ETProdOneBinder o
783 | ETConstr (s,_,p) -> ETProdConstr (s,p)
784 | ETPattern (_,n) -> ETProdPattern (pattern_entry_level n)
785
786 let keyword_needed need s =
787 (* Ensure that IDENT articulation terminal symbols are keywords *)
788 match CLexer.terminal s with
789 | Tok.PIDENT (Some k) ->
790 if need then
791 Flags.if_verbose Feedback.msg_info (str "Identifier '" ++ str k ++ str "' now a keyword");
792 need
793 | _ ->
794 match NumTok.Unsigned.parse_string s with
795 | Some n ->
796 if need then
797 Flags.if_verbose Feedback.msg_info (str "Number '" ++ NumTok.Unsigned.print n ++ str "' now a keyword");
798 need
799 | None ->
800 match String.unquote_coq_string s with
801 | Some _ ->
802 if need then
803 Flags.if_verbose Feedback.msg_info (str "String '" ++ str s ++ str "' now a keyword");
804 need
805 | _ -> true
806
807 let make_production ({notation_level = lev}, _) etyps symbols =
808 let rec aux need = function
809 | [] -> [[]]
810 | NonTerminal m :: l ->
811 let typ = prod_entry_type (List.assoc m etyps) in
812 distribute [GramConstrNonTerminal (typ, Some m)] (aux (is_not_small_constr typ) l)
813 | Terminal s :: l ->
814 let keyword = keyword_needed need s in
815 distribute [GramConstrTerminal (keyword,s)] (aux false l)
816 | Break _ :: l ->
817 aux need l
818 | SProdList (x,sl) :: l ->
819 let tkl = List.flatten
820 (List.map (function Terminal s -> [s]
821 | Break _ -> []
822 | _ -> anomaly (Pp.str "Found a non terminal token in recursive notation separator.")) sl) in
823 let tkl = List.map_i (fun i x -> let need = (i=0) in (keyword_needed need x, x)) 0 tkl in
824 match List.assoc x etyps with
825 | ETConstr (s,_,(lev,_ as typ)) ->
826 let p,l' = include_possible_similar_trailing_pattern (s,lev) etyps sl l in
827 expand_list_rule s typ tkl x 1 p (aux true l')
828 | ETBinder o ->
829 check_open_binder o sl x;
830 let typ = if o then (assert (tkl = []); ETBinderOpen) else ETBinderClosed (None,tkl) in
831 distribute
832 [GramConstrNonTerminal (ETProdBinderList typ, Some x)] (aux false l)
833 | ETIdent ->
834 distribute
835 [GramConstrNonTerminal (ETProdBinderList (ETBinderClosed (Some ETProdIdent,tkl)), Some x)] (aux false l)
836 | ETName ->
837 distribute
838 [GramConstrNonTerminal (ETProdBinderList (ETBinderClosed (Some ETProdName,tkl)), Some x)] (aux false l)
839 | ETPattern (st,n) ->
840 distribute
841 [GramConstrNonTerminal (ETProdBinderList (ETBinderClosed (Some (ETProdPattern (pattern_entry_level n)),tkl)), Some x)] (aux false l)
842 | _ ->
843 user_err Pp.(str "Components of recursive patterns in notation must be terms or binders.") in
844 let need = (* a leading ident/number factorizes iff at level 0 *) lev <> 0 in
845 aux need symbols
846
847 let rec find_symbols c_current c_next c_last = function
848 | [] -> []
849 | NonTerminal id :: sl ->
850 let prec = if not (List.is_empty sl) then c_current else c_last in
851 (id, prec) :: (find_symbols c_next c_next c_last sl)
852 | Terminal s :: sl -> find_symbols c_next c_next c_last sl
853 | Break n :: sl -> find_symbols c_current c_next c_last sl
854 | SProdList (x,_) :: sl' ->
855 (x,c_next)::(find_symbols c_next c_next c_last sl')
856
857 let border = function
858 | (_,(ETConstr(_,_,(_,BorderProd (_,a))))) :: _ -> a
859 | _ -> None
860
861 let recompute_assoc typs = let open Gramlib.Gramext in
862 match border typs, border (List.rev typs) with
863 | Some LeftA, Some RightA -> assert false
864 | Some LeftA, _ -> Some LeftA
865 | _, Some RightA -> Some RightA
866 | _ -> None
867
868 (** ******************************************************************** **)
869 (** Registration of syntax extensions **)
870 (** (parsing/printing, no interpretation) **)
871
872 let pr_arg_level from (lev,typ) =
873 let pplev = function
874 | LevelLt n when Int.equal n from -> spc () ++ str "at next level"
875 | LevelLe n -> spc () ++ str "at level " ++ int n
876 | LevelLt n -> spc () ++ str "at level below " ++ int n
877 | LevelSome -> mt () in
878 Ppvernac.pr_set_entry_type Nametab.CustomEntries.pr (fun _ -> (*TO CHECK*) mt()) typ ++ pplev lev
879
880 let pr_level ({notation_entry = from; notation_level = fromlevel}, args) typs =
881 (match from with InConstrEntry -> mt () | InCustomEntry s -> str "in " ++ Nametab.CustomEntries.pr s ++ spc()) ++
882 str "at level " ++ int fromlevel ++
883 (match args with | [] -> mt () | _ :: _ ->
884 spc () ++ str "with arguments" ++ spc()
885 ++ prlist_with_sep pr_comma (pr_arg_level fromlevel) (List.combine args typs))
886
887 let error_incompatible_level ntn oldprec oldtyps prec typs =
888 user_err
889 (str "Notation " ++ pr_notation ntn ++ str " is already defined" ++ spc() ++
890 pr_level oldprec oldtyps ++
891 spc() ++ str "while it is now required to be" ++ spc() ++
892 pr_level prec typs ++ str ".")
893
894 let error_parsing_incompatible_level ntn ntn' oldprec oldtyps prec typs =
895 user_err
896 (str "Notation " ++ pr_notation ntn ++ str " relies on a parsing rule for " ++ pr_notation ntn' ++ spc() ++
897 str " which is already defined" ++ spc() ++
898 pr_level oldprec oldtyps ++
899 spc() ++ str "while it is now required to be" ++ spc() ++
900 pr_level prec typs ++ str ".")
901
902 let warn_incompatible_format =
903 CWarnings.create ~name:"notation-incompatible-format" ~category:CWarnings.CoreCategories.parsing
904 (fun (specific,ntn) ->
905 let head,scope = match specific with
906 | None -> str "Notation", mt ()
907 | Some LastLonelyNotation -> str "Lonely notation", mt ()
908 | Some (NotationInScope sc) -> str "Notation", strbrk (" in scope " ^ sc) in
909 head ++ spc () ++ pr_notation ntn ++
910 strbrk " was already defined with a different format" ++ scope ++ str ".")
911
912 type syntax_extension = {
913 synext_level : level;
914 synext_nottyps : constr_entry_key list;
915 synext_notgram : notation_grammar option;
916 synext_notprint : generic_notation_printing_rules option;
917 }
918
919 type syntax_rules =
920 | PrimTokenSyntax
921 | SpecificSyntax of syntax_extension
922
923 let syntax_rules_iter f = function
924 | PrimTokenSyntax -> ()
925 | SpecificSyntax synext -> f synext
926
927 let check_reserved_format ntn rules rules' =
928 try
929 let { notation_printing_reserved = reserved; notation_printing_rules = generic_rules } = rules in
930 if reserved &&
931 (not (List.for_all2eq unparsing_eq rules'.notation_printing_unparsing generic_rules.notation_printing_unparsing))
932 then
933 warn_incompatible_format (None,ntn)
934 with Not_found -> ()
935
936 let specific_format_to_declare (specific,ntn as specific_ntn) rules =
937 try
938 let specific_rules = Ppextend.find_specific_notation_printing_rule specific_ntn in
939 if not (List.for_all2eq unparsing_eq rules.notation_printing_unparsing specific_rules.notation_printing_unparsing)
940 then (warn_incompatible_format (Some specific,ntn); true)
941 else false
942 with Not_found -> true
943
944 type syntax_extension_obj =
945 locality_flag * (notation * syntax_extension)
946
947 let check_and_extend_constr_grammar ntn rule =
948 try
949 let ntn_for_grammar = rule.notgram_notation in
950 if notation_eq ntn ntn_for_grammar then raise Not_found;
951 let prec = rule.notgram_level in
952 let typs = rule.notgram_typs in
953 let oldprec = Notation.level_of_notation ntn_for_grammar in
954 let oldparsing =
955 try
956 Some (Notgram_ops.grammar_of_notation ntn_for_grammar)
957 with Not_found -> None
958 in
959 let oldtyps = Notgram_ops.non_terminals_of_notation ntn_for_grammar in
960 if not (level_eq prec oldprec) && oldparsing <> None then
961 error_parsing_incompatible_level ntn ntn_for_grammar oldprec oldtyps prec typs;
962 if oldparsing = None then raise Not_found
963 with Not_found ->
964 Egramrocq.extend_constr_grammar rule
965
966 let warn_prefix_incompatible_level =
967 CWarnings.create ~name:"notation-incompatible-prefix"
968 ~category:CWarnings.CoreCategories.parsing
969 (fun (pref, ntn, pref_prec, pref_nottyps, prec, nottyps) ->
970 str "Notations " ++ pr_notation pref
971 ++ spc () ++ str "defined " ++ pr_level pref_prec pref_nottyps
972 ++ spc () ++ str "and " ++ pr_notation ntn
973 ++ spc () ++ str "defined " ++ pr_level prec nottyps
974 ++ spc () ++ str "have incompatible prefixes."
975 ++ spc () ++ str "One of them will likely not work.")
976
977 let level_firstn k (lvl, lvls) =
978 lvl, try CList.firstn k lvls with Failure _ -> []
979
980 let check_prefix_incompatible_level ntn prec nottyps =
981 match Notgram_ops.longest_common_prefix ntn with
982 | None -> ()
983 | Some (pref, k) ->
984 try
985 let pref_prec = Notation.level_of_notation pref in
986 let pref_prec = level_firstn k pref_prec in
987 let prec = level_firstn k prec in
988 let pref_nottyps = Notgram_ops.non_terminals_of_notation pref in
989 let pref_nottyps = CList.firstn k pref_nottyps in
990 let nottyps = CList.firstn k nottyps in
991 if not (level_eq prec pref_prec && List.for_all2 Extend.constr_entry_key_eq_ignore_binder_kind nottyps pref_nottyps) then
992 warn_prefix_incompatible_level (pref, ntn, pref_prec, pref_nottyps, prec, nottyps);
993 with Not_found | Failure _ -> ()
994
995 let cache_one_syntax_extension (ntn,synext) =
996 let prec = synext.synext_level in
997 (* Check and ensure that the level and the precomputed parsing rule is declared *)
998 let oldparsing =
999 try
1000 let oldprec = Notation.level_of_notation ntn in
1001 let oldparsing =
1002 try
1003 Some (Notgram_ops.grammar_of_notation ntn)
1004 with Not_found -> None
1005 in
1006 let oldtyps = Notgram_ops.non_terminals_of_notation ntn in
1007 if not (level_eq prec oldprec && List.for_all2 Extend.constr_entry_key_eq synext.synext_nottyps oldtyps) &&
1008 (oldparsing <> None || synext.synext_notgram = None) then
1009 error_incompatible_level ntn oldprec oldtyps prec synext.synext_nottyps;
1010 oldparsing
1011 with Not_found ->
1012 check_prefix_incompatible_level ntn prec synext.synext_nottyps;
1013 (* Declare the level and the precomputed parsing rule *)
1014 let () = Notation.declare_notation_level ntn prec in
1015 let () = Notgram_ops.declare_notation_non_terminals ntn synext.synext_nottyps in
1016 let () = Option.iter (Notgram_ops.declare_notation_grammar ntn) synext.synext_notgram in
1017 None in
1018 (* Declare the parsing rule *)
1019 begin match oldparsing, synext.synext_notgram with
1020 | None, Some grams -> List.iter (check_and_extend_constr_grammar ntn) grams
1021 | _ -> (* The grammars rules are canonically derived from the string and the precedence*) ()
1022 end;
1023 (* Printing *)
1024 Option.iter (declare_generic_notation_printing_rules ntn) synext.synext_notprint
1025
1026 let cache_syntax_extension (_, sy) =
1027 cache_one_syntax_extension sy
1028
1029 let subst_syntax_extension (subst, (local, (ntn, synext))) =
1030 (local, (ntn, synext))
1031
1032 let classify_syntax_definition (local, _) =
1033 if local then Dispose else Substitute
1034
1035 let inSyntaxExtension : syntax_extension_obj -> obj =
1036 declare_object
1037 {(default_object "SYNTAX-EXTENSION") with
1038 object_stage = Summary.Stage.Synterp;
1039 open_function = simple_open ~cat:notation_cat cache_syntax_extension;
1040 cache_function = cache_syntax_extension;
1041 subst_function = subst_syntax_extension;
1042 classify_function = classify_syntax_definition}
1043
1044 (** ******************************************************************** **)
1045 (** Precedences **)
1046
1047 (* Interpreting user-provided modifiers *)
1048
1049 (* XXX: We could move this to the parser itself *)
1050
1051 module NotationMods = struct
1052
1053 type notation_modifier = {
1054 assoc : Gramlib.Gramext.g_assoc option;
1055 level : int option;
1056 etyps : (Id.t * CustomName.t simple_constr_prod_entry_key) list;
1057
1058 (* common to syn_data below *)
1059 format : lstring option;
1060 }
1061
1062 let default = {
1063 assoc = None;
1064 level = None;
1065 etyps = [];
1066 format = None;
1067 }
1068
1069 end
1070
1071 let intern_entry_type = function
1072 | ETConstr (entry,x,y) ->
1073 let entry = intern_notation_entry entry in
1074 ETConstr (entry,x,y)
1075 | ETPattern _ | ETIdent | ETGlobal | ETBigint | ETName | ETBinder _ as v ->
1076 v
1077
1078 let interp_modifiers entry modl = let open NotationMods in
1079 let rec interp acc = function
1080 | [] -> acc
1081 | CAst.{loc;v} :: l -> match v with
1082 | SetEntryType (s,typ) ->
1083 let id = Id.of_string s in
1084 let typ = intern_entry_type typ in
1085 if Id.List.mem_assoc id acc.etyps then
1086 user_err ?loc
1087 (str s ++ str " is already assigned to an entry or constr level.");
1088 interp { acc with etyps = (id,typ) :: acc.etyps; } l
1089 | SetItemLevel ([],bko,n) ->
1090 interp acc l
1091 | SetItemLevel (s::idl,bko,n) ->
1092 let id = Id.of_string s in
1093 if Id.List.mem_assoc id acc.etyps then
1094 user_err ?loc
1095 (str s ++ str " is already assigned to an entry or constr level.");
1096 interp { acc with etyps = (id,ETConstr (entry,bko,n)) :: acc.etyps } ((CAst.make ?loc @@ SetItemLevel (idl,bko,n))::l)
1097 | SetLevel n ->
1098 (match entry with
1099 | InCustomEntry s ->
1100 if acc.level <> None then
1101 user_err ?loc (str ("isolated \"at level " ^ string_of_int n ^ "\" unexpected."))
1102 else
1103 (* XXX could we print the qualid used for the custom entry by the user
1104 instead of shortest_qualid? *)
1105 user_err ?loc (str "use \"in custom " ++ Nametab.CustomEntries.pr s ++ str " at level " ++ int n ++
1106 str "\"" ++ spc () ++ str "rather than" ++ spc () ++
1107 str ("\"at level " ^ string_of_int n ^ "\"") ++
1108 spc () ++ str "isolated.")
1109 | InConstrEntry ->
1110 if acc.level <> None then
1111 user_err ?loc (str "A level is already assigned.");
1112 interp { acc with level = Some n; } l)
1113 | SetCustomEntry (s,Some n) ->
1114 (* Note: name of entry already registered in interp_non_syntax_modifiers *)
1115 if acc.level <> None then
1116 user_err ?loc (str ("isolated \"at level " ^ string_of_int (Option.get acc.level) ^ "\" unexpected."));
1117 interp { acc with level = Some n } l
1118 | SetAssoc a ->
1119 if not (Option.is_empty acc.assoc) then user_err ?loc Pp.(str "An associativity is given more than once.");
1120 interp { acc with assoc = Some a; } l
1121 | SetOnlyParsing | SetOnlyPrinting | SetCustomEntry (_,None) | SetFormat _ | SetItemScope _ ->
1122 (* interpreted in interp_non_syntax_modifiers *)
1123 assert false
1124 in
1125 interp default modl
1126
1127 let check_useless_entry_types recvars mainvars etyps =
1128 let vars = let (l1,l2) = List.split recvars in l1@l2@mainvars in
1129 match List.filter (fun (x,etyp) -> not (List.mem x vars)) etyps with
1130 | (x,_)::_ -> user_err
1131 (Id.print x ++ str " is unbound in the notation.")
1132 | _ -> ()
1133
1134 type notation_main_data = {
1135 onlyparsing : bool;
1136 onlyprinting : bool;
1137 user_warns : UserWarn.t option;
1138 entry : notation_entry;
1139 format : unparsing Loc.located list option;
1140 itemscopes : (Id.t * scope_name) list;
1141 }
1142
1143 let warn_only_parsing_reserved_notation =
1144 CWarnings.create ~name:"irrelevant-reserved-notation-only-parsing" ~category:CWarnings.CoreCategories.parsing
1145 (fun () -> strbrk "The only parsing modifier has no effect in Reserved Notation.")
1146
1147 let warn_only_parsing_discarded_format =
1148 CWarnings.create ~name:"discarded-format-only-parsing" ~category:CWarnings.CoreCategories.parsing
1149 (fun () -> strbrk "The format modifier has no effect for only-parsing notations.")
1150
1151 let error_onlyparsing_onlyprinting ?loc =
1152 user_err ?loc (str "A notation cannot be both \"only printing\" and \"only parsing\".")
1153
1154 let set_onlyparsing ?loc ~reserved main_data =
1155 if reserved then
1156 (warn_only_parsing_reserved_notation ?loc ();
1157 main_data)
1158 else
1159 (if main_data.onlyparsing then user_err ?loc (str "\"only parsing\" is given more than once.");
1160 if main_data.onlyprinting then error_onlyparsing_onlyprinting ?loc;
1161 { main_data with onlyparsing = true })
1162
1163 let set_onlyprinting ?loc main_data =
1164 if main_data.onlyprinting then user_err ?loc (str "\"only printing\" is given more than once.");
1165 if main_data.onlyparsing then error_onlyparsing_onlyprinting ?loc;
1166 { main_data with onlyprinting = true }
1167
1168 let set_custom_entry ?loc main_data entry' =
1169 let entry' = intern_custom_name entry' in
1170 match main_data.entry with
1171 | InConstrEntry -> { main_data with entry = InCustomEntry entry' }
1172 | _ -> user_err ?loc (str "\"in custom\" is given more than once.")
1173
1174 let warn_irrelevant_format =
1175 CWarnings.create ~name:"irrelevant-format-only-parsing" ~category:CWarnings.CoreCategories.parsing
1176 (fun () -> str "The format modifier is irrelevant for only-parsing rules.")
1177
1178 let set_format ?loc main_data format =
1179 if not (Option.is_empty main_data.format) then user_err ?loc Pp.(str "A format is given more than once.");
1180 let format = if main_data.onlyparsing then (warn_irrelevant_format ?loc (); None) else Some (parse_format format) in
1181 { main_data with format }
1182
1183 let set_item_scope ?loc main_data ids sc =
1184 let itemscopes = List.map (fun id -> (Id.of_string id,sc)) ids @ main_data.itemscopes in
1185 match List.duplicates (fun (id1,_) (id2,_) -> Id.equal id1 id2) itemscopes with
1186 | (id,_)::_ -> user_err ?loc (str "Notation scope for argument " ++ Id.print id ++ str " can be specified only once.")
1187 | [] -> { main_data with itemscopes }
1188
1189 let interp_non_syntax_modifiers ~reserved ~infix ~abbrev user_warns mods =
1190 let set (main_data,rest) = CAst.with_loc_val (fun ?loc -> function
1191 | SetOnlyParsing ->
1192 if not (Option.is_empty main_data.format) then
1193 (warn_only_parsing_discarded_format ?loc (); (main_data, rest))
1194 else
1195 (set_onlyparsing ?loc ~reserved main_data,rest)
1196 | SetOnlyPrinting when not abbrev -> (set_onlyprinting ?loc main_data,rest)
1197 | SetCustomEntry (entry,None) when not abbrev -> (set_custom_entry ?loc main_data entry,rest)
1198 | SetCustomEntry (entry,Some _) as x when not abbrev -> (set_custom_entry main_data entry,CAst.make ?loc x :: rest)
1199 | SetEntryType _ when infix -> user_err ?loc Pp.(str "Unexpected entry type in infix notation.")
1200 | SetItemLevel _ when infix -> user_err ?loc Pp.(str "Unexpected entry level in infix notation.")
1201 | SetFormat (TextFormat s) when not abbrev -> (set_format ?loc main_data s, rest)
1202 | SetItemScope (ids,sc) -> (set_item_scope ?loc main_data ids sc, rest)
1203 | modif -> (main_data,(CAst.make ?loc modif)::rest))
1204 in
1205 let main_data =
1206 {
1207 onlyparsing = false; onlyprinting = false; user_warns;
1208 entry = InConstrEntry; format = None; itemscopes = []
1209 }
1210 in
1211 let main_data, rest = List.fold_left set (main_data,[]) mods in
1212 main_data, List.rev rest
1213
1214 (* Compute precedences from modifiers (or find default ones) *)
1215
1216 let set_entry_type from n etyps (x,typ) =
1217 let make_lev n s = match typ with
1218 | BorderProd _ -> NumLevel n
1219 | InternalProd -> DefaultLevel in
1220 let typ = try
1221 match List.assoc x etyps, typ with
1222 | ETConstr (s,bko,DefaultLevel), _ ->
1223 if notation_entry_eq from s then ETConstr (s,bko,(make_lev n s,typ))
1224 else ETConstr (s,bko,(DefaultLevel,typ))
1225 | ETConstr (s,bko,n), BorderProd (left,_) ->
1226 ETConstr (s,bko,(n,BorderProd (left,None)))
1227 | ETConstr (s,bko,n), InternalProd ->
1228 ETConstr (s,bko,(n,InternalProd))
1229 | ETPattern (b,n), _ -> ETPattern (b,n)
1230 | (ETIdent | ETName | ETBigint | ETGlobal | ETBinder _ as x), _ -> x
1231 with Not_found ->
1232 ETConstr (from,None,(make_lev n from,typ))
1233 in (x,typ)
1234
1235 let join_auxiliary_recursive_types recvars etyps =
1236 List.fold_right (fun (x,y) typs ->
1237 let xtyp = try Some (List.assoc x etyps) with Not_found -> None in
1238 let ytyp = try Some (List.assoc y etyps) with Not_found -> None in
1239 match xtyp,ytyp with
1240 | None, None -> typs
1241 | Some _, None -> typs
1242 | None, Some ytyp -> (x,ytyp)::typs
1243 | Some xtyp, Some ytyp when (=) xtyp ytyp -> typs (* FIXME *)
1244 | Some xtyp, Some ytyp ->
1245 user_err
1246 (strbrk "In " ++ Id.print x ++ str " .. " ++ Id.print y ++
1247 strbrk ", both ends have incompatible types."))
1248 recvars etyps
1249
1250 let internalization_type_of_entry_type = function
1251 | ETBinder _ | ETConstr (_,Some _,_) -> NtnInternTypeOnlyBinder
1252 | ETConstr (_,None,_) | ETBigint | ETGlobal
1253 | ETIdent | ETName | ETPattern _ -> NtnInternTypeAny None
1254
1255 let make_internalization_vars recvars maintyps =
1256 let maintyps = List.map (on_snd internalization_type_of_entry_type) maintyps in
1257 let extratyps = List.map (fun (x,y) -> (y,List.assoc x maintyps)) recvars in
1258 maintyps @ extratyps
1259
1260 let make_interpretation_type isrec isbinding default_if_binding typ =
1261 match typ, isrec with
1262 (* Parsed as constr, but interpreted as a specific kind of binder *)
1263 | ETConstr (_,Some bk,_), true -> NtnTypeBinderList (NtnBinderParsedAsConstr bk)
1264 | ETConstr (_,Some bk,_), false -> NtnTypeBinder (NtnBinderParsedAsConstr bk)
1265 (* Parsed as constr list but interpreted as the default kind of binder *)
1266 | ETConstr (_,None,_), true when isbinding -> NtnTypeBinderList (NtnBinderParsedAsConstr default_if_binding)
1267 | ETConstr (_,None,_), false when isbinding -> NtnTypeBinder (NtnBinderParsedAsConstr default_if_binding)
1268 (* Parsed as constr, interpreted as constr *)
1269 | ETConstr (_,None,_), true -> NtnTypeConstrList
1270 | ETConstr (_,None,_), false -> NtnTypeConstr
1271 (* Different way of parsing binders, maybe interpreted also as
1272 constr, but conventionally internally binders *)
1273 | ETIdent, true -> NtnTypeBinderList (NtnBinderParsedAsSomeBinderKind AsIdent)
1274 | ETIdent, false -> NtnTypeBinder (NtnBinderParsedAsSomeBinderKind AsIdent)
1275 | ETName, true -> NtnTypeBinderList (NtnBinderParsedAsSomeBinderKind AsName)
1276 | ETName, false -> NtnTypeBinder (NtnBinderParsedAsSomeBinderKind AsName)
1277 (* Parsed as ident/pattern, primarily interpreted as binder; maybe strict at printing *)
1278 | ETPattern (ppstrict,_), true -> NtnTypeBinderList (NtnBinderParsedAsSomeBinderKind (if ppstrict then AsStrictPattern else AsAnyPattern))
1279 | ETPattern (ppstrict,_), false -> NtnTypeBinder (NtnBinderParsedAsSomeBinderKind (if ppstrict then AsStrictPattern else AsAnyPattern))
1280 | ETBinder _, true -> NtnTypeBinderList NtnBinderParsedAsBinder
1281 | ETBinder _, false -> NtnTypeBinder NtnBinderParsedAsBinder
1282 (* Others *)
1283 | ETBigint, true | ETGlobal, true -> NtnTypeConstrList
1284 | ETBigint, false | ETGlobal, false -> NtnTypeConstr
1285
1286 let entry_relative_level_of_constr_prod_entry from_level = function
1287 | ETConstr (entry,_,(_,y)) as x ->
1288 let side = match y with BorderProd (side,_) -> Some side | _ -> None in
1289 { notation_subentry = entry; notation_relative_level = precedence_of_entry_type from_level x; notation_position = side }
1290 | _ -> constr_some_level
1291
1292 let make_interpretation_vars
1293 (* For binders, default is to parse only as an ident *) ?(default_if_binding=AsName)
1294 recvars allvars (entry,_) typs =
1295 let eq_subscope (sc1, l1) (sc2, l2) =
1296 List.equal String.equal sc1 sc2 &&
1297 List.equal String.equal l1 l2
1298 in
1299 let check (x, y) =
1300 let (_,scope1,_ntn_binding_ids1) = Id.Map.find x allvars in
1301 let (_,scope2,_ntn_binding_ids2) = Id.Map.find y allvars in
1302 if not (eq_subscope scope1 scope2) then error_not_same_scope x y
1303 (* Note: binding_ids should currently be the same, and even with
1304 eventually more complex notations, such as e.g.
1305 Notation "!! x .. y , P .. Q" := (fun x => (P, .. (fun y => (Q, True)) ..)).
1306 each occurrence of the recursive notation variables may have its own binders *)
1307 in
1308 let () = List.iter check recvars in
1309 let useless_recvars = List.map snd recvars in
1310 let mainvars =
1311 Id.Map.filter (fun x _ -> not (Id.List.mem x useless_recvars)) allvars in
1312 Id.Map.mapi (fun x (isonlybinding, sc, ntn_binding_ids) ->
1313 let typ = Id.List.assoc x typs in
1314 ((entry_relative_level_of_constr_prod_entry entry typ, sc), ntn_binding_ids,
1315 make_interpretation_type (Id.List.mem_assoc x recvars) isonlybinding default_if_binding typ)) mainvars
1316
1317 let check_rule_productivity l =
1318 if List.for_all (function NonTerminal _ | Break _ -> true | _ -> false) l then
1319 user_err Pp.(str "A notation must include at least one symbol.");
1320 if (match l with SProdList _ :: _ -> true | _ -> false) then
1321 user_err Pp.(str "A recursive notation must start with at least one symbol.")
1322
1323 let warn_notation_bound_to_variable =
1324 CWarnings.create ~name:"notation-bound-to-variable" ~category:CWarnings.CoreCategories.parsing
1325 (fun () ->
1326 strbrk "This notation will not be used for printing as it is bound to a single variable.")
1327
1328 let warn_non_reversible_notation =
1329 CWarnings.create ~name:"non-reversible-notation" ~category:CWarnings.CoreCategories.parsing
1330 (function[@warning "+9"]
1331 | APrioriReversible -> assert false
1332 | Forgetful {
1333 forget_ltac=ltac;
1334 forget_volatile_cast=cast;
1335 } ->
1336 let what = (if ltac then ["Ltac expressions"] else [])
1337 @ (if cast then ["volatile casts"] else [])
1338 in
1339 strbrk "This notation contains " ++
1340 prlist_with_sep (fun () -> strbrk " and ") str what ++ str ":" ++ spc() ++
1341 str "it will not be used for printing."
1342 | NonInjective ids ->
1343 let n = List.length ids in
1344 strbrk (String.plural n "Variable") ++ spc () ++ pr_enum Id.print ids ++ spc () ++
1345 strbrk (if n > 1 then "do" else "does") ++
1346 str " not occur in the right-hand side." ++ spc() ++
1347 strbrk "The notation will not be used for printing as it is not reversible.")
1348
1349 let is_coercion level typs =
1350 match level, typs with
1351 | Some ({notation_entry = custom; notation_level = n} as entry,_), [_,e] ->
1352 (match e, custom with
1353 | ETConstr _, _ ->
1354 let entry_relative = entry_relative_level_of_constr_prod_entry entry e in
1355 if is_coercion entry entry_relative then
1356 Some (IsEntryCoercion (entry,entry_relative))
1357 else
1358 None
1359 | ETGlobal, InCustomEntry s -> Some (IsEntryGlobal (s,n))
1360 | ETIdent, InCustomEntry s -> Some (IsEntryIdent (s,n))
1361 | _ -> None)
1362 | Some _, _ -> assert false
1363 | None, _ -> None
1364
1365 let printability level typs vars onlyparsing reversibility = function
1366 | NVar id when reversibility = APrioriReversible && List.mem_assoc_f Id.equal id vars ->
1367 let coe = is_coercion level typs in
1368 let onlyparsing =
1369 if not onlyparsing && Option.is_empty coe then
1370 (warn_notation_bound_to_variable (); true)
1371 else
1372 onlyparsing in
1373 onlyparsing, coe
1374 | _ ->
1375 (if not onlyparsing && reversibility <> APrioriReversible then
1376 (warn_non_reversible_notation reversibility; true)
1377 else onlyparsing),None
1378
1379 let warn_closed_notation_not_level_0 =
1380 CWarnings.create ~name:"closed-notation-not-level-0" ~category:CWarnings.CoreCategories.parsing
1381 (fun () -> strbrk "Closed notations (i.e. starting and ending with a \
1382 terminal symbol) should usually be at level 0 \
1383 (default).")
1384
1385 let warn_level_0_notation_not_closed =
1386 CWarnings.create ~name:"level-0-notation-not-closed" ~category:CWarnings.CoreCategories.parsing
1387 (fun () -> strbrk "Notations at level 0 should be closed (first and last \
1388 symbols should be terminal symbols).")
1389
1390 let warn_postfix_notation_not_level_1 =
1391 CWarnings.create ~name:"postfix-notation-not-level-1" ~category:CWarnings.CoreCategories.parsing
1392 (fun () -> strbrk "Postfix notations (i.e. starting with a \
1393 nonterminal symbol and ending with a terminal \
1394 symbol) should usually be at level 1 (default).")
1395
1396 let find_precedence custom lev etyps symbols onlyprint =
1397 let first_symbol =
1398 let rec aux = function
1399 | Break _ :: t -> aux t
1400 | h :: t -> Some h
1401 | [] -> None in
1402 aux symbols in
1403 let last_is_terminal () =
1404 let rec aux b = function
1405 | Break _ :: t -> aux b t
1406 | Terminal _ :: t -> aux true t
1407 | _ :: t -> aux false t
1408 | [] -> b in
1409 aux false symbols in
1410 let msgs, lev = match first_symbol with
1411 | None -> [],0
1412 | Some (NonTerminal x) ->
1413 let msgs, lev = match last_is_terminal (), lev with
1414 | false, _ -> [], lev
1415 | true, None -> [fun () -> Flags.if_verbose (Feedback.msg_info ?loc:None) (strbrk "Setting postfix notation at level 1.")], Some 1
1416 | true, Some 1 -> [], Some 1
1417 | true, Some n -> [warn_postfix_notation_not_level_1], Some n in
1418 let test () =
1419 if onlyprint then
1420 if Option.is_empty lev then
1421 user_err Pp.(str "Explicit level needed in only-printing mode when the level of the leftmost non-terminal is given.")
1422 else msgs,Option.get lev
1423 else
1424 user_err Pp.(str "The level of the leftmost non-terminal cannot be changed.") in
1425 (try match List.assoc x etyps, custom with
1426 | ETConstr (s,_,(NumLevel _ | NextLevel)), s' when s = s' -> test ()
1427 | (ETIdent | ETName | ETBigint | ETGlobal), _ ->
1428 begin match lev with
1429 | None ->
1430 ([fun () -> Flags.if_verbose (Feedback.msg_info ?loc:None) (strbrk "Setting notation at level 0.")],0)
1431 | Some 0 ->
1432 (msgs,0)
1433 | _ ->
1434 user_err Pp.(str "A notation starting with an atomic expression must be at level 0.")
1435 end
1436 | (ETPattern _ | ETBinder _), InConstrEntry when not onlyprint ->
1437 (* Don't know exactly if we can make sense of this case *)
1438 user_err Pp.(str "Binders or patterns not supported in leftmost position.")
1439 | (ETPattern _ | ETBinder _ | ETConstr _), _ ->
1440 (* Give a default ? *)
1441 if Option.is_empty lev then
1442 user_err Pp.(str "Need an explicit level.")
1443 else msgs,Option.get lev
1444 with Not_found ->
1445 if Option.is_empty lev then
1446 user_err Pp.(str "A left-recursive notation must have an explicit level.")
1447 else msgs,Option.get lev)
1448 | Some (Terminal _) when last_is_terminal () ->
1449 begin match lev with
1450 | None -> [fun () -> Flags.if_verbose (Feedback.msg_info ?loc:None) (strbrk "Setting notation at level 0.")], 0
1451 | Some 0 -> [], 0
1452 | Some n -> [warn_closed_notation_not_level_0], n
1453 end
1454 | Some _ ->
1455 if Option.is_empty lev then user_err Pp.(str "Cannot determine the level.");
1456 [],Option.get lev in
1457 if lev <> 0 then msgs, lev else
1458 match first_symbol, last_is_terminal (), symbols with
1459 (* no warning for closed notations *)
1460 | Some (Terminal _), true, _
1461 (* nor for particular cases "" and "x" *)
1462 | _, _, ([] | [_]) -> msgs, lev
1463 | _ -> msgs @ [warn_level_0_notation_not_closed], lev
1464
1465 let check_curly_brackets_notation_exists () =
1466 try let _ = Notation.level_of_notation (InConstrEntry,"{ _ }") in ()
1467 with Not_found ->
1468 user_err Pp.(str "Notations involving patterns of the form \"{ _ }\" are treated \n\
1469 specially and require that the notation \"{ _ }\" is already reserved.")
1470
1471 (* Remove patterns of the form "{ _ }", unless it is the "{ _ }" notation *)
1472 let remove_curly_brackets l =
1473 let rec skip_break acc = function
1474 | Break _ as br :: l -> skip_break (br::acc) l
1475 | l -> List.rev acc, l in
1476 let rec aux deb = function
1477 | [] -> []
1478 | Terminal "{" as t1 :: l ->
1479 let br,next = skip_break [] l in
1480 (match next with
1481 | NonTerminal _ as x :: l' ->
1482 let br',next' = skip_break [] l' in
1483 (match next' with
1484 | Terminal "}" as t2 :: l'' ->
1485 if deb && List.is_empty l'' then [t1;x;t2] else begin
1486 check_curly_brackets_notation_exists ();
1487 x :: aux false l''
1488 end
1489 | l1 -> t1 :: br @ x :: br' @ aux false l1)
1490 | l0 -> t1 :: aux false l0)
1491 | x :: l -> x :: aux false l
1492 in aux true l
1493
1494 let has_implicit_format symbols =
1495 List.exists (function Break _ -> true | _ -> false) symbols
1496
1497 (* Because of the special treatment for { }, the grammar rule sent
1498 to the parser may be different than what the user sees; e.g. for
1499 "{ A } + { B }", it is "A + B" which is sent to the parser *)
1500 type syn_pa_data = {
1501 ntn_for_grammar : notation;
1502 prec_for_grammar : level;
1503 typs_for_grammar : constr_entry_key list;
1504 need_squash : bool;
1505 }
1506
1507 module SynData = struct
1508
1509 type subentry_types = (Id.t * constr_entry_key) list
1510
1511 (* XXX: Document *)
1512 type syn_data = {
1513
1514 (* XXX: Callback to printing, must remove *)
1515 msgs : (unit -> unit) list;
1516
1517 (* Notation data for parsing *)
1518 level : level;
1519 subentries : subentry_types;
1520 pa_syntax_data : subentry_types * symbol list;
1521 pp_syntax_data : subentry_types * symbol list;
1522 not_data : syn_pa_data;
1523 }
1524
1525 end
1526
1527 let find_subentry_types from n assoc etyps symbols =
1528 let typs =
1529 find_symbols
1530 (BorderProd(Left,assoc))
1531 (InternalProd)
1532 (BorderProd(Right,assoc))
1533 symbols in
1534 let sy_typs = List.map (set_entry_type from n etyps) typs in
1535 let prec = List.map (assoc_of_type from n) sy_typs in
1536 sy_typs, prec
1537
1538 let custom_entry_locality = Summary.ref ~name:"LOCAL-CUSTOM-ENTRY" CustomName.Set.empty
1539 (** If the entry is present then local *)
1540
1541 let locality_of_custom_entry s = CustomName.Set.mem s !custom_entry_locality
1542
1543 let check_locality_compatibility local custom i_typs =
1544 if not local then
1545 let subcustom = List.map_filter (function _,ETConstr (InCustomEntry s,_,_) -> Some s | _ -> None) i_typs in
1546 let allcustoms = match custom with InCustomEntry s -> s::subcustom | _ -> subcustom in
1547 List.iter (fun s ->
1548 if locality_of_custom_entry s then
1549 user_err (strbrk "Notation has to be declared local as it depends on custom entry " ++
1550 Nametab.CustomEntries.pr s ++ strbrk " which is local."))
1551 (List.uniquize allcustoms)
1552
1553 let longest_common_prefix_level ntn =
1554 Notgram_ops.longest_common_prefix ntn
1555 |> Option.map (fun (ntn, sz) ->
1556 let level, levels = level_firstn sz (Notation.level_of_notation ntn) in
1557 ntn, level.notation_level, levels)
1558
1559 let default_prefix_level ntn_prefix =
1560 let with_prefix prefix level =
1561 Flags.if_verbose Feedback.msg_info
1562 (strbrk "Setting notation at level " ++ int level ++ spc ()
1563 ++ str "to match previous notation with longest common prefix:"
1564 ++ spc () ++ str "\"" ++ str (snd prefix) ++ str "\".");
1565 level in
1566 function Some n -> Some n | None ->
1567 Option.map (fun (prefix, level, _) -> with_prefix prefix level) ntn_prefix
1568
1569 let default_prefix_level_subentries ntn ntn_prefix symbols etyps =
1570 let with_prefix prefix from_level levels =
1571 let default_entry etyps (x, l) =
1572 let l' = match l with
1573 | LevelLt n when Int.equal n from_level -> NextLevel
1574 | LevelLe n | LevelLt n -> NumLevel n
1575 | LevelSome -> DefaultLevel in
1576 let e = List.assoc_opt x etyps
1577 |> Option.default (ETConstr (fst ntn, None, DefaultLevel)) in
1578 match l', e with
1579 | (NumLevel _ | NextLevel), ETConstr (n, b, DefaultLevel) ->
1580 Flags.if_verbose Feedback.msg_info
1581 (strbrk "Setting " ++ Id.print x ++ str " "
1582 ++ pr_arg_level from_level (l, e) ++ spc ()
1583 ++ str "to match previous notation with longest common prefix:"
1584 ++ spc () ++ str "\"" ++ str (snd prefix) ++ str "\".");
1585 (x, ETConstr (n, b, l')) :: List.remove_assoc x etyps
1586 | _ -> etyps in
1587 let levels =
1588 let rec aux levs symbs = match levs, symbs with
1589 | [], _ | _, [] | _, SProdList _ :: _ -> []
1590 (* not handling recursive notations *)
1591 | _, (Terminal _ | Break _) :: symbs -> aux levs symbs
1592 | l :: levs, NonTerminal x :: symbs -> (x, l) :: aux levs symbs in
1593 match levels, symbols with
1594 (* don't mess up with level of left border terminal *)
1595 | _ :: levs, NonTerminal _ :: symbs | levs, symbs -> aux levs symbs in
1596 List.fold_left default_entry etyps levels in
1597 match ntn_prefix with
1598 | None -> etyps
1599 | Some (prefix, from_level, levels) -> with_prefix prefix from_level levels
1600
1601 let compute_syntax_data ~local main_data notation_symbols ntn mods =
1602 let open SynData in
1603 let open NotationMods in
1604 if main_data.itemscopes <> [] then user_err (str "General notations don't support 'in scope'.");
1605 let {recvars;mainvars;symbols} = notation_symbols in
1606 let assoc = Option.append mods.assoc (Some Gramlib.Gramext.NonA) in
1607 let _ = check_useless_entry_types recvars mainvars mods.etyps in
1608
1609 (* Notations for interp and grammar *)
1610 let ntn_prefix = longest_common_prefix_level ntn in
1611 let level = default_prefix_level ntn_prefix mods.level in
1612 let msgs,n = find_precedence main_data.entry level mods.etyps symbols main_data.onlyprinting in
1613 let symbols_for_grammar =
1614 if main_data.entry = InConstrEntry then remove_curly_brackets symbols else symbols in
1615 let need_squash = not (List.equal Notation.symbol_eq symbols symbols_for_grammar) in
1616 let ntn_for_grammar = if need_squash then make_notation_key main_data.entry symbols_for_grammar else ntn in
1617 if main_data.entry = InConstrEntry && not main_data.onlyprinting then check_rule_productivity symbols_for_grammar;
1618 (* To globalize... *)
1619 let etyps = default_prefix_level_subentries ntn ntn_prefix symbols mods.etyps in
1620 let etyps = join_auxiliary_recursive_types recvars etyps in
1621 let sy_typs, prec =
1622 find_subentry_types main_data.entry n assoc etyps symbols in
1623 let sy_typs_for_grammar, prec_for_grammar =
1624 if need_squash then
1625 find_subentry_types main_data.entry n assoc etyps symbols_for_grammar
1626 else
1627 sy_typs, prec in
1628 check_locality_compatibility local main_data.entry sy_typs;
1629 let pa_sy_data = (sy_typs_for_grammar,symbols_for_grammar) in
1630 let pp_sy_data = (sy_typs,symbols) in
1631 let sy_fulldata = {
1632 ntn_for_grammar;
1633 prec_for_grammar = ({notation_entry = main_data.entry; notation_level = n}, prec_for_grammar);
1634 typs_for_grammar = List.map snd sy_typs_for_grammar;
1635 need_squash
1636 } in
1637
1638 (* Return relevant data for interpretation and for parsing/printing *)
1639 {
1640 msgs;
1641 level = ({notation_entry = main_data.entry; notation_level = n}, prec);
1642 subentries = sy_typs;
1643 pa_syntax_data = pa_sy_data;
1644 pp_syntax_data = pp_sy_data;
1645 not_data = sy_fulldata;
1646 }
1647
1648 (** **************************************************************** **)
1649 (** Registration of notation interpretation **)
1650
1651 type notation_obj = {
1652 notobj_local : bool;
1653 notobj_scope : scope_name option;
1654 notobj_interp : interpretation;
1655 notobj_coercion : entry_coercion_kind option;
1656 notobj_use : notation_use option;
1657 notobj_user_warns : UserWarn.t option;
1658 notobj_notation : notation * notation_location;
1659 notobj_specific_pp_rules : notation_printing_rules option;
1660 }
1661
1662 let load_notation_common silently_define_scope_if_undefined _ nobj =
1663 (* When the default shall be to require that a scope already exists *)
1664 (* the call to ensure_scope will have to be removed *)
1665 if silently_define_scope_if_undefined then
1666 (* Don't warn if the scope is not defined: *)
1667 (* there was already a warning at "cache" time *)
1668 Option.iter Notation.declare_scope nobj.notobj_scope
1669 else
1670 Option.iter Notation.ensure_scope nobj.notobj_scope
1671
1672 let load_notation =
1673 load_notation_common true
1674
1675 let open_notation nobj =
1676 let scope = nobj.notobj_scope in
1677 let (ntn, df) = nobj.notobj_notation in
1678 let pat = nobj.notobj_interp in
1679 let user_warns = nobj.notobj_user_warns in
1680 let scope = match scope with None -> LastLonelyNotation | Some sc -> NotationInScope sc in
1681 (* Declare the notation *)
1682 (match nobj.notobj_use with
1683 | Some use -> Notation.declare_notation (scope,ntn) pat df ~use nobj.notobj_coercion user_warns
1684 | None -> ());
1685 (* Declare specific format if any *)
1686 (match nobj.notobj_specific_pp_rules with
1687 | Some pp_sy ->
1688 if specific_format_to_declare (scope,ntn) pp_sy then
1689 Ppextend.declare_specific_notation_printing_rules (scope,ntn) pp_sy
1690 | None -> ())
1691
1692 let cache_notation o =
1693 load_notation_common false 1 o;
1694 open_notation o
1695
1696 let subst_notation (subst, nobj) =
1697 { nobj with notobj_interp = subst_interpretation subst nobj.notobj_interp; }
1698
1699 let classify_notation nobj =
1700 if nobj.notobj_local then Dispose else Substitute
1701
1702 let inNotation : notation_obj -> obj =
1703 declare_object {(default_object "NOTATION") with
1704 open_function = simple_open ~cat:notation_cat open_notation;
1705 cache_function = cache_notation;
1706 subst_function = subst_notation;
1707 load_function = load_notation;
1708 classify_function = classify_notation}
1709
1710 (**********************************************************************)
1711 (* Registration of interpretation scopes opening/closing *)
1712
1713 let cache_scope (local,op,sc) =
1714 if op then Notation.open_scope sc else Notation.close_scope sc
1715
1716 let subst_scope (subst,sc) = sc
1717
1718 let discharge_scope (local,_,_ as o) =
1719 if local then None else Some o
1720
1721 let classify_scope (local,_,_) =
1722 if local then Dispose else Substitute
1723
1724 let inScope : bool * bool * scope_name -> obj =
1725 declare_object {(default_object "SCOPE") with
1726 cache_function = cache_scope;
1727 open_function = simple_open ~cat:notation_cat cache_scope;
1728 subst_function = subst_scope;
1729 discharge_function = discharge_scope;
1730 classify_function = classify_scope }
1731
1732 let open_close_scope local ~to_open sc =
1733 Lib.add_leaf (inScope (local,to_open,normalize_scope sc))
1734
1735 (**********************************************************************)
1736
1737 let with_lib_stk_protection f x =
1738 let open Memprof_coq.Resource_bind in
1739 let freeze, unfreeze = Lib.Interp.(freeze, unfreeze) in
1740 let& () = Util.protect_state ~freeze ~unfreeze in
1741 f x
1742
1743 let with_syntax_protection f x =
1744 with_lib_stk_protection
1745 (Procq.with_grammar_rule_protection
1746 (with_notation_protection f)) x
1747
1748 (** **************************************************************** **)
1749 (** Recovering existing syntax **)
1750
1751 exception NoSyntaxRule
1752
1753 let recover_notation_syntax ntn =
1754 try
1755 let prec = Notation.level_of_notation ntn in
1756 let pa_typs = Notgram_ops.non_terminals_of_notation ntn in
1757 let pa_rule = try Some (Notgram_ops.grammar_of_notation ntn) with Not_found -> None in
1758 let pp_rule = try Some (find_generic_notation_printing_rule ntn) with Not_found -> None in
1759 {
1760 synext_level = prec;
1761 synext_nottyps = pa_typs;
1762 synext_notgram = pa_rule;
1763 synext_notprint = pp_rule;
1764 }
1765 with Not_found ->
1766 raise NoSyntaxRule
1767
1768 let recover_squash_syntax sy =
1769 let sq = recover_notation_syntax (InConstrEntry,"{ _ }") in
1770 match sq.synext_notgram with
1771 | Some gram -> sy :: gram
1772 | None -> raise NoSyntaxRule
1773
1774 (** **************************************************************** **)
1775 (** Main entry point for building parsing and printing rules **)
1776
1777 let make_pa_rule (typs,symbols) parsing_data =
1778 let { ntn_for_grammar; prec_for_grammar; typs_for_grammar; need_squash } = parsing_data in
1779 let assoc = recompute_assoc typs in
1780 let prod = make_production prec_for_grammar typs symbols in
1781 let sy = {
1782 notgram_level = prec_for_grammar;
1783 notgram_assoc = assoc;
1784 notgram_notation = ntn_for_grammar;
1785 notgram_prods = prod;
1786 notgram_typs = typs_for_grammar;
1787 } in
1788 (* By construction, the rule for "{ _ }" is declared, but we need to
1789 redeclare it because the file where it is declared needs not be open
1790 when the current file opens (especially in presence of -nois) *)
1791 if need_squash then recover_squash_syntax sy else [sy]
1792
1793 let make_pp_rule level (typs,symbols) fmt =
1794 match fmt with
1795 | None ->
1796 let hunks = make_hunks typs symbols level in
1797 if List.exists (function _,(UnpCut (PpBrk _) | UnpListMetaVar _) -> true | _ -> false) hunks then
1798 [UnpBox (PpHOVB 0,hunks)]
1799 else
1800 (* Optimization to work around what seems an ocaml Format bug (see Mantis #7804/#7807) *)
1801 List.map snd hunks (* drop locations which are dummy *)
1802 | Some fmt ->
1803 hunks_of_format (level, List.split typs) (symbols, fmt)
1804
1805 let make_parsing_rules main_data (sd : SynData.syn_data) =
1806 let open SynData in
1807 if main_data.onlyprinting then None
1808 else Some (make_pa_rule sd.pa_syntax_data sd.not_data)
1809
1810 (** **************************************************************** **)
1811 (** Main functions about notations **)
1812
1813 let make_generic_printing_rules reserved main_data ntn sd =
1814 let open SynData in
1815 let {notation_entry = custom; notation_level = level},_ = sd.level in
1816 let make_rule rule =
1817 {
1818 notation_printing_reserved = reserved;
1819 notation_printing_rules =
1820 {
1821 notation_printing_unparsing = rule;
1822 notation_printing_level = level;
1823 }
1824 }
1825 in
1826 try
1827 let rules = (Ppextend.find_generic_notation_printing_rule ntn) in
1828 match main_data.format with
1829 | None when not (has_implicit_format (snd sd.pp_syntax_data)) ->
1830 (* No intent to define a format, we reuse the existing generic rules *)
1831 Some rules
1832 | _ ->
1833 if not reserved && main_data.onlyprinting then
1834 (* No intent to define a generic format *)
1835 Some rules
1836 else
1837 let rules' = make_rule (make_pp_rule level sd.pp_syntax_data main_data.format) in
1838 let () = check_reserved_format ntn rules rules'.notation_printing_rules in
1839 Some rules'
1840 with Not_found ->
1841 Some (make_rule (make_pp_rule level sd.pp_syntax_data main_data.format))
1842
1843 let make_syntax_rules reserved main_data ntn sd =
1844 let open SynData in
1845 List.iter (fun f -> f ()) sd.msgs;
1846 (* Prepare the parsing and printing rules *)
1847 let pa_rules = make_parsing_rules main_data sd in
1848 let pp_rules = make_generic_printing_rules reserved main_data ntn sd in
1849 {
1850 synext_level = sd.level;
1851 synext_nottyps = List.map snd sd.subentries;
1852 synext_notgram = pa_rules;
1853 synext_notprint = pp_rules;
1854 }
1855
1856 (**********************************************************************)
1857 (* Main entry point for building specific printing rules *)
1858
1859 let make_specific_printing_rules etyps symbols level pp_rule format =
1860 match level with
1861 | None -> None
1862 | Some ({ notation_level = level},_) ->
1863 match format, pp_rule with
1864 | None, Some _ when not (has_implicit_format symbols) -> None
1865 | _ ->
1866 Some
1867 {
1868 notation_printing_unparsing = make_pp_rule level (etyps,symbols) format;
1869 notation_printing_level = level;
1870 }
1871
1872 (**********************************************************************)
1873 (* Miscellaneous *)
1874
1875 let warn_unused_interpretation =
1876 CWarnings.create ~name:"unused-notation" ~category:CWarnings.CoreCategories.parsing
1877 (fun b ->
1878 strbrk "interpretation is used neither for printing nor for parsing, " ++
1879 (if b then strbrk "the declaration could be replaced by \"Reserved Notation\"."
1880 else strbrk "the declaration could be removed."))
1881
1882 let make_use reserved onlyparse onlyprint =
1883 match onlyparse, onlyprint with
1884 | false, false -> Some ParsingAndPrinting
1885 | true, false -> Some OnlyParsing
1886 | false, true -> Some OnlyPrinting
1887 | true, true -> warn_unused_interpretation reserved; None
1888
1889 (**********************************************************************)
1890 (* Main functions about notations *)
1891
1892 let make_notation_interpretation ~local main_data notation_symbols ntn syntax_rules df env ?(impls=empty_internalization_env) c scope =
1893 let {recvars;mainvars;symbols} = notation_symbols in
1894 (* Recover types of variables and pa/pp rules; redeclare them if needed *)
1895 let level, i_typs, main_data, sy_pp_rules =
1896 match syntax_rules with
1897 | PrimTokenSyntax -> None, [], main_data, None
1898 | SpecificSyntax sy ->
1899 (* If the only printing flag has been explicitly requested, put it back *)
1900 let main_data = { main_data with onlyprinting = main_data.onlyprinting || (sy.synext_notgram = None && not main_data.onlyparsing) } in
1901 Some sy.synext_level, List.combine mainvars sy.synext_nottyps, main_data, sy.synext_notprint
1902 in
1903 (* Declare interpretation *)
1904 let sy_pp_rules = make_specific_printing_rules i_typs symbols level sy_pp_rules main_data.format in
1905 let path = (Lib.library_dp(), Lib.current_dirpath true) in
1906 let df' = ntn, (path,df) in
1907 let i_vars = make_internalization_vars recvars i_typs in
1908 let nenv = {
1909 ninterp_var_type = Id.Map.of_list i_vars;
1910 ninterp_rec_vars = Id.Map.of_list recvars;
1911 } in
1912 let (acvars, ac, reversibility) = interp_notation_constr env ~impls nenv c in
1913 let plevel = match level with Some (entry,l) -> (entry,l) | None (* numeral: irrelevant )*) -> (constr_lowest_level,[]) in
1914 let interp = make_interpretation_vars recvars acvars plevel i_typs in
1915 let map (x, _) = try Some (x, Id.Map.find x interp) with Not_found -> None in
1916 let vars = List.map_filter map i_vars in (* Order of elements is important here! *)
1917 let onlyparsing,coe = printability level i_typs vars main_data.onlyparsing reversibility ac in
1918 let main_data = { main_data with onlyparsing } in
1919 let use = make_use false onlyparsing main_data.onlyprinting in
1920 {
1921 notobj_local = local;
1922 notobj_scope = scope;
1923 notobj_use = use;
1924 notobj_interp = (vars, ac);
1925 notobj_coercion = coe;
1926 notobj_user_warns = main_data.user_warns;
1927 notobj_notation = df';
1928 notobj_specific_pp_rules = sy_pp_rules;
1929 }
1930
1931 (* Notations without interpretation (Reserved Notation) *)
1932
1933 let add_reserved_notation ~local ~infix ({CAst.loc;v=df},mods) =
1934 let (main_data,mods) = interp_non_syntax_modifiers ~reserved:true ~infix ~abbrev:false None mods in
1935 let mods = interp_modifiers main_data.entry mods in
1936 let notation_symbols, is_prim_token = analyze_notation_tokens ~onlyprinting:main_data.onlyprinting ~infix main_data.entry df in
1937 let notation_symbols = if infix then adjust_reserved_infix_notation notation_symbols else notation_symbols in
1938 let ntn = make_notation_key main_data.entry notation_symbols.symbols in
1939 if is_prim_token then user_err ?loc (str "Notations for numbers or strings are primitive and need not be reserved.");
1940 let sd = compute_syntax_data ~local main_data notation_symbols ntn mods in
1941 let synext = make_syntax_rules true main_data ntn sd in
1942 Lib.add_leaf (inSyntaxExtension(local,(ntn,synext)))
1943
1944 type notation_interpretation_decl =
1945 notation_declaration * notation_main_data * notation_symbols * notation * syntax_rules
1946
1947 (* Notations associated to a where clause *)
1948
1949 let prepare_where_notation ntn_decl =
1950 let
1951 { ntn_decl_string = { CAst.loc ; v = df };
1952 ntn_decl_interp = c;
1953 ntn_decl_modifiers = modifiers;
1954 ntn_decl_scope = sc;
1955 } = ntn_decl in
1956 let (main_data,mods) = interp_non_syntax_modifiers ~reserved:false ~infix:false ~abbrev:false None modifiers in
1957 match mods with
1958 | _::_ -> CErrors.user_err (str"Only modifiers not affecting parsing are supported here.")
1959 | [] ->
1960 let notation_symbols, is_prim_token = analyze_notation_tokens ~onlyprinting:main_data.onlyprinting ~infix:false main_data.entry df in
1961 let ntn = make_notation_key main_data.entry notation_symbols.symbols in
1962 let syntax_rules =
1963 if is_prim_token then PrimTokenSyntax else
1964 try SpecificSyntax (recover_notation_syntax ntn)
1965 with NoSyntaxRule ->
1966 user_err Pp.(str "Parsing rule for this notation has to be previously declared.") in
1967 (ntn_decl, main_data, notation_symbols, ntn, syntax_rules)
1968
1969 let add_notation_interpretation ~local env (ntn_decl, main_data, notation_symbols, ntn, syntax_rules) =
1970 let { ntn_decl_string = { CAst.loc ; v = df }; ntn_decl_interp = c; ntn_decl_scope = sc } = ntn_decl in
1971 let notation = make_notation_interpretation ~local main_data notation_symbols ntn syntax_rules df env c sc in
1972 Lib.add_leaf (inNotation notation);
1973 Dumpglob.dump_notation (CAst.make ?loc ntn) sc true
1974
1975 (* interpreting a where clause *)
1976 let set_notation_for_interpretation env impls (ntn_decl, main_data, notation_symbols, ntn, syntax_rules) =
1977 let { ntn_decl_string = { CAst.loc ; v = df }; ntn_decl_interp = c; ntn_decl_scope = sc } = ntn_decl in
1978 let notation = make_notation_interpretation ~local:true main_data notation_symbols ntn syntax_rules df env ~impls c sc in
1979 Lib.add_leaf (inNotation notation);
1980 Option.iter (fun sc -> Lib.add_leaf (inScope (false,true,sc))) sc
1981
1982 let build_notation_syntax ~local ~infix user_warns ntn_decl =
1983 let { ntn_decl_string = {CAst.loc;v=df}; ntn_decl_modifiers = modifiers; ntn_decl_interp = c } = ntn_decl in
1984 (* Extract the modifiers not affecting the parsing rule *)
1985 let (main_data,syntax_modifiers) = interp_non_syntax_modifiers ~reserved:false ~infix ~abbrev:false user_warns modifiers in
1986 (* Extract the modifiers not affecting the parsing rule *)
1987 let notation_symbols, is_prim_token = analyze_notation_tokens ~onlyprinting:main_data.onlyprinting ~infix main_data.entry df in
1988 (* Add variables on both sides if an infix notation *)
1989 let df, notation_symbols, c = if infix then adjust_infix_notation df notation_symbols c else df, notation_symbols, c in
1990 (* Build the canonical identifier of the syntactic part of the notation *)
1991 let ntn = make_notation_key main_data.entry notation_symbols.symbols in
1992 let syntax_rules = if is_prim_token then (check_no_syntax_modifiers_for_numeral syntax_modifiers; PrimTokenSyntax) else
1993 match syntax_modifiers with
1994 | [] ->
1995 (* No syntax data: try to rely on a previously declared rule *)
1996 (try SpecificSyntax (recover_notation_syntax ntn)
1997 with NoSyntaxRule ->
1998 (* Try to determine a default syntax rule *)
1999 let sd = compute_syntax_data ~local main_data notation_symbols ntn NotationMods.default in
2000 SpecificSyntax (make_syntax_rules false main_data ntn sd))
2001
2002 | _ ->
2003 let mods = interp_modifiers main_data.entry syntax_modifiers in
2004 let sd = compute_syntax_data ~local main_data notation_symbols ntn mods in
2005 SpecificSyntax (make_syntax_rules false main_data ntn sd)
2006 in
2007 main_data, notation_symbols, ntn, syntax_rules, c, df
2008
2009 let add_notation_syntax ~local ~infix user_warns ntn_decl =
2010 (* Build or rebuild the syntax rules *)
2011 let main_data, notation_symbols, ntn, syntax_rules, c, df = build_notation_syntax ~local ~infix user_warns ntn_decl in
2012 (* Declare syntax *)
2013 syntax_rules_iter (fun sy -> Lib.add_leaf (inSyntaxExtension (local,(ntn,sy)))) syntax_rules;
2014 let ntn_decl_string = CAst.make ?loc:ntn_decl.ntn_decl_string.CAst.loc df in
2015 let ntn_decl = { ntn_decl with ntn_decl_interp = c; ntn_decl_string } in
2016 ntn_decl, main_data, notation_symbols, ntn, syntax_rules
2017
2018 (** **************************************************************** **)
2019 (** Scopes, delimiters and classes bound to scopes **)
2020
2021 type scope_command =
2022 | ScopeDeclare
2023 | ScopeDelimAdd of string
2024 | ScopeDelimRemove
2025 | ScopeClasses of add_scope_where option * scope_class list
2026
2027 let load_scope_command_common silently_define_scope_if_undefined _ (local,scope,o) =
2028 let declare_scope_if_needed =
2029 if silently_define_scope_if_undefined then Notation.declare_scope
2030 else Notation.ensure_scope in
2031 match o with
2032 | ScopeDeclare -> Notation.declare_scope scope
2033 (* When the default shall be to require that a scope already exists *)
2034 (* the call to declare_scope_if_needed will have to be removed below *)
2035 | ScopeDelimAdd dlm -> declare_scope_if_needed scope
2036 | ScopeDelimRemove -> declare_scope_if_needed scope
2037 | ScopeClasses _ -> declare_scope_if_needed scope
2038
2039 let load_scope_command =
2040 load_scope_command_common true
2041
2042 let open_scope_command (noexport,scope,o) =
2043 match o with
2044 | ScopeDeclare -> ()
2045 | ScopeDelimAdd dlm -> Notation.declare_delimiters scope dlm
2046 | ScopeDelimRemove -> Notation.remove_delimiters scope
2047 | ScopeClasses (where, cl) ->
2048 let local = Lib.sections_are_opened () in
2049 List.iter (Notation.declare_scope_class local scope ?where) cl
2050
2051 let cache_scope_command o =
2052 load_scope_command_common false 1 o;
2053 open_scope_command o
2054
2055 let subst_scope_command (subst,(noexport,scope,o as x)) = match o with
2056 | ScopeClasses (where, cl) ->
2057 let env = Global.env () in
2058 let cl' = List.map_filter (subst_scope_class env subst) cl in
2059 let cl' =
2060 if List.for_all2eq (==) cl cl' then cl
2061 else cl' in
2062 noexport, scope, ScopeClasses (where, cl')
2063 | _ -> x
2064
2065 let classify_scope_command (noexport, _, _) =
2066 if noexport then Dispose else Substitute
2067
2068 let inScopeCommand : locality_flag * scope_name * scope_command -> obj =
2069 declare_object {(default_object "DELIMITERS") with
2070 cache_function = cache_scope_command;
2071 open_function = simple_open ~cat:notation_cat open_scope_command;
2072 load_function = load_scope_command;
2073 subst_function = subst_scope_command;
2074 classify_function = classify_scope_command}
2075
2076 let declare_scope local scope =
2077 Lib.add_leaf (inScopeCommand(local,scope,ScopeDeclare))
2078
2079 let add_delimiters local scope key =
2080 Lib.add_leaf (inScopeCommand(local,scope,ScopeDelimAdd key))
2081
2082 let remove_delimiters local scope =
2083 Lib.add_leaf (inScopeCommand(local,scope,ScopeDelimRemove))
2084
2085 let add_class_scope local scope where cl =
2086 Lib.add_leaf (inScopeCommand(local,scope,ScopeClasses (where, cl)))
2087
2088 let interp_abbreviation_modifiers modl =
2089 let mods, skipped = interp_non_syntax_modifiers ~reserved:false ~infix:false ~abbrev:true None modl in
2090 if skipped <> [] then
2091 (let modifier = List.hd skipped in
2092 user_err ?loc:modifier.CAst.loc (str "Abbreviations don't support " ++ Ppvernac.pr_syntax_modifier modifier));
2093 (mods.onlyparsing, mods.itemscopes)
2094
2095 let add_abbreviation ~local user_warns env ident (vars,c) modl =
2096 let (only_parsing, scopes) = interp_abbreviation_modifiers modl in
2097 let vars = List.map (fun v -> v, List.assoc_opt v scopes) vars in
2098 let acvars,pat,reversibility =
2099 match vars, intern_name_alias c with
2100 | [], Some(r,u) ->
2101 (* Check if abbreviation to a name and avoid early insertion of
2102 maximal implicit arguments *)
2103 Id.Map.empty, NRef(r, u), APrioriReversible
2104 | _ ->
2105 let fold accu (id,scope) = Id.Map.add id (NtnInternTypeAny scope) accu in
2106 let i_vars = List.fold_left fold Id.Map.empty vars in
2107 let nenv = {
2108 ninterp_var_type = i_vars;
2109 ninterp_rec_vars = Id.Map.empty;
2110 } in
2111 interp_notation_constr env nenv c
2112 in
2113 let level_arg = NumLevel 9 (* level of arguments of an application *) in
2114 let in_pat (id,_) = (id,ETConstr (Constrexpr.InConstrEntry,None,(level_arg,InternalProd))) in
2115 let level = (* not relevant *) (constr_lowest_level,[]) in
2116 let interp = make_interpretation_vars ~default_if_binding:AsAnyPattern [] acvars level (List.map in_pat vars) in
2117 let vars = List.map (fun (x,_) -> (x, Id.Map.find x interp)) vars in
2118 let onlyparsing = only_parsing || fst (printability None [] vars false reversibility pat) in
2119 Abbreviation.declare ~local user_warns ident ~onlyparsing (vars,pat)
2120
2121 (**********************************************************************)
2122 (* Activating/deactivating notations *)
2123
2124 let cache_notation_toggle (local,(on,all,pat)) =
2125 let env = Global.env () in
2126 let sigma = Evd.from_env env in
2127 let flags = PrintingFlags.Extern.current() in
2128 let flags = { flags with notations = false } in
2129 let prglob c = Printer.pr_glob_constr_env ~flags env sigma c in
2130 toggle_notations ~on ~all ~verbose:(not !Flags.quiet) prglob pat
2131
2132 let subst_notation_toggle (subst,(local,(on,all,pat))) =
2133 let {notation_entry_pattern; interp_rule_key_pattern; use_pattern;
2134 scope_pattern; interpretation_pattern} = pat in
2135 let interpretation_pattern = Option.map (subst_interpretation subst) interpretation_pattern in
2136 let interp_rule_key_pattern = interp_rule_key_pattern in
2137 (local,(on,all,{notation_entry_pattern; interp_rule_key_pattern; use_pattern;
2138 scope_pattern; interpretation_pattern}))
2139
2140 let classify_notation_toggle (local,_) =
2141 if local then Dispose else Substitute
2142
2143 let inNotationActivation : locality_flag * (bool * bool * notation_query_pattern) -> obj =
2144 declare_object {(default_object "NOTATION-TOGGLE") with
2145 cache_function = cache_notation_toggle;
2146 open_function = simple_open cache_notation_toggle;
2147 subst_function = subst_notation_toggle;
2148 classify_function = classify_notation_toggle}
2149
2150 let declare_notation_toggle local ~on ~all s =
2151 Lib.add_leaf (inNotationActivation (local,(on,all,s)))
2152
2153 (** **************************************************************** **)
2154 (** Declaration of custom entries **)
2155
2156 let load_custom_entry i ((sp,kn),local) =
2157 Nametab.CustomEntries.push (Until i) sp kn;
2158 add_custom_compat kn;
2159 Egramrocq.create_custom_entry kn;
2160 let () = if local then
2161 custom_entry_locality := CustomName.Set.add kn !custom_entry_locality
2162 in
2163 ()
2164
2165 let import_custom_entry i ((sp,kn),_) =
2166 Nametab.CustomEntries.push (Exactly i) sp kn
2167
2168 let cache_custom_entry o = load_custom_entry 1 o
2169
2170 let subst_custom_entry (subst,x) = x
2171
2172 let classify_custom_entry local =
2173 if local then Dispose else Substitute
2174
2175 let inCustomEntry : Id.t -> locality_flag -> obj =
2176 declare_named_object {(default_object "CUSTOM-ENTRIES") with
2177 object_stage = Summary.Stage.Synterp;
2178 cache_function = cache_custom_entry;
2179 load_function = load_custom_entry;
2180 open_function = filtered_open import_custom_entry;
2181 subst_function = subst_custom_entry;
2182 classify_function = classify_custom_entry}
2183
2184 let declare_custom_entry local s =
2185 let () = if List.mem (Id.to_string s) ["constr";"pattern";"ident";"global";"binder";"bigint"] then
2186 user_err Pp.(quote (Id.print s) ++ str " is a reserved entry name.")
2187 in
2188 let () =
2189 if Nametab.CustomEntries.exists (Lib.make_path s) then
2190 user_err Pp.(Id.print s ++ str " already exists.")
2191 in
2192 Lib.add_leaf (inCustomEntry s local)