forked from coq/coq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metasyntax.ml
2002 lines (1764 loc) · 82.5 KB
/
metasyntax.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * Copyright INRIA, CNRS and contributors *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
open Pp
open CErrors
open Util
open Names
open Constrexpr
open Constrexpr_ops
open Vernacexpr
open Notation_term
open Notationextern
open Notation_gram
open Notation_ops
open Ppextend
open Extend
open Libobject
open Constrintern
open Libnames
open Notation
open Nameops
(** **************************************************************** **)
(** Printing grammar entries **)
let entry_buf = Buffer.create 64
let pr_entry e =
let () = Buffer.clear entry_buf in
let ft = Format.formatter_of_buffer entry_buf in
let () = Pcoq.Entry.print ft e in
str (Buffer.contents entry_buf)
let error_unknown_entry ?loc name =
user_err ?loc Pp.(str "Unknown or unprintable grammar entry " ++ str name ++ str".")
let pr_registered_grammar name =
let gram = Pcoq.find_grammars_by_name name in
match gram with
| [] -> error_unknown_entry name
| entries ->
let pr_one (Pcoq.Entry.Any e) =
str "Entry " ++ str (Pcoq.Entry.name e) ++ str " is" ++ fnl () ++
pr_entry e
in
prlist pr_one entries
let pr_grammar_subset grammar =
let pp = String.Map.mapi (fun name l -> match l with
| [] -> assert false
| entries ->
str "Entry " ++ str name ++ str " is" ++ fnl() ++
prlist_with_sep (fun () -> str "or" ++ fnl())
(fun (Pcoq.Entry.Any e) -> pr_entry e)
entries)
grammar
in
let pp = CString.Map.bindings pp in
prlist_with_sep fnl (fun (_,pp) -> pp) pp
let is_known = let open Pcoq.Entry in function
| "constr" | "term" | "binder_constr" ->
Some [ Any Pcoq.Constr.constr;
Any Pcoq.Constr.lconstr;
Any Pcoq.Constr.binder_constr;
Any Pcoq.Constr.term;
]
| "vernac" ->
Some Pvernac.Vernac_.[
Any vernac_control;
(* main_entry="vernac", included not because it's interesting but because otherwise it's shadowed by the "vernac" group defined here *)
Any main_entry;
Any command;
Any syntax;
Any gallina;
Any gallina_ext;
]
| name ->
let gram = Pcoq.find_grammars_by_name name in
match gram with
| [] -> None
| entries -> Some entries
let full_grammar () = Pcoq.Entry.accumulate_in Pvernac.Vernac_.vernac_control
let same_entry (Pcoq.Entry.Any e) (Pcoq.Entry.Any e') = (Obj.magic e) == (Obj.magic e')
let pr_grammar = function
| [] ->
let grammar = full_grammar () in
pr_grammar_subset grammar
| names ->
let known, other = List.fold_left (fun (known,other) name ->
match is_known name with
| Some v -> v @ known, other
| None -> known, name::other)
([],[])
names
in
let grammar = if List.is_empty other then String.Map.empty else full_grammar () in
let () = List.iter (fun name ->
if not (String.Map.mem name grammar)
then error_unknown_entry name)
other
in
let other = String.Set.of_list other in
let grammar = String.Map.filter (fun name _ -> String.Set.mem name other) grammar in
let grammar = List.fold_left (fun grammar (Pcoq.Entry.Any e as any) ->
String.Map.update (Pcoq.Entry.name e) (function
| None -> Some [any]
| Some vl as v ->
if List.mem_f same_entry any vl
then v else Some (any :: vl))
grammar)
grammar known
in
pr_grammar_subset grammar
let pr_custom_grammar name = pr_registered_grammar ("custom:"^name)
let pr_keywords () =
Pp.prlist_with_sep Pp.fnl Pp.str (CString.Set.elements (CLexer.keywords (Pcoq.get_keyword_state())))
(** **************************************************************** **)
(** Parse a format (every terminal starting with a letter or a single
quote (except a single quote alone) must be quoted) **)
let parse_format ({CAst.loc;v=str} : lstring) =
let len = String.length str in
(* TODO: update the line of the location when the string contains newlines *)
let make_loc i j = Option.map (Loc.shift_loc (i+1) (j-len)) loc in
let push_token loc a = function
| (i,cur)::l -> (i,(loc,a)::cur)::l
| [] -> assert false in
let push_white i n l =
if Int.equal n 0 then l else push_token (make_loc i (i+n)) (UnpTerminal (String.make n ' ')) l in
let close_box start stop b = function
| (_,a)::(_::_ as l) -> push_token (make_loc start stop) (UnpBox (b,a)) l
| [a] -> user_err ?loc:(make_loc start stop) Pp.(str "Non terminated box in format.")
| [] -> assert false in
let close_quotation start i =
if i < len && str.[i] == '\'' then
if (Int.equal (i+1) len || str.[i+1] == ' ')
then i+1
else user_err ?loc:(make_loc (i+1) (i+1)) Pp.(str "Space expected after quoted expression.")
else
user_err ?loc:(make_loc start (i-1)) Pp.(str "Beginning of quoted expression expected to be ended by a quote.") in
let rec spaces n i =
if i < len && str.[i] == ' ' then spaces (n+1) (i+1)
else n in
let rec nonspaces quoted n i =
if i < len && str.[i] != ' ' then
if str.[i] == '\'' && quoted &&
(i+1 >= len || str.[i+1] == ' ')
then if Int.equal n 0 then user_err ?loc:(make_loc (i-1) i) Pp.(str "Empty quoted token.") else n
else nonspaces quoted (n+1) (i+1)
else
if quoted then user_err ?loc:(make_loc i i) Pp.(str "Spaces are not allowed in (quoted) symbols.")
else n in
let rec parse_non_format i =
let n = nonspaces false 0 i in
push_token (make_loc i (i+n-1)) (UnpTerminal (String.sub str i n)) (parse_token 1 (i+n))
and parse_quoted n k i =
if i < len then match str.[i] with
(* Parse " // " *)
| '/' when i+1 < len && str.[i+1] == '/' ->
(* We discard the useless n spaces... *)
push_token (make_loc (i-n) (i+1)) (UnpCut PpFnl)
(parse_token 1 (close_quotation i (i+2)))
(* Parse " .. / .. " *)
| '/' when i+1 < len ->
let p = spaces 0 (i+1) in
push_token (make_loc (i-n) (i+p)) (UnpCut (PpBrk (n,p)))
(parse_token 1 (close_quotation i (i+p+1)))
| c ->
(* The spaces are real spaces *)
push_white (i-n-1-k) n (match c with
| '[' ->
if i+1 < len then match str.[i+1] with
(* Parse " [h .. ", *)
| 'h' when i+1 <= len && str.[i+2] == 'v' ->
(parse_box i (fun n -> PpHVB n) (i+3))
(* Parse " [v .. ", *)
| 'v' ->
parse_box i (fun n -> PpVB n) (i+2)
(* Parse " [ .. ", *)
| ' ' | '\'' ->
parse_box i (fun n -> PpHOVB n) (i+1)
| _ -> user_err ?loc:(make_loc i i) Pp.(str "\"v\", \"hv\", \" \" expected after \"[\" in format.")
else user_err ?loc:(make_loc i i) Pp.(str "\"v\", \"hv\" or \" \" expected after \"[\" in format.")
(* Parse "]" *)
| ']' ->
((i,[]) :: parse_token 1 (close_quotation i (i+1)))
(* Parse a non formatting token *)
| c ->
let n = nonspaces true 0 i in
push_token (make_loc i (i+n-1)) (UnpTerminal (String.sub str (i-1) (n+2)))
(parse_token 1 (close_quotation i (i+n))))
else
if Int.equal n 0 then []
else user_err ?loc:(make_loc (len-n) len) Pp.(str "Ending spaces non part of a format annotation.")
and parse_box start box i =
let n = spaces 0 i in
close_box start (i+n-1) (box n) (parse_token 1 (close_quotation i (i+n)))
and parse_token k i =
let n = spaces 0 i in
let i = i+n in
if i < len then match str.[i] with
(* Parse a ' *)
| '\'' when i+1 >= len || str.[i+1] == ' ' ->
push_white (i-n) (n-k) (push_token (make_loc i (i+1)) (UnpTerminal "'") (parse_token 1 (i+1)))
(* Parse the beginning of a quoted expression *)
| '\'' ->
parse_quoted (n-k) k (i+1)
(* Otherwise *)
| _ ->
push_white (i-n) (n-k) (parse_non_format i)
else push_white (i-n) n [(len,[])]
in
if not (String.is_empty str) then
match parse_token 0 0 with
| [_,l] -> l
| (i,_)::_ -> user_err ?loc:(make_loc i i) Pp.(str "Box closed without being opened.")
| [] -> assert false
else
[]
(** **************************************************************** **)
(** Analyzing notations **)
(* Find non-terminal tokens of notation *)
(* To protect alphabetic tokens and quotes from being seen as variables *)
let quote_notation_token x =
let n = String.length x in
let norm = CLexer.is_ident x in
if (n > 0 && norm) || (n > 2 && x.[0] == '\'') then "'"^x^"'"
else x
let analyze_notation_tokens ~onlyprinting ~infix entry df =
let df = if infix then quote_notation_token df else df in
let { recvars; mainvars; symbols } as res = decompose_raw_notation df in
(* don't check for nonlinearity if printing only, see Bug 5526 *)
(if not onlyprinting then
match List.duplicates Id.equal (mainvars @ List.map snd recvars) with
| id :: _ ->
user_err
(str "Variable " ++ Id.print id ++ str " occurs more than once.")
| _ -> ());
let is_prim_token = is_prim_token_constant_in_constr (entry, symbols) in
res, is_prim_token
let adjust_symbols vars notation_symbols =
let x = Namegen.next_ident_away (Id.of_string "x") vars in
let y = Namegen.next_ident_away (Id.of_string "y") (Id.Set.add x vars) in
let notation_symbols = {
recvars = notation_symbols.recvars; mainvars = x::notation_symbols.mainvars@[y];
symbols = NonTerminal x :: notation_symbols.symbols @ [NonTerminal y];
} in
x, y, notation_symbols
let adjust_reserved_infix_notation notation_symbols =
let vars = Id.Set.of_list (List.map_filter (function NonTerminal x -> Some x | _ -> None) notation_symbols.symbols) in
let _, _, notation_symbols = adjust_symbols vars notation_symbols in
notation_symbols
let adjust_infix_notation df notation_symbols c =
let vars = names_of_constr_expr c in
let x, y, notation_symbols = adjust_symbols vars notation_symbols in
let df = Id.to_string x ^ " " ^ df ^ " " ^ Id.to_string y in
let inject_var x = CAst.make @@ CRef (qualid_of_ident x,None) in
let metas = [inject_var x; inject_var y] in
let c = mkAppC (c,metas) in
df, notation_symbols, c
let warn_unexpected_primitive_token_modifier =
CWarnings.create ~name:"primitive-token-modifier" ~category:CWarnings.CoreCategories.parsing
(fun () -> str "Notations for numbers or strings are primitive; skipping this modifier.")
let check_no_syntax_modifiers_for_numeral = function
| [] -> ()
| l -> List.iter (function {CAst.loc} -> warn_unexpected_primitive_token_modifier ?loc ()) l
let error_not_same_scope x y =
user_err
(str "Variables " ++ Id.print x ++ str " and " ++ Id.print y ++ str " must be in the same scope.")
(** **************************************************************** **)
(** Build pretty-printing rules **)
let pr_notation_entry = function
| InConstrEntry -> str "constr"
| InCustomEntry s -> str "custom " ++ str s
let side = function
| BorderProd (b,_) -> Some b
| _ -> None
let precedence_of_position_and_level from_level = function
| NumLevel n, BorderProd (b,Some a) ->
let prec =
let open Gramlib.Gramext in
match a, b with
| RightA, Left -> LevelLt n
| RightA, Right -> LevelLe n
| LeftA, Left -> LevelLe n
| LeftA, Right -> LevelLt n
| NonA, _ -> LevelLt n in
{notation_subentry = InConstrEntry; notation_relative_level = prec; notation_position = Some b}
| NumLevel n, b -> {notation_subentry = InConstrEntry; notation_relative_level = LevelLe n; notation_position = side b}
| NextLevel, b -> {notation_subentry = InConstrEntry; notation_relative_level = LevelLt from_level; notation_position = side b}
| DefaultLevel, b -> {notation_subentry = InConstrEntry; notation_relative_level = LevelSome; notation_position = side b}
(** Computing precedences of non-terminals for parsing *)
let precedence_of_entry_type { notation_entry = from_custom; notation_level = from_level } = function
| ETConstr (custom,_,x) when notation_entry_eq custom from_custom ->
(precedence_of_position_and_level from_level x).notation_relative_level
| ETConstr (custom,_,(NumLevel n,_)) -> LevelLe n
| ETConstr (custom,_,(NextLevel,_)) ->
user_err (strbrk "\"next level\" is only for sub-expressions in the same entry as where the notation is (" ++
quote (pr_notation_entry custom) ++ strbrk " is different from " ++
quote (pr_notation_entry from_custom) ++ str ").")
| ETPattern (_,n) -> let n = match n with None -> 0 | Some n -> n in LevelLe n
| _ -> LevelSome (* should not matter *)
let pattern_entry_level = function None -> 0 | Some n -> n
(** Computing precedences for future insertion of parentheses at
the time of printing using hard-wired constr levels *)
let unparsing_precedence_of_entry_type from_level = function
| ETConstr (InConstrEntry,_,x) ->
(* Possible insertion of parentheses at printing time to deal
with precedence in a constr entry is managed using [prec_less]
in [ppconstr.ml] *)
precedence_of_position_and_level from_level x
| ETConstr (custom,_,(_,b)) ->
(* Precedence of printing for a custom entry is managed using
explicit insertion of entry coercions at the time of building
a [constr_expr] *)
{notation_subentry = custom; notation_relative_level = LevelSome; notation_position = side b}
| ETPattern (_,n) -> (* in constr *)
{notation_subentry = InConstrEntry; notation_relative_level = LevelLe (pattern_entry_level n); notation_position = None}
| _ -> (* should not matter *)
{notation_subentry = InConstrEntry; notation_relative_level = LevelSome; notation_position = None}
(** Utilities for building default printing rules *)
(* Some breaking examples *)
(* "x = y" : "x /1 = y" (breaks before any symbol) *)
(* "x =S y" : "x /1 =S /1 y" (protect from confusion; each side for symmetry)*)
(* "+ {" : "+ {" may breaks reversibility without space but oth. not elegant *)
(* "x y" : "x spc y" *)
(* "{ x } + { y }" : "{ x } / + { y }" *)
(* "< x , y > { z , t }" : "< x , / y > / { z , / t }" *)
let starts_with_left_bracket s =
let l = String.length s in not (Int.equal l 0) &&
(s.[0] == '{' || s.[0] == '[' || s.[0] == '(')
let ends_with_right_bracket s =
let l = String.length s in not (Int.equal l 0) &&
(s.[l-1] == '}' || s.[l-1] == ']' || s.[l-1] == ')')
let is_left_bracket s =
starts_with_left_bracket s && not (ends_with_right_bracket s)
let is_right_bracket s =
not (starts_with_left_bracket s) && ends_with_right_bracket s
let is_comma s =
let l = String.length s in not (Int.equal l 0) &&
(s.[0] == ',' || s.[0] == ';')
let is_operator s =
let l = String.length s in not (Int.equal l 0) &&
(s.[0] == '+' || s.[0] == '*' || s.[0] == '=' ||
s.[0] == '-' || s.[0] == '/' || s.[0] == '<' || s.[0] == '>' ||
s.[0] == '@' || s.[0] == '\\' || s.[0] == '&' || s.[0] == '~' || s.[0] == '$')
let is_non_terminal = function
| NonTerminal _ | SProdList _ -> true
| _ -> false
let is_next_non_terminal b = function
| [] -> b
| pr :: _ -> is_non_terminal pr
let is_next_terminal = function Terminal _ :: _ -> true | _ -> false
let is_next_break = function Break _ :: _ -> true | _ -> false
let add_break n l = (None,UnpCut (PpBrk(n,0))) :: l
let add_break_if_none n b = function
| (_,UnpCut (PpBrk _)) :: _ as l -> l
| [] when not b -> []
| l -> (None,UnpCut (PpBrk(n,0))) :: l
let check_open_binder isopen sl m =
let pr_token = function
| Terminal s -> str s
| Break n -> str "␣"
| _ -> assert false
in
if isopen && not (List.is_empty sl) then
user_err (str "as " ++ Id.print m ++
str " is a non-closed binder, no such \"" ++
prlist_with_sep spc pr_token sl
++ strbrk "\" is allowed to occur.")
let unparsing_metavar i from typs =
let x = List.nth typs (i-1) in
let subentry = unparsing_precedence_of_entry_type from x in
match x with
| ETConstr _ | ETGlobal | ETBigint ->
UnpMetaVar subentry
| ETPattern _ | ETName | ETIdent ->
UnpBinderMetaVar (subentry,NotQuotedPattern)
| ETBinder isopen ->
UnpBinderMetaVar (subentry,QuotedPattern)
(** Heuristics for building default printing rules *)
let index_id id l = List.index Id.equal id l
let make_hunks etyps symbols from_level =
let vars,typs = List.split etyps in
let rec make b = function
| NonTerminal m :: prods ->
let i = index_id m vars in
let u = unparsing_metavar i from_level typs in
if is_next_non_terminal b prods then
(None, u) :: add_break_if_none 1 b (make b prods)
else
(None, u) :: make_with_space b prods
| Terminal s :: prods
when (* true to simulate presence of non-terminal *) b || List.exists is_non_terminal prods ->
if (is_comma s || is_operator s) then
(* Always a breakable space after comma or separator *)
(None, UnpTerminal s) :: add_break_if_none 1 b (make b prods)
else if is_right_bracket s && is_next_terminal prods then
(* Always no space after right bracked, but possibly a break *)
(None, UnpTerminal s) :: add_break_if_none 0 b (make b prods)
else if is_left_bracket s && is_next_non_terminal b prods then
(None, UnpTerminal s) :: make b prods
else if not (is_next_break prods) then
(* Add rigid space, no break, unless user asked for something *)
(None, UnpTerminal (s^" ")) :: make b prods
else
(* Rely on user spaces *)
(None, UnpTerminal s) :: make b prods
| Terminal s :: prods ->
(* Separate but do not cut a trailing sequence of terminal *)
(match prods with
| Terminal _ :: _ -> (None,UnpTerminal (s^" ")) :: make b prods
| _ -> (None,UnpTerminal s) :: make b prods)
| Break n :: prods ->
add_break n (make b prods)
| SProdList (m,sl) :: prods ->
let i = index_id m vars in
let typ = List.nth typs (i-1) in
let subentry = unparsing_precedence_of_entry_type from_level typ in
let sl' =
(* If no separator: add a break *)
if List.is_empty sl then add_break 1 []
(* We add NonTerminal for simulation but remove it afterwards *)
else make true sl in
let hunk = match typ with
| ETConstr _ -> UnpListMetaVar (subentry,List.map snd sl')
| ETBinder isopen ->
check_open_binder isopen sl m;
UnpBinderListMetaVar (isopen,true,List.map snd sl')
| ETName | ETIdent ->
UnpBinderListMetaVar (false,true,List.map snd sl')
| ETPattern _ ->
UnpBinderListMetaVar (false,false,List.map snd sl')
| _ -> assert false in
(None, hunk) :: make_with_space b prods
| [] -> []
and make_with_space b prods =
match prods with
| Terminal s' :: prods'->
if is_operator s' then
(* A rigid space before operator and a breakable after *)
(None,UnpTerminal (" "^s')) :: add_break_if_none 1 b (make b prods')
else if is_comma s' then
(* No space whatsoever before comma *)
make b prods
else if is_right_bracket s' then
make b prods
else
(* A breakable space between any other two terminals *)
add_break_if_none 1 b (make b prods)
| (NonTerminal _ | SProdList _) :: _ ->
(* A breakable space before a non-terminal *)
add_break_if_none 1 b (make b prods)
| Break _ :: _ ->
(* Rely on user wish *)
make b prods
| [] -> []
in make false symbols
(** Build default printing rules from explicit format *)
let error_format ?loc () = user_err ?loc Pp.(str "The format does not match the notation.")
let warn_format_break =
CWarnings.create ~name:"notation-both-format-and-spaces" ~category:CWarnings.CoreCategories.parsing
(fun () ->
strbrk "Discarding format implicitly indicated by multiple spaces in notation because an explicit format modifier is given.")
let has_ldots l =
List.exists (function (_,UnpTerminal s) -> String.equal s (Id.to_string Notation_ops.ldots_var) | _ -> false) l
let rec split_format_at_ldots hd = function
| (loc,UnpTerminal s) :: fmt when String.equal s (Id.to_string Notation_ops.ldots_var) -> loc, List.rev hd, fmt
| u :: fmt ->
check_no_ldots_in_box u;
split_format_at_ldots (u::hd) fmt
| [] -> raise_notrace Exit
and check_no_ldots_in_box = function
| (_,UnpBox (_,fmt)) ->
(try
let loc,_,_ = split_format_at_ldots [] fmt in
user_err ?loc Pp.(str ("The special symbol \"..\" must occur at the same formatting depth than the variables of which it is the ellipse."))
with Exit -> ())
| _ -> ()
let error_not_same ?loc () =
user_err ?loc Pp.(str "The format is not the same on the right- and left-hand sides of the special token \"..\".")
let find_prod_list_loc sfmt fmt =
(* [fmt] is some [UnpTerminal x :: sfmt @ UnpTerminal ".." :: sfmt @ UnpTerminal y :: rest] *)
if List.is_empty sfmt then
(* No separators; we highlight the sequence "x .." *)
Loc.merge_opt (fst (List.hd fmt)) (fst (List.hd (List.tl fmt)))
else
(* A separator; we highlight the separating sequence *)
Loc.merge_opt (fst (List.hd sfmt)) (fst (List.last sfmt))
let is_blank s =
let n = String.length s in
let rec aux i s = i >= n || s.[i] = ' ' && aux (i+1) s in
aux 0 s
let is_formatting = function
| (_,UnpCut _) -> true
| (_,UnpTerminal s) -> is_blank s
| _ -> false
let rec is_var_in_recursive_format = function
| (_,UnpTerminal s) when not (is_blank s) -> true
| (loc,UnpBox (b,l)) ->
(match List.filter (fun a -> not (is_formatting a)) l with
| [a] -> is_var_in_recursive_format a
| _ -> error_not_same ?loc ())
| _ -> false
let rec check_eq_var_upto_name = function
| (_,UnpTerminal s1), (_,UnpTerminal s2) when not (is_blank s1 && is_blank s2) || s1 = s2 -> ()
| (_,UnpBox (b1,l1)), (_,UnpBox (b2,l2)) when b1 = b2 -> List.iter check_eq_var_upto_name (List.combine l1 l2)
| (_,UnpCut b1), (_,UnpCut b2) when b1 = b2 -> ()
| _, (loc,_) -> error_not_same ?loc ()
let skip_var_in_recursive_format = function
| a :: sl when is_var_in_recursive_format a -> a, sl
| (loc,_) :: _ -> error_not_same ?loc ()
| [] -> assert false
let read_recursive_format sl fmt =
(* Turn [[UnpTerminal s :: some-list @ UnpTerminal ".." :: same-some-list @ UnpTerminal s' :: rest] *)
(* into [(some-list,rest)] *)
let get_head fmt =
let var,sl = skip_var_in_recursive_format fmt in
try var, split_format_at_ldots [] sl
with Exit -> error_not_same ?loc:(fst (List.last (if sl = [] then fmt else sl))) () in
let rec get_tail = function
| (loc,a) :: sepfmt, (_,b) :: fmt when (=) a b -> get_tail (sepfmt, fmt) (* FIXME *)
| [], tail -> skip_var_in_recursive_format tail
| (loc,_) :: _, ([] | (_,UnpTerminal _) :: _)-> error_not_same ?loc ()
| _, (loc,_)::_ -> error_not_same ?loc () in
let var1, (loc, slfmt, fmt) = get_head fmt in
let var2, res = get_tail (slfmt, fmt) in
check_eq_var_upto_name (var1,var2);
(* To do, though not so important: check that the names match
the names in the notation *)
slfmt, res
let hunks_of_format (from_level,(vars,typs)) symfmt =
let rec aux = function
| symbs, (_,(UnpTerminal s' as u)) :: fmt
when String.equal s' (String.make (String.length s') ' ') ->
let symbs, l = aux (symbs,fmt) in symbs, u :: l
| Terminal s :: symbs, (_,UnpTerminal s') :: fmt
when String.equal s (String.drop_simple_quotes s') ->
let symbs, l = aux (symbs,fmt) in symbs, UnpTerminal s :: l
| NonTerminal s :: symbs, (_,UnpTerminal s') :: fmt when Id.equal s (Id.of_string s') ->
let i = index_id s vars in
let symbs, l = aux (symbs,fmt) in symbs, unparsing_metavar i from_level typs :: l
| symbs, (_,(UnpCut _ as u)) :: fmt ->
let symbs, l = aux (symbs,fmt) in symbs, u :: l
| SProdList (m,sl) :: symbs, fmt when has_ldots fmt ->
let i = index_id m vars in
let typ = List.nth typs (i-1) in
let subentry = unparsing_precedence_of_entry_type from_level typ in
let loc_slfmt,rfmt = read_recursive_format sl fmt in
let sl, slfmt = aux (sl,loc_slfmt) in
if not (List.is_empty sl) then error_format ?loc:(find_prod_list_loc loc_slfmt fmt) ();
let symbs, l = aux (symbs,rfmt) in
let hunk = match typ with
| ETConstr _ -> UnpListMetaVar (subentry,slfmt)
| ETBinder isopen ->
check_open_binder isopen sl m;
UnpBinderListMetaVar (isopen,true,slfmt)
| ETName | ETIdent ->
UnpBinderListMetaVar (false,true,slfmt)
| ETPattern _ ->
UnpBinderListMetaVar (false,false,slfmt)
| _ -> assert false in
symbs, hunk :: l
| symbs, (_,UnpBox (a,b)) :: fmt ->
let symbs', b' = aux (symbs,b) in
let symbs', l = aux (symbs',fmt) in
symbs', UnpBox (a,List.map (fun x -> (None,x)) b') :: l
| symbs, [] -> symbs, []
| Break _ :: symbs, fmt -> warn_format_break (); aux (symbs,fmt)
| _, fmt -> error_format ?loc:(fst (List.hd fmt)) ()
in
match aux symfmt with
| [], l -> l
| _ -> error_format ()
(** **************************************************************** **)
(** Build parsing rules **)
let assoc_of_type from n (_,typ) = precedence_of_entry_type {notation_entry = from; notation_level = n} typ
let is_not_small_constr = function
ETProdConstr _ -> true
| _ -> false
let distribute a ll = List.map (fun l -> a @ l) ll
(* Expand LIST1(t,sep);sep;t;...;t (with the trailing pattern
occurring p times, possibly p=0) into the combination of
t;sep;t;...;t;sep;t (p+1 times)
t;sep;t;...;t;sep;t;sep;t (p+2 times)
...
t;sep;t;...;t;sep;t;...;t;sep;t (p+n times)
t;sep;t;...;t;sep;t;...;t;sep;t;LIST1(t,sep) *)
let expand_list_rule s typ tkl x n p ll =
let camlp5_message_name = Some (add_suffix x ("_"^string_of_int n)) in
let main = GramConstrNonTerminal (ETProdConstr (s,typ), camlp5_message_name) in
let tks = List.map (fun (kw,s) -> GramConstrTerminal (kw, s)) tkl in
let rec aux i hds ll =
if i < p then aux (i+1) (main :: tks @ hds) ll
else if Int.equal i (p+n) then
let hds =
GramConstrListMark (p+n,true,p) :: hds
@ [GramConstrNonTerminal (ETProdConstrList (s, typ,tkl), Some x)] in
distribute hds ll
else
distribute (GramConstrListMark (i+1,false,p) :: hds @ [main]) ll @
aux (i+1) (main :: tks @ hds) ll in
aux 0 [] ll
let is_constr_typ (s,lev) x etyps =
match List.assoc x etyps with
(* TODO: factorize these rules with the ones computing the effective
sublevel sent to camlp5, so as to include the case of
DefaultLevel which are valid *)
| ETConstr (s',_,(lev',InternalProd | (NumLevel _ | NextLevel as lev'), _)) ->
notation_entry_eq s s' && production_level_eq lev lev'
| _ -> false
let include_possible_similar_trailing_pattern typ etyps sl l =
let rec aux n = function
| Terminal s :: sl, Terminal s'::l' when s = s' -> aux n (sl,l')
| [], NonTerminal x ::l' when is_constr_typ typ x etyps -> try_aux n l'
| Break _ :: sl, l -> aux n (sl,l)
| sl, Break _ :: l -> aux n (sl,l)
| _ -> raise_notrace Exit
and try_aux n l =
try aux (n+1) (sl,l)
with Exit -> n,l in
try_aux 0 l
let prod_entry_type = function
| ETIdent -> ETProdIdent
| ETName -> ETProdName
| ETGlobal -> ETProdGlobal
| ETBigint -> ETProdBigint
| ETBinder o -> ETProdOneBinder o
| ETConstr (s,_,p) -> ETProdConstr (s,p)
| ETPattern (_,n) -> ETProdPattern (pattern_entry_level n)
let keyword_needed need s =
(* Ensure that IDENT articulation terminal symbols are keywords *)
match Pcoq.terminal s with
| Tok.PIDENT (Some k) ->
if need then
Flags.if_verbose Feedback.msg_info (str "Identifier '" ++ str k ++ str "' now a keyword");
need
| _ ->
match NumTok.Unsigned.parse_string s with
| Some n ->
if need then
Flags.if_verbose Feedback.msg_info (str "Number '" ++ NumTok.Unsigned.print n ++ str "' now a keyword");
need
| None ->
match String.unquote_coq_string s with
| Some _ ->
if need then
Flags.if_verbose Feedback.msg_info (str "String '" ++ str s ++ str "' now a keyword");
need
| _ -> true
let make_production ({notation_level = lev}, _) etyps symbols =
let rec aux need = function
| [] -> [[]]
| NonTerminal m :: l ->
let typ = prod_entry_type (List.assoc m etyps) in
distribute [GramConstrNonTerminal (typ, Some m)] (aux (is_not_small_constr typ) l)
| Terminal s :: l ->
let keyword = keyword_needed need s in
distribute [GramConstrTerminal (keyword,s)] (aux false l)
| Break _ :: l ->
aux need l
| SProdList (x,sl) :: l ->
let tkl = List.flatten
(List.map (function Terminal s -> [s]
| Break _ -> []
| _ -> anomaly (Pp.str "Found a non terminal token in recursive notation separator.")) sl) in
let tkl = List.map_i (fun i x -> let need = (i=0) in (keyword_needed need x, x)) 0 tkl in
match List.assoc x etyps with
| ETConstr (s,_,(lev,_ as typ)) ->
let p,l' = include_possible_similar_trailing_pattern (s,lev) etyps sl l in
expand_list_rule s typ tkl x 1 p (aux true l')
| ETBinder o ->
check_open_binder o sl x;
let typ = if o then (assert (tkl = []); ETBinderOpen) else ETBinderClosed (None,tkl) in
distribute
[GramConstrNonTerminal (ETProdBinderList typ, Some x)] (aux false l)
| ETIdent ->
distribute
[GramConstrNonTerminal (ETProdBinderList (ETBinderClosed (Some ETProdIdent,tkl)), Some x)] (aux false l)
| ETName ->
distribute
[GramConstrNonTerminal (ETProdBinderList (ETBinderClosed (Some ETProdName,tkl)), Some x)] (aux false l)
| ETPattern (st,n) ->
distribute
[GramConstrNonTerminal (ETProdBinderList (ETBinderClosed (Some (ETProdPattern (pattern_entry_level n)),tkl)), Some x)] (aux false l)
| _ ->
user_err Pp.(str "Components of recursive patterns in notation must be terms or binders.") in
let need = (* a leading ident/number factorizes iff at level 0 *) lev <> 0 in
aux need symbols
let rec find_symbols c_current c_next c_last = function
| [] -> []
| NonTerminal id :: sl ->
let prec = if not (List.is_empty sl) then c_current else c_last in
(id, prec) :: (find_symbols c_next c_next c_last sl)
| Terminal s :: sl -> find_symbols c_next c_next c_last sl
| Break n :: sl -> find_symbols c_current c_next c_last sl
| SProdList (x,_) :: sl' ->
(x,c_next)::(find_symbols c_next c_next c_last sl')
let border = function
| (_,(ETConstr(_,_,(_,BorderProd (_,a))))) :: _ -> a
| _ -> None
let recompute_assoc typs = let open Gramlib.Gramext in
match border typs, border (List.rev typs) with
| Some LeftA, Some RightA -> assert false
| Some LeftA, _ -> Some LeftA
| _, Some RightA -> Some RightA
| _ -> None
(** ******************************************************************** **)
(** Registration of syntax extensions **)
(** (parsing/printing, no interpretation) **)
let pr_arg_level from (lev,typ) =
let pplev = function
| LevelLt n when Int.equal n from -> spc () ++ str "at next level"
| LevelLe n -> spc () ++ str "at level " ++ int n
| LevelLt n -> spc () ++ str "at level below " ++ int n
| LevelSome -> mt () in
Ppvernac.pr_set_entry_type (fun _ -> (*TO CHECK*) mt()) typ ++ pplev lev
let pr_level ntn ({notation_entry = from; notation_level = fromlevel}, args) typs =
(match from with InConstrEntry -> mt () | InCustomEntry s -> str "in " ++ str s ++ spc()) ++
str "at level " ++ int fromlevel ++ spc () ++ str "with arguments" ++ spc() ++
prlist_with_sep pr_comma (pr_arg_level fromlevel) (List.combine args typs)
let error_incompatible_level ntn oldprec oldtyps prec typs =
user_err
(str "Notation " ++ pr_notation ntn ++ str " is already defined" ++ spc() ++
pr_level ntn oldprec oldtyps ++
spc() ++ str "while it is now required to be" ++ spc() ++
pr_level ntn prec typs ++ str ".")
let error_parsing_incompatible_level ntn ntn' oldprec oldtyps prec typs =
user_err
(str "Notation " ++ pr_notation ntn ++ str " relies on a parsing rule for " ++ pr_notation ntn' ++ spc() ++
str " which is already defined" ++ spc() ++
pr_level ntn oldprec oldtyps ++
spc() ++ str "while it is now required to be" ++ spc() ++
pr_level ntn prec typs ++ str ".")
let warn_incompatible_format =
CWarnings.create ~name:"notation-incompatible-format" ~category:CWarnings.CoreCategories.parsing
(fun (specific,ntn) ->
let head,scope = match specific with
| None -> str "Notation", mt ()
| Some LastLonelyNotation -> str "Lonely notation", mt ()
| Some (NotationInScope sc) -> str "Notation", strbrk (" in scope " ^ sc) in
head ++ spc () ++ pr_notation ntn ++
strbrk " was already defined with a different format" ++ scope ++ str ".")
type syntax_extension = {
synext_level : level;
synext_nottyps : constr_entry_key list;
synext_notgram : notation_grammar option;
synext_notprint : generic_notation_printing_rules option;
}
type syntax_rules =
| PrimTokenSyntax
| SpecificSyntax of syntax_extension
let syntax_rules_iter f = function
| PrimTokenSyntax -> ()
| SpecificSyntax synext -> f synext
let check_reserved_format ntn rules rules' =
try
let { notation_printing_reserved = reserved; notation_printing_rules = generic_rules } = rules in
if reserved &&
(not (List.for_all2eq unparsing_eq rules'.notation_printing_unparsing generic_rules.notation_printing_unparsing))
then
warn_incompatible_format (None,ntn)
with Not_found -> ()
let specific_format_to_declare (specific,ntn as specific_ntn) rules =
try
let specific_rules = Ppextend.find_specific_notation_printing_rule specific_ntn in
if not (List.for_all2eq unparsing_eq rules.notation_printing_unparsing specific_rules.notation_printing_unparsing)
then (warn_incompatible_format (Some specific,ntn); true)
else false
with Not_found -> true
type syntax_extension_obj =
locality_flag * (notation * syntax_extension)
let check_and_extend_constr_grammar ntn rule =
try
let ntn_for_grammar = rule.notgram_notation in
if notation_eq ntn ntn_for_grammar then raise Not_found;
let prec = rule.notgram_level in
let typs = rule.notgram_typs in
let oldprec = Notation.level_of_notation ntn_for_grammar in
let oldparsing =
try
Some (Notgram_ops.grammar_of_notation ntn_for_grammar)
with Not_found -> None
in
let oldtyps = Notgram_ops.non_terminals_of_notation ntn_for_grammar in
if not (level_eq prec oldprec) && oldparsing <> None then
error_parsing_incompatible_level ntn ntn_for_grammar oldprec oldtyps prec typs;
if oldparsing = None then raise Not_found
with Not_found ->
Egramcoq.extend_constr_grammar rule
let cache_one_syntax_extension (ntn,synext) =
let prec = synext.synext_level in
(* Check and ensure that the level and the precomputed parsing rule is declared *)
let oldparsing =
try
let oldprec = Notation.level_of_notation ntn in
let oldparsing =
try
Some (Notgram_ops.grammar_of_notation ntn)
with Not_found -> None
in
let oldtyps = Notgram_ops.non_terminals_of_notation ntn in
if not (level_eq prec oldprec && List.for_all2 Extend.constr_entry_key_eq synext.synext_nottyps oldtyps) &&
(oldparsing <> None || synext.synext_notgram = None) then
error_incompatible_level ntn oldprec oldtyps prec synext.synext_nottyps;
oldparsing
with Not_found ->
(* Declare the level and the precomputed parsing rule *)
let () = Notation.declare_notation_level ntn prec in
let () = Notgram_ops.declare_notation_non_terminals ntn synext.synext_nottyps in
let () = Option.iter (Notgram_ops.declare_notation_grammar ntn) synext.synext_notgram in
None in
(* Declare the parsing rule *)
begin match oldparsing, synext.synext_notgram with
| None, Some grams -> List.iter (check_and_extend_constr_grammar ntn) grams
| _ -> (* The grammars rules are canonically derived from the string and the precedence*) ()
end;
(* Printing *)
Option.iter (declare_generic_notation_printing_rules ntn) synext.synext_notprint
let cache_syntax_extension (_, sy) =
cache_one_syntax_extension sy
let subst_syntax_extension (subst, (local, (ntn, synext))) =
(local, (ntn, synext))
let classify_syntax_definition (local, _) =
if local then Dispose else Substitute
let open_syntax_extension i o =
if Int.equal i 1 then cache_syntax_extension o
let inSyntaxExtension : syntax_extension_obj -> obj =
declare_object
{(default_object "SYNTAX-EXTENSION") with
object_stage = Summary.Stage.Synterp;
open_function = simple_open ~cat:notation_cat open_syntax_extension;
cache_function = cache_syntax_extension;
subst_function = subst_syntax_extension;
classify_function = classify_syntax_definition}
(** ******************************************************************** **)
(** Precedences **)
(* Interpreting user-provided modifiers *)
(* XXX: We could move this to the parser itself *)
module NotationMods = struct
type notation_modifier = {
assoc : Gramlib.Gramext.g_assoc option;
level : int option;
etyps : (Id.t * simple_constr_prod_entry_key) list;
(* common to syn_data below *)
format : lstring option;
}
let default = {
assoc = None;
level = None;
etyps = [];
format = None;
}
end
exception UnknownCustomEntry of string
let () = CErrors.register_handler @@ function
| UnknownCustomEntry entry -> Some Pp.(str "Unknown custom entry: " ++ str entry ++ str ".")
| _ -> None
let check_custom_entry entry =
if not (Egramcoq.exists_custom_entry entry) then
raise @@ UnknownCustomEntry entry
let check_entry_type = function
| ETConstr (InCustomEntry entry,_,_) -> check_custom_entry entry
| ETConstr (InConstrEntry,_,_) | ETPattern _
| ETIdent | ETGlobal | ETBigint | ETName | ETBinder _-> ()
let interp_modifiers entry modl = let open NotationMods in
let rec interp acc = function
| [] -> acc
| CAst.{loc;v} :: l -> match v with
| SetEntryType (s,typ) ->
let id = Id.of_string s in
check_entry_type typ;
if Id.List.mem_assoc id acc.etyps then
user_err ?loc
(str s ++ str " is already assigned to an entry or constr level.");
interp { acc with etyps = (id,typ) :: acc.etyps; } l
| SetItemLevel ([],bko,n) ->
interp acc l
| SetItemLevel (s::idl,bko,n) ->
let id = Id.of_string s in
if Id.List.mem_assoc id acc.etyps then
user_err ?loc
(str s ++ str " is already assigned to an entry or constr level.");