-
Notifications
You must be signed in to change notification settings - Fork 2
/
xr.el
2285 lines (2142 loc) · 96.8 KB
/
xr.el
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
;;; xr.el --- Convert string regexp to rx notation -*- lexical-binding: t -*-
;; Copyright (C) 2019-2024 Free Software Foundation, Inc.
;; Author: Mattias Engdegård <mattiase@acm.org>
;; Version: 2.0
;; Package-Requires: ((emacs "27.1"))
;; URL: https://github.com/mattiase/xr
;; Keywords: lisp, regexps
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package translates regexps in string form to the rx notation.
;; It can also find mistakes and questionable constructs in regexps
;; and related expressions. See the README file for more information.
;;; Code:
(require 'rx)
(require 'cl-lib)
(defun xr--add-diag-group (warnings group)
(push group (car warnings)))
(defun xr--warn (warnings beg end message &rest info)
"Add the warning MESSAGE at BEG..END to WARNINGS.
BEG and END are inclusive char indices. END is nil if only start is known.
More BEG END MESSAGE argument triples for info-level messages can follow."
(when warnings
(let ((more nil))
(while info
(unless (cddr info)
(error "bad xr--warn info args"))
(push (list (nth 0 info) (nth 1 info) (nth 2 info) 'info)
more)
(setq info (cdddr info)))
(xr--add-diag-group warnings (cons (list beg end message 'warning)
(nreverse more))))))
(defun xr--add-error (warnings beg end message)
(when warnings
(xr--add-diag-group warnings (list (list beg end message 'error)))))
(define-error 'xr-parse-error "xr parsing error")
(defun xr--error (beg end message &rest args)
"Format MESSAGE with ARGS at BEG..END as an error and abort the parse.
END is nil if unknown."
(signal 'xr-parse-error
(list (apply #'format-message message args) beg end)))
;; House versions of `cl-some' and `cl-every', but faster.
(defmacro xr--some (pred list)
"Whether PRED is true for at least one element in LIST."
`(let ((list ,list))
(while (and list (not (funcall ,pred (car list))))
(setq list (cdr list)))
list))
(defmacro xr--every (pred list)
"Whether PRED is true for all elements in LIST."
`(let ((list ,list))
(while (and list (funcall ,pred (car list)))
(setq list (cdr list)))
(not list)))
(defvar xr--string)
(defvar xr--len)
(defvar xr--idx)
(defmacro xr--substring-p (string idx substring)
"Whether SUBSTRING is in STRING at IDX."
(let ((i (make-symbol "i"))
(sub (make-symbol "sub")))
`(let ((,i ,idx)
(,sub ,substring))
(eq (compare-strings ,string ,i (+ ,i (length ,sub)) ,sub nil nil)
t))))
;; `string-search' added in Emacs 28
(defalias 'xr--string-search
(if (fboundp 'string-search)
#'string-search
(lambda (needle haystack start-pos)
"Index of the string NEEDLE in the string HAYSTACK, or nil."
(string-match-p (regexp-quote needle) haystack start-pos))))
(defun xr--parse-char-alt (negated warnings checks)
(let* ((intervals nil)
(classes nil)
(start-pos xr--idx)
(string xr--string)
(len xr--len)
(idx start-pos)
ch)
(while (and (< idx len)
(or (not (eq (setq ch (aref string idx)) ?\]))
(= idx start-pos)))
(cond
;; character class
((and (eq ch ?\[)
(< (+ idx 3) len)
(eq (aref string (1+ idx)) ?:)
(let ((i (xr--string-search ":]" string (+ 2 idx))))
(and i
(let ((sym (intern (substring string (+ idx 2) i))))
(unless
(memq sym
'( ascii alnum alpha blank cntrl digit graph
lower multibyte nonascii print punct space
unibyte upper word xdigit))
(xr--error idx (1+ i)
"No character class `[:%s:]'"
(symbol-name sym)))
(let ((prev (assq sym classes)))
(if prev
(let* ((prev-beg (cdr prev))
(prev-end (1+ (xr--string-search
":]" string prev-beg))))
(xr--warn
warnings idx (1+ i)
(format-message
"Duplicated character class `[:%s:]'" sym)
prev-beg prev-end "Previous occurrence here"))
(push (cons sym idx) classes)))
(setq idx (+ i 2))
t)))))
;; character range
((and (< (+ idx 3) len)
(eq (aref string (1+ idx)) ?-)
(not (memq (aref string (+ idx 2)) '(?\] nil))))
(let ((start ch)
(end (aref string (+ idx 2))))
(cond
((<= start #x7f #x3fff80 end)
;; Intervals that go from ASCII (0-7f) to raw bytes
;; (3fff80-3fffff) always exclude the intervening (Unicode) points.
(push (vector start #x7f idx) intervals)
(push (vector #x3fff80 end idx) intervals))
((<= start end)
(push (vector start end idx) intervals))
;; It's unlikely that anyone writes z-a by mistake; don't complain.
((and (eq start ?z) (eq end ?a)))
(t
(xr--warn
warnings idx (+ idx 2)
(xr--escape-string
(format-message "Reversed range `%c-%c' matches nothing"
start end)))))
(cond
;; Suppress warnings about ranges between adjacent digits,
;; like [0-1], as they are common and harmless.
((and (= end (1+ start)) (not (<= ?0 start end ?9)))
(xr--warn warnings idx (+ idx 2)
(xr--escape-string
(format-message "Two-character range `%c-%c'"
start end))))
;; This warning is not necessarily free of false positives,
;; although they are unlikely. Maybe it should be off by default?
((and (<= ?A start ?Z) (<= ?a end ?z))
(xr--warn
warnings idx (+ idx 2)
(format-message
"Range `%c-%c' between upper and lower case includes symbols"
start end)))
;; Ranges on the form +-X and X-+ are likely to be a
;; mistake because matching both + and - is common.
((and (eq checks 'all)
(or (eq start ?+) (eq end ?+)))
(xr--warn
warnings idx (+ idx 2)
(xr--escape-string
(format-message
"Suspect character range `%c-%c': should `-' be literal?"
start end)))))
(setq idx (+ idx 3))))
;; single character (including ], ^ and -)
(t
(when (and
warnings
(eq ch ?\[)
;; Ad-hoc pattern attempting to catch mistakes
;; on the form [...[...]...]
;; where we are ^here
(let ((i (1+ idx)))
(while (and (< i len)
(not (memq (aref string i) '(?\[ ?\]))))
(setq i (1+ i)))
(and (< i len)
(eq (aref string i) ?\])
(let ((j (1+ i)))
(while (and (< j len)
(not (memq (aref string j) '(?\[ ?\]))))
(setq j (1+ j)))
(and
(< (+ i 1) j len)
(not (memq (aref string (- j 1)) '(?\[ ?\\)))
(eq (aref string j) ?\])))))
;; Only if the alternative didn't start with ]
(not (and intervals
(eq (aref (car (last intervals)) 0) ?\]))))
(xr--warn warnings idx idx
(format-message "Suspect `[' in char alternative")))
(when (and (eq ch ?-)
(< start-pos idx (1- len))
(not (eq (aref string (1+ idx)) ?\])))
(xr--warn
warnings idx idx
(format-message
"Literal `-' not first or last in character alternative")))
(when (eq checks 'all)
(let ((last (car-safe intervals)))
(when (and last
(eq (aref last 1) ?\\)
(or (memq ch '( ?t ?n ?r ?f ?x ?e ?b ; char escapes
?s ?S ?d ?D ?w ?W)) ; PCRE sequences
(<= ?0 ch ?7)) ; octal escapes
;; Suppress some common false positives, eg [\\nrt]
(not (and (memq ch '(?t ?n ?r ?f ?x ?e ?b))
(< (1+ idx) len)
(memq (aref string (1+ idx))
'(?t ?n ?r ?f ?x ?e ?b)))))
(xr--warn
warnings (- idx 1) idx
(format-message
"Possibly erroneous `\\%c' in character alternative" ch)))))
(push (vector ch ch idx) intervals)
(setq idx (1+ idx)))))
(unless (< idx len)
(xr--error (- start-pos (if negated 2 1)) (- len 1)
"Unterminated character alternative"))
(setq xr--idx (1+ idx)) ; eat the ] and write back
;; Detect duplicates and overlapping intervals.
(let* ((sorted
(sort (nreverse intervals)
(lambda (a b) (< (aref a 0) (aref b 0)))))
(s sorted))
(while (cdr s)
(let* ((this (car s))
(next (cadr s)))
(if (>= (aref this 1) (aref next 0))
;; Overlap.
(let* ((a (if (< (aref this 2) (aref next 2)) this next))
(b (if (< (aref this 2) (aref next 2)) next this)))
(cond
;; Duplicate character: drop it and warn.
((and (eq (aref a 0) (aref a 1))
(eq (aref b 0) (aref b 1)))
(xr--warn warnings
(aref b 2) (aref b 2)
(xr--escape-string
(format-message
"Duplicated `%c' inside character alternative"
(aref this 0)))
(aref a 2) (aref a 2) "Previous occurrence here"))
;; Duplicate range: drop it and warn.
((and (eq (aref a 0) (aref b 0))
(eq (aref a 1) (aref b 1)))
(xr--warn
warnings (aref b 2) (+ (aref b 2) 2)
(xr--escape-string
(format-message
"Duplicated `%c-%c' inside character alternative"
(aref b 0) (aref b 1)))
(aref a 2) (+ (aref a 2) 2) "Previous occurrence here"))
;; Character in range: drop it and warn.
((eq (aref a 0) (aref a 1))
(when (eq a this)
(setcar s next))
(xr--warn
warnings (aref b 2) (+ (aref b 2) 2)
(xr--escape-string
(format-message
"Range `%c-%c' includes character `%c'"
(aref b 0) (aref b 1) (aref a 0)))
(aref a 2) (aref a 2) "Previous occurrence here"))
;; Same but other way around.
((eq (aref b 0) (aref b 1))
(when (eq b this)
(setcar s next))
(xr--warn
warnings (aref b 2) (aref b 2)
(xr--escape-string
(format-message
"Character `%c' included in range `%c-%c'"
(aref b 0) (aref a 0) (aref a 1)))
(aref a 2) (+ (aref a 2) 2) "Previous occurrence here"))
;; Overlapping ranges: merge and warn.
(t
(let ((this-end (aref this 1)))
(aset this 1 (max (aref this 1) (aref next 1)))
(xr--warn
warnings (aref b 2) (+ (aref b 2) 2)
(xr--escape-string
(format-message "Ranges `%c-%c' and `%c-%c' overlap"
(aref this 0) this-end
(aref next 0) (aref next 1)))
(aref a 2) (+ (aref a 2) 2) "Previous occurrence here"))))
(setcdr s (cddr s)))
;; No overlap.
(setq s (cdr s)))))
;; Gather ranges and single characters separately.
;; We make no attempts at merging adjacent intervals/characters,
;; nor at splitting short intervals such as "a-b"; if the user
;; wrote it that way, there was probably a reason for it.
(let ((ranges nil)
(chars nil))
(dolist (interv sorted)
(if (eq (aref interv 0) (aref interv 1))
(push (aref interv 0) chars)
(push (string (aref interv 0) ?- (aref interv 1))
ranges)))
;; We return (any) for non-negated empty sets, such as [z-a].
;; `unmatchable' would perhaps be better; both require Emacs 27.1
;; or newer for use in rx.
(cond
;; Negated empty set, like [^z-a]: anything.
((and negated
(null chars)
(null ranges)
(null classes))
'anything)
;; Non-negated single-char set, like [$]: make a string.
((and (= (length chars) 1)
(not negated)
(null ranges)
(null classes))
(string (car chars)))
;; Single named class, like [[:space:]]: use the symbol.
((and (= (length classes) 1)
(null chars)
(null ranges))
(if negated
(list 'not (caar classes))
(caar classes)))
;; [^\n]: nonl.
((and negated
(equal chars '(?\n))
(null ranges)
(null classes))
'nonl)
;; Anything else: produce (any ...)
(t
;; Put dash last of all single characters.
(when (memq ?- chars)
(setq chars (cons ?- (delq ?- chars))))
(let* ((set (cons 'any
(nconc
(and ranges
(list (apply #'concat (nreverse ranges))))
(and chars
(list (apply #'string (nreverse chars))))
(nreverse (mapcar #'car classes))))))
(if negated
(list 'not set)
set))))))))
(defun xr--rev-join-seq (sequence)
"Reverse SEQUENCE, flatten any (seq ...) inside, and concatenate
adjacent strings. SEQUENCE is used destructively."
(let ((strings nil)
(result nil))
(while sequence
(let ((elem (car sequence))
(rest (cdr sequence)))
(setq sequence
(cond ((stringp elem)
(push elem strings)
rest)
((eq (car-safe elem) 'seq)
(nconc (nreverse (cdr elem)) rest))
(strings
(push (if (cdr strings)
(mapconcat #'identity strings nil)
(car strings))
result)
(setq strings nil)
(push elem result)
rest)
(t
(push elem result)
rest)))))
(if strings
(cons (if (cdr strings)
(mapconcat #'identity strings nil)
(car strings))
result)
result)))
(defun xr--char-category (negated category-code)
(let* ((sym (assq category-code
'((?\s . space-for-indent)
(?. . base)
(?0 . consonant)
(?1 . base-vowel)
(?2 . upper-diacritical-mark)
(?3 . lower-diacritical-mark)
(?4 . tone-mark)
(?5 . symbol)
(?6 . digit)
(?7 . vowel-modifying-diacritical-mark)
(?8 . vowel-sign)
(?9 . semivowel-lower)
(?< . not-at-end-of-line)
(?> . not-at-beginning-of-line)
(?A . alpha-numeric-two-byte)
(?C . chinese-two-byte)
(?G . greek-two-byte)
(?H . japanese-hiragana-two-byte)
(?I . indian-two-byte)
(?K . japanese-katakana-two-byte)
(?L . strong-left-to-right)
(?N . korean-hangul-two-byte)
(?R . strong-right-to-left)
(?Y . cyrillic-two-byte)
(?^ . combining-diacritic)
(?a . ascii)
(?b . arabic)
(?c . chinese)
(?e . ethiopic)
(?g . greek)
(?h . korean)
(?i . indian)
(?j . japanese)
(?k . japanese-katakana)
(?l . latin)
(?o . lao)
(?q . tibetan)
(?r . japanese-roman)
(?t . thai)
(?v . vietnamese)
(?w . hebrew)
(?y . cyrillic)
(?| . can-break))))
(item (list 'category (if sym (cdr sym) category-code))))
(if negated (list 'not item) item)))
(defconst xr--char-syntax-alist
'((?- . whitespace)
(?\s . whitespace)
(?. . punctuation)
(?w . word)
(?W . word) ; undocumented
(?_ . symbol)
(?\( . open-parenthesis)
(?\) . close-parenthesis)
(?' . expression-prefix)
(?\" . string-quote)
(?$ . paired-delimiter)
(?\\ . escape)
(?/ . character-quote)
(?< . comment-start)
(?> . comment-end)
(?| . string-delimiter)
(?! . comment-delimiter)))
(defun xr--postfix (operator-char lazy operand)
;; We use verbose names for the common *, + and ? operators for readability
;; even though these names are affected by the rx-greedy-flag, since nobody
;; uses minimal-match in practice.
(let* ((sym (cdr (assq operator-char
(if lazy
;; What a pretty symmetry!
'((?* . *?)
(?+ . +?)
(?? . ??))
'((?* . zero-or-more)
(?+ . one-or-more)
(?? . opt))))))
;; Simplify when the operand is (seq ...)
(body (if (and (listp operand) (eq (car operand) 'seq))
(cdr operand)
(list operand))))
(cons sym body)))
(defun xr--repeat (lower upper operand)
"Apply a repetition of {LOWER,UPPER} to OPERAND.
UPPER may be nil, meaning infinity."
;; rx does not accept (= 0 ...) or (>= 0 ...), so we use
;; (repeat 0 0 ...) and (zero-or-more ...), respectively.
;; Note that we cannot just delete the operand if LOWER=UPPER=0,
;; since doing so may upset the group numbering.
(let* ((operator (cond ((null upper)
(if (zerop lower)
'(zero-or-more)
(list '>= lower)))
((and (= lower upper) (> lower 0))
(list '= lower))
(t
(list 'repeat lower upper))))
;; Simplify when the operand is (seq ...).
(body (if (and (listp operand) (eq (car operand) 'seq))
(cdr operand)
(list operand))))
(append operator body)))
(defconst xr--zero-width-assertions
'(bol eol bos eos bow eow word-boundary not-word-boundary
symbol-start symbol-end point))
(defun xr--matches-empty-p (rx)
"Whether RX can match the empty string regardless of context."
(pcase rx
(`(,(or 'seq 'one-or-more '+? 'group) . ,body)
(xr--every #'xr--matches-empty-p body))
(`(or . ,body)
(xr--some #'xr--matches-empty-p body))
(`(group-n ,_ . ,body)
(xr--every #'xr--matches-empty-p body))
(`(,(or 'opt 'zero-or-more ?? '*?) . ,_)
t)
(`(repeat ,from ,_ . ,body)
(or (= from 0)
(xr--every #'xr--matches-empty-p body)))
(`(,(or '= '>=) ,_ . ,body)
(xr--every #'xr--matches-empty-p body))
("" t)))
(defun xr--adjacent-subsumption (a b)
"Check if A subsumes B, or vice versa, or not, assuming they are adjacent.
Return `a-subsumes-b', `b-subsumes-a' or nil."
;; Check for subsuming repetitions in sequence: (Ra A) (Rb B)
;; where Ra and Rb are repetition operators, and A and B are operands.
;; We conclude that (Ra A) subsumes (Rb B), in the sense that the
;; sequence is equivalent to just (Ra A), if:
;; A matches a superset of B
;; and Ra can match infinitely many times
;; and Rb can match zero times
;; and Rb is non-greedy if Ra is non-greedy.
;; Example: [cd]+c?
(let ((a-expr (and (consp a)
(memq (car a)
'(zero-or-more one-or-more opt *? +? ??))
(xr--make-seq (cdr a)))))
(when a-expr
(let ((b-expr (and (consp b)
(memq (car b)
'(zero-or-more one-or-more opt *? +? ??))
(xr--make-seq (cdr b)))))
(when b-expr
(let ((a-op (car a))
(b-op (car b)))
;; Test the same condition twice, but mirrored.
(cond
((and (memq b-op '(zero-or-more opt *? ??))
(memq a-op '(zero-or-more one-or-more *? +?))
(not (and (memq a-op '(*? +?))
(memq b-op '(zero-or-more opt))))
(xr--superset-p a-expr b-expr))
'a-subsumes-b)
((and (memq a-op '(zero-or-more opt *? ??))
(memq b-op '(zero-or-more one-or-more *? +?))
(not (and (memq b-op '(*? +?))
(memq a-op '(zero-or-more opt))))
(xr--superset-p b-expr a-expr))
'b-subsumes-a))))))))
(defun xr--check-wrap-around-repetition (operand beg end warnings)
"Whether OPERAND has a wrap-around repetition subsumption case,
like (* (* X) ... (* X))."
(when (and (consp operand)
(memq (car operand) '(seq group group-n)))
(let* ((operands
(if (eq (car operand) 'group-n)
(cddr operand)
(cdr operand))))
(when (cddr operands)
(let* ((first (car operands))
(last (car (last operands)))
(subsumption (xr--adjacent-subsumption last first)))
(when subsumption
;; FIXME: add info about first and last item.
;; How do we get their locations?
(xr--warn
warnings beg end
(if (eq subsumption 'b-subsumes-a)
"First item in repetition subsumes last item (wrapped)"
"Last item in repetition subsumes first item (wrapped)"))))))))
(defun xr--parse-seq (warnings purpose checks)
(let ((locations nil) ; starting idx for each item in sequence
(sequence nil) ; parsed items, reversed
(string xr--string)
(len xr--len)
(idx xr--idx)
(at-end nil))
(while (and (< idx len) (not at-end))
(let ((item-start idx)
(next-char (aref string idx)))
(push item-start locations)
(cond
;; ^ - only special at beginning of sequence
((eq next-char ?^)
(setq idx (1+ idx))
(if (null sequence)
(progn
(when (eq purpose 'file)
(xr--warn warnings item-start item-start
"Use \\` instead of ^ in file-matching regexp"))
(push 'bol sequence))
(xr--warn warnings item-start item-start
(format-message "Unescaped literal `^'"))
(push "^" sequence)))
;; $ - only special at end of sequence
((eq next-char ?$)
(setq idx (1+ idx))
(if (or (>= idx len)
(and (< (1+ idx) len)
(eq (aref string idx) ?\\)
(memq (aref string (1+ idx)) '(?| ?\)))))
(progn
(when (eq purpose 'file)
(xr--warn warnings item-start item-start
"Use \\' instead of $ in file-matching regexp"))
(push 'eol sequence))
(xr--warn warnings item-start item-start
(format-message "Unescaped literal `$'"))
(push "$" sequence)))
;; not-newline
((eq next-char ?.)
(setq idx (1+ idx))
;; Assume that .* etc is intended.
(when (and (eq purpose 'file)
(not (and (< idx len)
(memq (aref string idx) '(?? ?* ?+)))))
(xr--warn warnings item-start item-start
(format-message
"Possibly unescaped `.' in file-matching regexp")))
(push 'nonl sequence))
;; character alternative
((eq next-char ?\[)
(setq idx (1+ idx))
(let ((negated (and (< idx len) (eq (aref string idx) ?^))))
(when negated (setq idx (1+ idx)))
;; FIXME: ugly spill and fill around call
(setq xr--idx idx)
(push (xr--parse-char-alt negated warnings checks) sequence)
(setq idx xr--idx)))
;; * ? + (and non-greedy variants)
((memq next-char '(?* ?? ?+))
;; - not special at beginning of sequence or after ^ or \`
(if (and sequence
(not (and (memq (car sequence) '(bol bos))
(memq (aref string (1- idx)) '(?^ ?`)))))
(let* ((operator-char next-char)
(lazy (and (< (1+ item-start) len)
(eq (aref string (1+ item-start)) ??)))
(end-idx (if lazy (1+ item-start) item-start))
(operand (car sequence)))
(when warnings
;; Check both (OP (OP X)) and (OP (group (OP X))).
(let ((inner-op
(and (consp operand)
(if (eq (car operand) 'group)
(and (null (cddr operand))
(let ((inner (cadr operand)))
(and (consp inner)
(car inner))))
(car operand)))))
(cond
((and
;; (OP1 (OP2 X)), for any repetitions OP1, OP2
(memq inner-op '(opt zero-or-more one-or-more *? +? ??))
;; Except (? (+ X)) which may be legitimate.
(not (and (eq operator-char ??)
(consp operand)
(memq inner-op '(one-or-more +?)))))
(let ((outer-opt (eq operator-char ??))
(inner-opt (memq inner-op '(opt ??))))
(xr--warn warnings
idx end-idx
(if outer-opt
(if inner-opt
"Optional option"
"Optional repetition")
(if inner-opt
"Repetition of option"
"Repetition of repetition"))
(cadr locations) (1- idx)
"This is the inner expression")))
((memq operand xr--zero-width-assertions)
(xr--warn warnings
idx end-idx
(if (eq operator-char ??)
"Optional zero-width assertion"
"Repetition of zero-width assertion")
(cadr locations) (1- idx)
"Zero-width assertion here"))
((and (xr--matches-empty-p operand)
;; Rejecting repetition of the empty string
;; suppresses some false positives.
(not (equal operand "")))
(xr--warn warnings
idx end-idx
(concat
(if (eq operator-char ??)
"Optional expression"
"Repetition of expression")
" matching an empty string")
(cadr locations) (1- idx)
"This expression matches an empty string"))
((and (memq operator-char '(?* ?+))
(consp operand)
(memq (car operand) '(seq group))
(let ((nonzero-items
(mapcan
(lambda (item)
(and (not (xr--matches-empty-p item))
(list item)))
(cdr operand))))
(and (= (length nonzero-items) 1)
(consp (car nonzero-items))
(memq (caar nonzero-items)
'( opt zero-or-more one-or-more
+? *? ?? >=)))))
(xr--warn warnings
idx end-idx
"Repetition of effective repetition"
(cadr locations) (1- idx)
"This expression contains a repetition"))))
;; (* (* X) ... (* X)) etc: wrap-around subsumption
(unless (eq operator-char ??)
(xr--check-wrap-around-repetition
operand (cadr locations) end-idx warnings)))
(setq idx (1+ end-idx))
(setq sequence (cons (xr--postfix operator-char lazy operand)
(cdr sequence)))
(pop locations))
(setq idx (1+ idx))
(xr--warn warnings item-start item-start
(format-message "Unescaped literal `%c'" next-char))
(push (char-to-string next-char) sequence)))
;; Anything starting with backslash
((eq next-char ?\\)
(setq idx (1+ idx))
(unless (< idx len)
(xr--error (1- len) (1- len) "Backslash at end of regexp"))
(setq next-char (aref string idx))
(cond
;; end of sequence: \) or \|
((memq next-char '(?\) ?|))
(setq idx (1- idx)) ; regurgitate the backslash
(setq at-end t))
;; group
((eq next-char ?\()
(setq idx (1+ idx))
(let* ((group-start idx)
(submatch
(if (and (< idx len) (eq (aref string idx) ??))
(progn
(setq idx (1+ idx))
(unless (< idx len)
(xr--error (- idx 3) (1- idx)
"Invalid \\(? syntax"))
(let ((c (aref string idx)))
(cond
((eq c ?:)
(setq idx (1+ idx))
nil)
((and (<= ?1 c ?9)
(let ((i (1+ idx)))
(while
(and (< i len)
(<= ?0 (aref string i) ?9))
(setq i (1+ i)))
(and (< i len)
(eq (aref string i) ?:)
(prog1
(string-to-number
(substring string idx i))
(setq idx (1+ i)))))))
(t (xr--error (- idx 3) (1- idx)
"Invalid \\(? syntax")))))
(when (and (eq checks 'all)
(< (1+ idx) len)
(eq (aref string idx) ?:)
(eq (aref string (1+ idx)) ??)
;; suppress if the group ends after the :?
(not (xr--substring-p string (+ idx 2) "\\)")))
(xr--warn
warnings idx (1+ idx)
(format-message
"Possibly mistyped `:?' at start of group")))
'unnumbered))
(group (progn
;; FIXME: ugly spill and fill around call
(setq xr--idx idx)
(prog1
(xr--parse-alt warnings purpose checks)
(setq idx xr--idx))))
;; simplify - group has an implicit seq
(operand (if (and (listp group) (eq (car group) 'seq))
(cdr group)
(list group))))
(unless (and (< (1+ idx) len)
(eq (aref string idx) ?\\)
(eq (aref string (1+ idx)) ?\)))
(xr--error (- group-start 2) (1- (min len idx))
"Missing \\)"))
(setq idx (+ 2 idx))
(let ((item (cond ((eq submatch 'unnumbered)
(cons 'group operand))
(submatch
(append (list 'group-n submatch) operand))
(t group))))
(push item sequence))))
;; \{..\} - not special at beginning of sequence or after ^ or \`
((eq next-char ?\{)
(if (or (not sequence)
(and (memq (car sequence) '(bol bos))
(memq (aref string (1- item-start)) '(?^ ?`))))
;; Literal {
(xr--warn warnings item-start (1+ item-start)
(format-message
"Escaped non-special character `{'"))
(setq idx (1+ idx))
(let ((operand (car sequence)))
;; parse bounds
(let* ((start idx)
(i start))
(while (and (< i len)
(<= ?0 (aref string i) ?9))
(setq i (1+ i)))
(let ((lower (and (> i start)
(string-to-number
(substring string start i))))
(comma nil)
(upper nil))
(when (and (< i len)
(eq (aref string i) ?,))
(setq comma t)
(setq i (1+ i))
(let ((start-u i))
(while (and (< i len)
(<= ?0 (aref string i) ?9))
(setq i (1+ i)))
(setq upper
(and (> i start-u)
(string-to-number
(substring string start-u i))))))
(setq idx i)
(unless (xr--substring-p string idx "\\}")
(xr--error (- start 2) (1- idx) "Missing \\}"))
(unless (or lower upper)
(xr--warn warnings (- start 2) (+ idx 1)
(if comma
"Uncounted repetition"
"Implicit zero repetition")))
(setq idx (+ i 2))
(setq lower (or lower 0))
(unless comma
(setq upper lower))
(when (and upper (> lower upper))
(xr--error start (1- i)
"Invalid repetition interval"))
(when warnings
(when (or (not upper) (>= upper 2))
(xr--check-wrap-around-repetition
operand (cadr locations) (1- idx) warnings))
(cond
((and (consp operand)
(or
;; (** N M (* X)), for any repetition *
(memq (car operand)
'(opt zero-or-more one-or-more +? *? ??))
;; (** N M (group (* X))), for any repetition *
(and
(eq (car operand) 'group)
(null (cddr operand))
(let ((inner (cadr operand)))
(and (consp inner)
(memq (car inner)
'(opt zero-or-more one-or-more
+? *? ??)))))))
(let ((inner-opt (or (memq (car operand) '(opt ??))
(and (eq (car operand) 'group)
(memq (caadr operand)
'(opt ??))))))
(xr--warn warnings
item-start (1- idx)
(if inner-opt
"Repetition of option"
"Repetition of repetition")
(cadr locations) (1- item-start)
"This is the inner expression")))
((memq operand xr--zero-width-assertions)
(xr--warn warnings
item-start (1- idx)
"Repetition of zero-width assertion"
(cadr locations) (1- item-start)
"Zero-width assertion here"))
((and (xr--matches-empty-p operand)
;; Rejecting repetition of the empty string
;; suppresses some false positives.
(not (equal operand "")))
(xr--warn
warnings item-start (1- idx)
"Repetition of expression matching an empty string"
(cadr locations) (1- item-start)
"This expression matches an empty string"))))
(setq sequence (cons (xr--repeat lower upper operand)
(cdr sequence)))
(pop locations))))))
;; back-reference
((memq next-char (eval-when-compile (number-sequence ?1 ?9)))
(setq idx (1+ idx))
(push (list 'backref (- next-char ?0))
sequence))
;; various simple substitutions
((memq next-char '(?w ?W ?` ?\' ?= ?b ?B ?< ?>))
(setq idx (1+ idx))
(let ((sym (cdr (assq
next-char
;; Note that translating \w to wordchar isn't
;; right, since `wordchar' yields [[:word:]] which
;; does not respect syntax properties.
;; We translate \W to (not (syntax word)) for
;; consistency, rather than the confusingly
;; named legacy `not-wordchar'.
'((?w . (syntax word)) (?W . (not (syntax word)))
(?` . bos) (?\' . eos)
(?= . point)
(?b . word-boundary) (?B . not-word-boundary)
(?< . bow) (?> . eow))))))
(push sym sequence)))
;; symbol-start, symbol-end
((eq next-char ?_)
(setq idx (1+ idx))
(let* ((c (and (< idx len) (aref string idx)))
(sym (cond ((eq c ?<) 'symbol-start)
((eq c ?>) 'symbol-end)
(t
(xr--error (- idx 2) idx
"Invalid \\_ sequence")))))
(setq idx (1+ idx))
(push sym sequence)))
;; character syntax
((memq next-char '(?s ?S))
(setq idx (1+ idx))
(unless (< idx len)
(xr--error (- idx 2) (1- len)
"Incomplete \\%c sequence" next-char))
(let* ((negated (eq next-char ?S))
(syntax-code (aref string idx)))
(setq idx (1+ idx))
(let ((sym (assq syntax-code xr--char-syntax-alist)))
(unless sym
(xr--error (- idx 3) (- idx 1)
"Unknown syntax code `%s'"
(xr--escape-string
(char-to-string syntax-code))))
(push (let ((item (list 'syntax (cdr sym))))
(if negated (list 'not item) item))
sequence))))
;; character categories
((memq next-char '(?c ?C))
(setq idx (1+ idx))
(unless (< idx len)
(xr--error (- idx 2) (1- len)
"Incomplete \\%c sequence" next-char))
(let ((negated (eq next-char ?C))
(category-code (aref string idx)))
(setq idx (1+ idx))