-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
gdscript-rx.el
1491 lines (1347 loc) · 63.6 KB
/
gdscript-rx.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
;;; gdscript-rx.el --- Regex for GDScript -*- lexical-binding: t; -*-
;; Copyright (C) 2020 GDQuest
;; Author: Nathan Lovato <nathan@gdquest.com>, Fabián E. Gallina <fgallina@gnu.org>
;; URL: https://github.com/godotengine/emacs-gdscript-mode/
;; Version: 1.0.0
;; Package-Requires: ((emacs "26.3"))
;; Maintainer: nathan@gdquest.com
;; Created: Feb 2020
;; Keywords: languages
;; 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Macro that defines named regular expressions to detect syntactic elements in
;; GDScript code.
;; Starts with a copy of the rx package that ships with Emacs 27.
;;; Code:
;; gdscript-rx is a copy of Emacs 27's rx module, to ensure compatibility with
;; Emacs 26
;; Copy of Emacs 27's rx package
;; This facility allows writing regexps in a sexp-based language
;; instead of strings. Regexps in the `rx' notation are easier to
;; read, write and maintain; they can be indented and commented in a
;; natural way, and are easily composed by program code.
;; The translation to string regexp is done by a macro and does not
;; incur any extra processing during run time. Example:
;;
;; (rx bos (or (not (any "^"))
;; (seq "^" (or " *" "["))))
;;
;; => "\\`\\(?:[^^]\\|\\^\\(?: \\*\\|\\[\\)\\)"
;;
;; The notation is much influenced by and retains some compatibility with
;; Olin Shivers's SRE, with concessions to Emacs regexp peculiarities,
;; and the older Emacs package Sregex.
;; The `gdscript-rx--translate...' functions below return (REGEXP . PRECEDENCE),
;; where REGEXP is a list of string expressions that will be
;; concatenated into a regexp, and PRECEDENCE is one of
;;
;; t -- can be used as argument to postfix operators (eg. "a")
;; seq -- can be concatenated in sequence with other seq or higher (eg. "ab")
;; lseq -- can be concatenated to the left of rseq or higher (eg. "^a")
;; rseq -- can be concatenated to the right of lseq or higher (eg. "a$")
;; nil -- can only be used in alternatives (eg. "a\\|b")
;;
;; They form a lattice:
;;
;; t highest precedence
;; |
;; seq
;; / \
;; lseq rseq
;; \ /
;; nil lowest precedence
(defconst gdscript-rx--char-classes
'((digit . digit)
(numeric . digit)
(num . digit)
(control . cntrl)
(cntrl . cntrl)
(hex-digit . xdigit)
(hex . xdigit)
(xdigit . xdigit)
(blank . blank)
(graphic . graph)
(graph . graph)
(printing . print)
(print . print)
(alphanumeric . alnum)
(alnum . alnum)
(letter . alpha)
(alphabetic . alpha)
(alpha . alpha)
(ascii . ascii)
(nonascii . nonascii)
(lower . lower)
(lower-case . lower)
(punctuation . punct)
(punct . punct)
(space . space)
(whitespace . space)
(white . space)
(upper . upper)
(upper-case . upper)
(word . word)
(wordchar . word)
(unibyte . unibyte)
(multibyte . multibyte))
"Alist mapping rx symbols to character classes.
Most of the names are from SRE.")
(defvar gdscript-rx-constituents nil
"Alist of old-style rx extensions, for compatibility.
For new code, use `gdscript-rx-define', `gdscript-rx-let',
or `gdscript-rx-let-eval'.
Each element is (SYMBOL . DEF).
If DEF is a symbol, then SYMBOL is an alias of DEF.
If DEF is a string, then SYMBOL is a plain rx symbol defined as the
regexp string DEF.
If DEF is a list on the form (FUN MIN-ARGS MAX-ARGS PRED), then
SYMBOL is an rx form with at least MIN-ARGS and at most
MAX-ARGS arguments. If MAX-ARGS is nil, then there is no upper limit.
FUN is a function taking the entire rx form as single argument
and returning the translated regexp string.
If PRED is non-nil, it is a predicate that all actual arguments must
satisfy.")
(defvar gdscript-rx--local-definitions nil
"Alist of dynamic local rx definitions.
Each entry is:
(NAME DEF) -- NAME is an rx symbol defined as the rx form DEF.
(NAME ARGS DEF) -- NAME is an rx form with arglist ARGS, defined
as the rx form DEF (which can contain members of ARGS).")
(defsubst gdscript-rx--lookup-def (name)
"Current definition of NAME: (DEF) or (ARGS DEF), or nil if none."
(or (cdr (assq name gdscript-rx--local-definitions))
(get name 'gdscript-rx-definition)))
(defun gdscript-rx--expand-def (form)
"FORM expanded (once) if a user-defined construct; otherwise nil."
(cond ((symbolp form)
(let ((def (gdscript-rx--lookup-def form)))
(and def
(if (cdr def)
(error "Not an `rx' symbol definition: %s" form)
(car def)))))
((consp form)
(let* ((op (car form))
(def (gdscript-rx--lookup-def op)))
(and def
(if (cdr def)
(gdscript-rx--expand-template
op (cdr form) (nth 0 def) (nth 1 def))
(error "Not an `rx' form definition: %s" op)))))))
;; TODO: Additions to consider:
;; - A construct like `or' but without the match order guarantee,
;; maybe `unordered-or'. Useful for composition or generation of
;; alternatives; permits more effective use of regexp-opt.
(defun gdscript-rx--translate-symbol (sym)
"Translate the rx symbol SYM. Return (REGEXP . PRECEDENCE)."
(pcase sym
;; Use `list' instead of a quoted list to wrap the strings here,
;; since the return value may be mutated.
((or 'nonl 'not-newline 'any) (cons (list ".") t))
((or 'anychar 'anything) (cons (list "[^z-a]") t))
('unmatchable (gdscript-rx--empty))
((or 'bol 'line-start) (cons (list "^") 'lseq))
((or 'eol 'line-end) (cons (list "$") 'rseq))
((or 'bos 'string-start 'bot 'buffer-start) (cons (list "\\`") t))
((or 'eos 'string-end 'eot 'buffer-end) (cons (list "\\'") t))
('point (cons (list "\\=") t))
((or 'bow 'word-start) (cons (list "\\<") t))
((or 'eow 'word-end) (cons (list "\\>") t))
('word-boundary (cons (list "\\b") t))
('not-word-boundary (cons (list "\\B") t))
('symbol-start (cons (list "\\_<") t))
('symbol-end (cons (list "\\_>") t))
('not-wordchar (cons (list "\\W") t))
(_
(cond
((let ((class (cdr (assq sym gdscript-rx--char-classes))))
(and class (cons (list (concat "[[:" (symbol-name class) ":]]")) t))))
((let ((expanded (gdscript-rx--expand-def sym)))
(and expanded (gdscript-rx--translate expanded))))
;; For compatibility with old rx.
((let ((entry (assq sym gdscript-rx-constituents)))
(and (progn
(while (and entry (not (stringp (cdr entry))))
(setq entry
(if (symbolp (cdr entry))
;; Alias for another entry.
(assq (cdr entry) gdscript-rx-constituents)
;; Wrong type, try further down the list.
(assq (car entry)
(cdr (memq entry gdscript-rx-constituents))))))
entry)
(cons (list (cdr entry)) nil))))
(t (error "Unknown rx symbol `%s'" sym))))))
(defun gdscript-rx--enclose (left-str rexp right-str)
"Bracket REXP by LEFT-STR and RIGHT-STR."
(append (list left-str) rexp (list right-str)))
(defun gdscript-rx--bracket (rexp)
(gdscript-rx--enclose "\\(?:" rexp "\\)"))
(defun gdscript-rx--sequence (left right)
"Return the concatenation of LEFT and RIGHT, translated items.
Each item is of the form (REGEXP . PRECEDENCE), returning (REGEXP . PRECEDENCE)."
;; Concatenation rules:
;; seq ++ seq -> seq
;; lseq ++ seq -> lseq
;; seq ++ rseq -> rseq
;; lseq ++ rseq -> nil
(cond ((not (car left)) right)
((not (car right)) left)
(t
(let ((l (if (memq (cdr left) '(nil rseq))
(cons (gdscript-rx--bracket (car left)) t)
left))
(r (if (memq (cdr right) '(nil lseq))
(cons (gdscript-rx--bracket (car right)) t)
right)))
(cons (append (car l) (car r))
(if (eq (cdr l) 'lseq)
(if (eq (cdr r) 'rseq)
nil ; lseq ++ rseq
'lseq) ; lseq ++ seq
(if (eq (cdr r) 'rseq)
'rseq ; seq ++ rseq
'seq))))))) ; seq ++ seq
(defun gdscript-rx--translate-seq (body)
"Translate the sequence BODY of zero or more rx items.
Return (REGEXP . PRECEDENCE)."
(if body
(let* ((items (mapcar #'gdscript-rx--translate body))
(result (car items)))
(dolist (item (cdr items))
(setq result (gdscript-rx--sequence result item)))
result)
(cons nil 'seq)))
(defun gdscript-rx--empty ()
"Regexp that never match anything."
(cons (list "\\`a\\`") 'seq))
;; `cl-every' replacement to avoid bootstrapping problems.
(defun gdscript-rx--every (pred list)
"Whether PRED is true for every element of LIST."
(while (and list (funcall pred (car list)))
(setq list (cdr list)))
(null list))
(defun gdscript-rx--foldl (f x l)
"(F (F (F X L0) L1) L2) ...
Left-fold the list L, starting with X, by the binary function F."
(while l
(setq x (funcall f x (car l)))
(setq l (cdr l)))
x)
(defun gdscript-rx--translate-or (body)
"Translate the or-pattern BODY of zero or more rx items.
Return (REGEXP . PRECEDENCE)."
;; FIXME: Possible improvements:
;;
;; - Turn single characters to strings: (or ?a ?b) -> (or "a" "b"),
;; so that they can be candidates for regexp-opt.
;;
;; - Translate compile-time strings (`eval' forms), again for regexp-opt.
;;
;; - Flatten sub-patterns first: (or (or A B) (or C D)) -> (or A B C D)
;; in order to improve effectiveness of regexp-opt.
;; This would also help composability.
;;
;; - Use associativity to run regexp-opt on contiguous subsets of arguments
;; if not all of them are strings. Example:
;; (or (+ digit) "CHARLIE" "CHAN" (+ blank))
;; -> (or (+ digit) (or "CHARLIE" "CHAN") (+ blank))
;;
;; - Optimise single-character alternatives better:
;; * classes: space, alpha, ...
;; * (syntax S), for some S (whitespace, word)
;; so that (or "@" "%" digit (any "A-Z" space) (syntax word))
;; -> (any "@" "%" digit "A-Z" space word)
;; -> "[A-Z@%[:digit:][:space:][:word:]]"
;;
;; Problem: If a subpattern is carefully written to be
;; optimizable by regexp-opt, how do we prevent the transforms
;; above from destroying that property?
;; Example: (or "a" (or "abc" "abd" "abe"))
(cond
((null body) ; No items: a never-matching regexp.
(gdscript-rx--empty))
((null (cdr body)) ; Single item.
(gdscript-rx--translate (car body)))
((gdscript-rx--every #'stringp body) ; All strings.
(cons (list (regexp-opt body nil))
t))
((gdscript-rx--every #'gdscript-rx--charset-p body) ; All charsets.
(gdscript-rx--translate-union nil body))
(t
(cons (append (car (gdscript-rx--translate (car body)))
(mapcan (lambda (item)
(cons "\\|" (car (gdscript-rx--translate item))))
(cdr body)))
nil))))
(defun gdscript-rx--charset-p (form)
"Return t if FORM is like a charset.
A charset only consists of character intervals and set operations."
(or (and (consp form)
(or (and (memq (car form) '(any 'in 'char))
(gdscript-rx--every (lambda (x) (not (symbolp x))) (cdr form)))
(and (memq (car form) '(not or | intersection))
(gdscript-rx--every #'gdscript-rx--charset-p (cdr form)))))
(characterp form)
(and (stringp form) (= (length form) 1))
(and (or (symbolp form) (consp form))
(let ((expanded (gdscript-rx--expand-def form)))
(and expanded
(gdscript-rx--charset-p expanded))))))
(defun gdscript-rx--string-to-intervals (str)
"Decode STR as intervals.
A-Z becomes (?A . ?Z), and the single character X becomes (?X .
?X). Return the intervals in a list."
;; We could just do string-to-multibyte on the string and work with
;; that instead of this `decode-char' workaround.
(let ((decode-char
(if (multibyte-string-p str)
#'identity
#'unibyte-char-to-multibyte))
(len (length str))
(i 0)
(intervals nil))
(while (< i len)
(cond ((and (< i (- len 2))
(= (aref str (1+ i)) ?-))
;; Range.
(let ((start (funcall decode-char (aref str i)))
(end (funcall decode-char (aref str (+ i 2)))))
(cond ((and (<= start #x7f) (>= end #x3fff80))
;; Ranges between ASCII and raw bytes are split to
;; avoid having them absorb Unicode characters
;; caught in-between.
(push (cons start #x7f) intervals)
(push (cons #x3fff80 end) intervals))
((<= start end)
(push (cons start end) intervals))
(t
(error "Invalid rx `any' range: %s"
(substring str i 3))))
(setq i (+ i 3))))
(t
;; Single character.
(let ((char (funcall decode-char (aref str i))))
(push (cons char char) intervals))
(setq i (+ i 1)))))
intervals))
(defun gdscript-rx--condense-intervals (intervals)
"Merge adjacent and overlapping intervals by mutation, preserving the order.
INTERVALS is a list of (START . END) with START ≤ END, sorted by START."
(let ((tail intervals)
d)
(while (setq d (cdr tail))
(if (>= (cdar tail) (1- (caar d)))
(progn
(setcdr (car tail) (max (cdar tail) (cdar d)))
(setcdr tail (cdr d)))
(setq tail d)))
intervals))
(defun gdscript-rx--parse-any (body)
"Parse arguments of an (any ...) construct.
Return (INTERVALS . CLASSES), where INTERVALS is a sorted list of
disjoint intervals (each a cons of chars), and CLASSES
a list of named character classes in the order they occur in BODY."
(let ((classes nil)
(strings nil)
(conses nil))
;; Collect strings, conses and characters, and classes in separate bins.
(dolist (arg body)
(cond ((stringp arg)
(push arg strings))
((and (consp arg)
(characterp (car arg))
(characterp (cdr arg))
(<= (car arg) (cdr arg)))
;; Copy the cons, in case we need to modify it.
(push (cons (car arg) (cdr arg)) conses))
((characterp arg)
(push (cons arg arg) conses))
((and (symbolp arg)
(let ((class (cdr (assq arg gdscript-rx--char-classes))))
(and class
(or (memq class classes)
(progn (push class classes) t))))))
(t (error "Invalid rx `any' argument: %s" arg))))
(cons (gdscript-rx--condense-intervals
(sort (append conses
(mapcan #'gdscript-rx--string-to-intervals strings))
#'car-less-than-car))
(reverse classes))))
(defun gdscript-rx--generate-alt (negated intervals classes)
"Generate a character alternative. Return (REGEXP . PRECEDENCE).
If NEGATED is non-nil, negate the result; INTERVALS is a sorted
list of disjoint intervals and CLASSES a list of named character
classes."
(let ((items (append intervals classes)))
;; Move lone ] and range ]-x to the start.
(let ((rbrac-l (assq ?\] items)))
(when rbrac-l
(setq items (cons rbrac-l (delq rbrac-l items)))))
;; Split x-] and move the lone ] to the start.
(let ((rbrac-r (rassq ?\] items)))
(when (and rbrac-r (not (eq (car rbrac-r) ?\])))
(setcdr rbrac-r ?\\)
(setq items (cons '(?\] . ?\]) items))))
;; Split ,-- (which would end up as ,- otherwise).
(let ((dash-r (rassq ?- items)))
(when (eq (car dash-r) ?,)
(setcdr dash-r ?,)
(setq items (nconc items '((?- . ?-))))))
;; Remove - (lone or at start of interval)
(let ((dash-l (assq ?- items)))
(when dash-l
(if (eq (cdr dash-l) ?-)
(setq items (delq dash-l items)) ; Remove lone -
(setcar dash-l ?.)) ; Reduce --x to .-x
(setq items (nconc items '((?- . ?-))))))
;; Deal with leading ^ and range ^-x.
(when (and (consp (car items))
(eq (caar items) ?^)
(cdr items))
;; Move ^ and ^-x to second place.
(setq items (cons (cadr items)
(cons (car items) (cddr items)))))
(cond
;; Empty set: if negated, any char, otherwise match-nothing.
((null items)
(if negated
(gdscript-rx--translate-symbol 'anything)
(gdscript-rx--empty)))
;; Single non-negated character.
((and (null (cdr items))
(consp (car items))
(eq (caar items) (cdar items))
(not negated))
(cons (list (regexp-quote (char-to-string (caar items))))
t))
;; At least one character or class, possibly negated.
(t
(cons
(list
(concat
"["
(and negated "^")
(mapconcat (lambda (item)
(cond ((symbolp item)
(format "[:%s:]" item))
((eq (car item) (cdr item))
(char-to-string (car item)))
((eq (1+ (car item)) (cdr item))
(string (car item) (cdr item)))
(t
(string (car item) ?- (cdr item)))))
items nil)
"]"))
t)))))
(defun gdscript-rx--translate-any (negated body)
"Translate the (any ...) construct BODY. Return (REGEXP . PRECEDENCE).
If NEGATED, negate the sense."
(let ((parsed (gdscript-rx--parse-any body)))
(gdscript-rx--generate-alt negated (car parsed) (cdr parsed))))
(defun gdscript-rx--intervals-to-alt (negated intervals)
"Generate a character alternative from an interval set.
Return (REGEXP . PRECEDENCE).
INTERVALS is a sorted list of disjoint intervals.
If NEGATED, negate the sense."
;; Detect whether the interval set is better described in
;; complemented form. This is not just a matter of aesthetics: any
;; range from ASCII to raw bytes will automatically exclude the
;; entire non-ASCII Unicode range by the regexp engine.
(if (gdscript-rx--every (lambda (iv) (not (<= (car iv) #x3ffeff (cdr iv))))
intervals)
(gdscript-rx--generate-alt negated intervals nil)
(gdscript-rx--generate-alt
(not negated) (gdscript-rx--complement-intervals intervals) nil)))
;; FIXME: Consider turning `not' into a variadic operator, following SRE:
;; (not A B) = (not (or A B)) = (intersection (not A) (not B)), and
;; (not) = anychar.
;; Maybe allow singleton characters as arguments.
(defun gdscript-rx--translate-not (negated body)
"Translate the (not ...) construct BODY. Return (REGEXP . PRECEDENCE).
If NEGATED, negate the sense (thus making it positive)."
(unless (and body (null (cdr body)))
(error "The rx `not' form takes exactly one argument"))
(let ((arg (car body)))
(cond
((and (consp arg)
(pcase (car arg)
((or 'any 'in 'char)
(gdscript-rx--translate-any (not negated) (cdr arg)))
('syntax
(gdscript-rx--translate-syntax (not negated) (cdr arg)))
('category
(gdscript-rx--translate-category (not negated) (cdr arg)))
('not
(gdscript-rx--translate-not (not negated) (cdr arg)))
((or 'or '|)
(gdscript-rx--translate-union (not negated) (cdr arg)))
('intersection
(gdscript-rx--translate-intersection (not negated) (cdr arg))))))
((let ((class (cdr (assq arg gdscript-rx--char-classes))))
(and class
(gdscript-rx--generate-alt (not negated) nil (list class)))))
((eq arg 'word-boundary)
(gdscript-rx--translate-symbol
(if negated 'word-boundary 'not-word-boundary)))
((characterp arg)
(gdscript-rx--generate-alt (not negated) (list (cons arg arg)) nil))
((and (stringp arg) (= (length arg) 1))
(let ((char (string-to-char arg)))
(gdscript-rx--generate-alt (not negated) (list (cons char char)) nil)))
((let ((expanded (gdscript-rx--expand-def arg)))
(and expanded
(gdscript-rx--translate-not negated (list expanded)))))
(t (error "Illegal argument to rx `not': %S" arg)))))
(defun gdscript-rx--complement-intervals (intervals)
"Complement of the interval list INTERVALS."
(let ((compl nil)
(c 0))
(dolist (iv intervals)
(when (< c (car iv))
(push (cons c (1- (car iv))) compl))
(setq c (1+ (cdr iv))))
(when (< c (max-char))
(push (cons c (max-char)) compl))
(nreverse compl)))
(defun gdscript-rx--intersect-intervals (ivs-a ivs-b)
"Intersection of the interval lists IVS-A and IVS-B."
(let ((isect nil))
(while (and ivs-a ivs-b)
(let ((a (car ivs-a))
(b (car ivs-b)))
(cond
((< (cdr a) (car b)) (setq ivs-a (cdr ivs-a)))
((> (car a) (cdr b)) (setq ivs-b (cdr ivs-b)))
(t
(push (cons (max (car a) (car b))
(min (cdr a) (cdr b)))
isect)
(setq ivs-a (cdr ivs-a))
(setq ivs-b (cdr ivs-b))
(cond ((< (cdr a) (cdr b))
(push (cons (1+ (cdr a)) (cdr b))
ivs-b))
((> (cdr a) (cdr b))
(push (cons (1+ (cdr b)) (cdr a))
ivs-a)))))))
(nreverse isect)))
(defun gdscript-rx--union-intervals (ivs-a ivs-b)
"Union of the interval lists IVS-A and IVS-B."
(gdscript-rx--complement-intervals
(gdscript-rx--intersect-intervals
(gdscript-rx--complement-intervals ivs-a)
(gdscript-rx--complement-intervals ivs-b))))
(defun gdscript-rx--charset-intervals (charset)
"Return a sorted list of non-adjacent disjoint intervals from CHARSET.
CHARSET is any expression allowed in a character set expression:
characters, single-char strings, `any' forms (no classes permitted),
or `not', `or' or `intersection' forms whose arguments are charsets."
(pcase charset
(`(,(or 'any 'in 'char) . ,body)
(let ((parsed (gdscript-rx--parse-any body)))
(when (cdr parsed)
(error
"Character class not permitted in set operations: %S"
(cadr parsed)))
(car parsed)))
(`(not ,x) (gdscript-rx--complement-intervals (gdscript-rx--charset-intervals x)))
(`(,(or 'or '|) . ,body) (gdscript-rx--charset-union body))
(`(intersection . ,body) (gdscript-rx--charset-intersection body))
((pred characterp)
(list (cons charset charset)))
((guard (and (stringp charset) (= (length charset) 1)))
(let ((char (string-to-char charset)))
(list (cons char char))))
(_ (let ((expanded (gdscript-rx--expand-def charset)))
(if expanded
(gdscript-rx--charset-intervals expanded)
(error "Bad character set: %S" charset))))))
(defun gdscript-rx--charset-union (charsets)
"Union of CHARSETS, as a set of intervals."
(gdscript-rx--foldl #'gdscript-rx--union-intervals nil
(mapcar #'gdscript-rx--charset-intervals charsets)))
(defconst gdscript-rx--charset-all (list (cons 0 (max-char))))
(defun gdscript-rx--charset-intersection (charsets)
"Intersection of CHARSETS, as a set of intervals."
(gdscript-rx--foldl #'gdscript-rx--intersect-intervals gdscript-rx--charset-all
(mapcar #'gdscript-rx--charset-intervals charsets)))
(defun gdscript-rx--translate-union (negated body)
"Translate the (or ...) construct of charsets BODY.
Return (REGEXP . PRECEDENCE). If NEGATED, negate the sense."
(gdscript-rx--intervals-to-alt negated (gdscript-rx--charset-union body)))
(defun gdscript-rx--translate-intersection (negated body)
"Translate the (intersection ...) construct BODY.
Return (REGEXP . PRECEDENCE). If NEGATED, negate the sense."
(gdscript-rx--intervals-to-alt negated (gdscript-rx--charset-intersection body)))
(defun gdscript-rx--atomic-regexp (item)
"ITEM is (REGEXP . PRECEDENCE); return a regexp of precedence t."
(if (eq (cdr item) t)
(car item)
(gdscript-rx--bracket (car item))))
(defun gdscript-rx--translate-counted-repetition (min-count max-count body)
(let ((operand (gdscript-rx--translate-seq body)))
(if (car operand)
(cons (append
(gdscript-rx--atomic-regexp operand)
(list (concat "\\{"
(number-to-string min-count)
(cond ((null max-count) ",")
((< min-count max-count)
(concat "," (number-to-string max-count))))
"\\}")))
t)
operand)))
(defun gdscript-rx--check-repeat-arg (name min-args body)
(unless (>= (length body) min-args)
(error "The rx `%s' requires at least %d argument%s"
name min-args (if (= min-args 1) "" "s")))
;; There seems to be no reason to disallow zero counts.
(unless (natnump (car body))
(error "The rx `%s' first argument must be nonnegative" name)))
(defun gdscript-rx--translate-bounded-repetition (name body)
(let ((min-count (car body))
(max-count (cadr body))
(items (cddr body)))
(unless (and (natnump min-count)
(natnump max-count)
(<= min-count max-count))
(error "Range error `%s'" name))
(gdscript-rx--translate-counted-repetition min-count max-count items)))
(defun gdscript-rx--translate-repeat (body)
(gdscript-rx--check-repeat-arg 'repeat 2 body)
(if (= (length body) 2)
(gdscript-rx--translate-counted-repetition (car body) (car body) (cdr body))
(gdscript-rx--translate-bounded-repetition 'repeat body)))
(defun gdscript-rx--translate-** (body)
(gdscript-rx--check-repeat-arg '** 2 body)
(gdscript-rx--translate-bounded-repetition '** body))
(defun gdscript-rx--translate->= (body)
(gdscript-rx--check-repeat-arg '>= 1 body)
(gdscript-rx--translate-counted-repetition (car body) nil (cdr body)))
(defun gdscript-rx--translate-= (body)
(gdscript-rx--check-repeat-arg '= 1 body)
(gdscript-rx--translate-counted-repetition (car body) (car body) (cdr body)))
(defvar gdscript-rx--greedy t)
(defun gdscript-rx--translate-rep (op-string greedy body)
"Translate the repetition BODY; OP-STRING is one of \"*\", \"+\" or \"?\".
GREEDY is a boolean. Return (REGEXP . PRECEDENCE)."
(let ((operand (gdscript-rx--translate-seq body)))
(if (car operand)
(cons (append (gdscript-rx--atomic-regexp operand)
(list (concat op-string (unless greedy "?"))))
;; The result has precedence seq to avoid (? (* "a")) -> "a*?"
'seq)
operand)))
(defun gdscript-rx--control-greedy (greedy body)
"Translate the sequence BODY with greediness GREEDY.
Return (REGEXP . PRECEDENCE)."
(let ((gdscript-rx--greedy greedy))
(gdscript-rx--translate-seq body)))
(defun gdscript-rx--translate-group (body)
"Translate the `group' form BODY. Return (REGEXP . PRECEDENCE)."
(cons (gdscript-rx--enclose "\\("
(car (gdscript-rx--translate-seq body))
"\\)")
t))
(defun gdscript-rx--translate-group-n (body)
"Translate the `group-n' form BODY. Return (REGEXP . PRECEDENCE)."
(unless (and (integerp (car body)) (> (car body) 0))
(error "The rx `group-n' requires a positive number as first argument"))
(cons (gdscript-rx--enclose (concat "\\(?" (number-to-string (car body)) ":")
(car (gdscript-rx--translate-seq (cdr body)))
"\\)")
t))
(defun gdscript-rx--translate-backref (body)
"Translate the `backref' form BODY. Return (REGEXP . PRECEDENCE)."
(unless (and (= (length body) 1) (integerp (car body)) (<= 1 (car body) 9))
(error "The rx `backref' requires an argument in the range 1..9"))
(cons (list "\\" (number-to-string (car body))) t))
(defconst gdscript-rx--syntax-codes
'((whitespace . ?-) ; SPC also accepted
(punctuation . ?.)
(word . ?w) ; W also accepted
(symbol . ?_)
(open-parenthesis . ?\()
(close-parenthesis . ?\))
(expression-prefix . ?\')
(string-quote . ?\")
(paired-delimiter . ?$)
(escape . ?\\)
(character-quote . ?/)
(comment-start . ?<)
(comment-end . ?>)
(string-delimiter . ?|)
(comment-delimiter . ?!)))
(defun gdscript-rx--translate-syntax (negated body)
"Translate the `syntax' form BODY. Return (REGEXP . PRECEDENCE).
If NEGATED, inverse the effect."
(unless (and body (null (cdr body)))
(error "The rx `syntax' form takes exactly one argument"))
(let* ((sym (car body))
(syntax (cdr (assq sym gdscript-rx--syntax-codes))))
(unless syntax
(cond
;; Syntax character directly (sregex compatibility)
((and (characterp sym) (rassq sym gdscript-rx--syntax-codes))
(setq syntax sym))
;; Syntax character as symbol (sregex compatibility)
((symbolp sym)
(let ((name (symbol-name sym)))
(when (= (length name) 1)
(let ((char (string-to-char name)))
(when (rassq char gdscript-rx--syntax-codes)
(setq syntax char)))))))
(unless syntax
(error "Unknown rx syntax name `%s'" sym)))
(cons (list (string ?\\ (if negated ?S ?s) syntax))
t)))
(defconst gdscript-rx--categories
'((space-for-indent . ?\s)
(base . ?.)
(consonant . ?0)
(base-vowel . ?1)
(upper-diacritical-mark . ?2)
(lower-diacritical-mark . ?3)
(tone-mark . ?4)
(symbol . ?5)
(digit . ?6)
(vowel-modifying-diacritical-mark . ?7)
(vowel-sign . ?8)
(semivowel-lower . ?9)
(not-at-end-of-line . ?<)
(not-at-beginning-of-line . ?>)
(alpha-numeric-two-byte . ?A)
(chinese-two-byte . ?C)
(chinse-two-byte . ?C) ; A typo in Emacs 21.1-24.3.
(greek-two-byte . ?G)
(japanese-hiragana-two-byte . ?H)
(indian-two-byte . ?I)
(japanese-katakana-two-byte . ?K)
(strong-left-to-right . ?L)
(korean-hangul-two-byte . ?N)
(strong-right-to-left . ?R)
(cyrillic-two-byte . ?Y)
(combining-diacritic . ?^)
(ascii . ?a)
(arabic . ?b)
(chinese . ?c)
(ethiopic . ?e)
(greek . ?g)
(korean . ?h)
(indian . ?i)
(japanese . ?j)
(japanese-katakana . ?k)
(latin . ?l)
(lao . ?o)
(tibetan . ?q)
(japanese-roman . ?r)
(thai . ?t)
(vietnamese . ?v)
(hebrew . ?w)
(cyrillic . ?y)
(can-break . ?|)))
(defun gdscript-rx--translate-category (negated body)
"Translate the `category' form BODY. Return (REGEXP . PRECEDENCE).
If NEGATED, inverse the effect."
(unless (and body (null (cdr body)))
(error "The rx `category' form takes exactly one argument"))
(let* ((arg (car body))
(category
(cond ((symbolp arg)
(let ((cat (assq arg gdscript-rx--categories)))
(unless cat
(error "Unknown rx category `%s'" arg))
(cdr cat)))
((characterp arg) arg)
(t (error "Invalid rx `category' argument `%s'" arg)))))
(cons (list (string ?\\ (if negated ?C ?c) category))
t)))
(defvar gdscript-rx--delayed-evaluation nil
"Whether to allow certain forms to be evaluated at runtime.")
(defun gdscript-rx--translate-literal (body)
"Translate the `literal' form BODY. Return (REGEXP . PRECEDENCE)."
(unless (and body (null (cdr body)))
(error "The rx `literal' form takes exactly one argument"))
(let ((arg (car body)))
(cond ((stringp arg)
(cons (list (regexp-quote arg)) (if (= (length arg) 1) t 'seq)))
(gdscript-rx--delayed-evaluation
(cons (list (list 'regexp-quote arg)) 'seq))
(t (error "The rx `literal' form with non-string argument")))))
(defun gdscript-rx--translate-eval (body)
"Translate the `eval' form BODY. Return (REGEXP . PRECEDENCE)."
(unless (and body (null (cdr body)))
(error "The rx `eval' form takes exactly one argument"))
(gdscript-rx--translate (eval (car body))))
(defvar gdscript-rx--regexp-atomic-regexp nil)
(defun gdscript-rx--translate-regexp (body)
"Translate the `regexp' form BODY. Return (REGEXP . PRECEDENCE)."
(unless (and body (null (cdr body)))
(error "The rx `regexp' form takes exactly one argument"))
(let ((arg (car body)))
(cond ((stringp arg)
;; Generate the regexp when needed, since rx isn't
;; necessarily present in the byte-compilation environment.
(unless gdscript-rx--regexp-atomic-regexp
(setq gdscript-rx--regexp-atomic-regexp
;; Match atomic (precedence t) regexps: may give
;; false negatives but no false positives, assuming
;; the target string is syntactically correct.
(gdscript-rx-to-string
'(seq
bos
(or (seq "["
(opt "^")
(opt "]")
(* (or (seq "[:" (+ (any "a-z")) ":]")
(not (any "]"))))
"]")
anything
(seq "\\"
(or anything
(seq (any "sScC_") anything)
(seq "("
(* (or (not (any "\\"))
(seq "\\" (not (any ")")))))
"\\)"))))
eos)
t)))
(cons (list arg)
(if (string-match-p gdscript-rx--regexp-atomic-regexp arg) t nil)))
(gdscript-rx--delayed-evaluation
(cons (list arg) nil))
(t (error "The rx `regexp' form with non-string argument")))))
(defun gdscript-rx--translate-compat-form (def form)
"Translate a compatibility form from `gdscript-rx-constituents'.
DEF is the definition tuple. Return (REGEXP . PRECEDENCE)."
(let* ((fn (nth 0 def))
(min-args (nth 1 def))
(max-args (nth 2 def))
(predicate (nth 3 def))
(nargs (1- (length form))))
(when (< nargs min-args)
(error "The `%s' form takes at least %d argument(s)"
(car form) min-args))
(when (and max-args (> nargs max-args))
(error "The `%s' form takes at most %d argument(s)"
(car form) max-args))
(when (and predicate (not (gdscript-rx--every predicate (cdr form))))
(error "The `%s' form requires arguments satisfying `%s'"
(car form) predicate))
(let ((regexp (funcall fn form)))
(unless (stringp regexp)
(error "The `%s' form did not expand to a string" (car form)))
(cons (list regexp) nil))))
(defun gdscript-rx--substitute (bindings form)
"Substitute BINDINGS in FORM. BINDINGS is an alist of (NAME . VALUES)
where VALUES is a list to splice into FORM wherever NAME occurs.
Return the substitution result wrapped in a list, since a single value
can expand to any number of values."
(cond ((symbolp form)
(let ((binding (assq form bindings)))
(if binding
(cdr binding)
(list form))))
((consp form)
(if (listp (cdr form))
;; Proper list. We substitute variables even in the head
;; position -- who knows, might be handy one day.
(list (mapcan (lambda (x) (copy-sequence
(gdscript-rx--substitute bindings x)))
form))
;; Cons pair (presumably an interval).
(let ((first (gdscript-rx--substitute bindings (car form)))
(second (gdscript-rx--substitute bindings (cdr form))))
(if (and first (not (cdr first))
second (not (cdr second)))
(list (cons (car first) (car second)))
(error
"Cannot substitute a &rest parameter into a dotted pair")))))
(t (list form))))
;; FIXME: Consider adding extensions in Lisp macro style, where
;; arguments are passed unevaluated to code that returns the rx form
;; to use. Example:
;;
;; (gdscript-rx-let ((radix-digit (radix)
;; :lisp (list 'any (cons ?0 (+ ?0 (eval radix) -1)))))
;; (rx (radix-digit (+ 5 3))))
;; =>
;; "[0-7]"
;;
;; While this would permit more powerful extensions, it's unclear just
;; how often they would be used in practice. Let's wait until there is
;; demand for it.
;; FIXME: An alternative binding syntax would be
;;
;; (NAME RXs...)
;; and
;; ((NAME ARGS...) RXs...)
;;
;; which would have two minor advantages: multiple RXs with implicit
;; `seq' in the definition, and the arglist is no longer an optional
;; element in the middle of the list. On the other hand, it's less
;; like traditional lisp arglist constructs (defun, defmacro).
;; Since it's a Scheme-like syntax, &rest parameters could be done using
;; dotted lists:
;; (gdscript-rx-let (((name arg1 arg2 . rest) ...definition...)) ...)
(defun gdscript-rx--expand-template (op values arglist template)
"Return TEMPLATE with variables in ARGLIST replaced with VALUES."
(let ((bindings nil)
(value-tail values)
(formals arglist))
(while formals
(pcase (car formals)
('&rest
(unless (cdr formals)
(error
"Expanding rx def `%s': missing &rest parameter name" op))
(push (cons (cadr formals) value-tail) bindings)
(setq formals nil)
(setq value-tail nil))
(name
(unless value-tail
(error
"Expanding rx def `%s': too few arguments (got %d, need %s%d)"
op (length values)
(if (memq '&rest arglist) "at least " "")