-
Notifications
You must be signed in to change notification settings - Fork 2
/
relint.el
2881 lines (2675 loc) · 117 KB
/
relint.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
;;; relint.el --- Elisp regexp mistake finder -*- lexical-binding: t -*-
;; Copyright (C) 2019-2024 Free Software Foundation, Inc.
;; Author: Mattias Engdegård <[email protected]>
;; Version: 2.1
;; Package-Requires: ((xr "2.0") (emacs "27.1"))
;; URL: https://github.com/mattiase/relint
;; 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:
;; Relint scans elisp files for regexps and reports potential errors,
;; including deprecated syntax and bad practice. See the README file
;; for more information.
;;; Code:
(require 'xr)
(require 'compile)
(require 'cl-lib)
(require 'subr-x)
(defcustom relint-xr-checks nil
"Extra checks to be performed by `xr' for each regexp.
This is the CHECKS argument passed to `xr-lint' (q.v.).
It is either nil, meaning the standard set of checks with minimal
false positives, or `all', enabling all checks."
:group 'relint
:type '(choice (const :tag "Standard checks only" nil)
(const :tag "All checks" all)))
(defface relint-buffer-highlight
'((t :inherit highlight))
"Face for highlighting the string part warned about in the `*relint*' buffer."
:group 'relint)
;; FIXME: default to underline or reverse? Or `caret' if stdout is non-tty?
(defcustom relint-batch-highlight '("\e[7m" . "\e[m")
"How to emphasise part of a string warned about in batch output.
The value is one of the following:
A pair of strings for turning on and off highlighting in
the terminal; these are typically escape sequences.
`caret', which adds an ASCII caret on the line under the string.
`nil', which disables highlighting.
The default value produces reverse video in a VT100-compatible terminal.
In interactive mode, relint uses the `relint-buffer-highlight' face instead."
:group 'relint
:type '(choice
(const :tag "Terminal reverse" ("\e[7m" . "\e[m"))
(const :tag "Terminal underline" ("\e[4m" . "\e[m"))
(cons :tag "Escape sequences"
(string :tag "Sequence for turning highlighting on" "\e[7m")
(string :tag "Sequence for turning highlighting off" "\e[m"))
(const :tag "ASCII caret" caret)
(const :tag "Highlighting disabled" nil)))
(defvar relint--force-batch-output nil) ; for testing only
(cl-defstruct (relint-diag
(:constructor nil)
(:constructor
relint--make-diag (message beg-pos end-pos pos-type
string beg-idx end-idx severity))
(:copier nil)
(:type vector))
message ; string of message
beg-pos ; first buffer position
end-pos ; last buffer position, or nil if only the start available
pos-type ; `string' if buffer at BEG-POS..END-POS is inside a string literal
; corresponding to STRING at BEG-IDX..END-IDX;
; any other value means that BEG-POS..END-POS just point to code
string ; string inside which the complaint occurs, or nil
beg-idx ; first index into STRING, or nil
end-idx ; last index into STRING, or nil
severity ; `error', `warning' or `info'
)
(defun relint--get-error-buffer ()
"Buffer to which errors are printed, or nil if noninteractive."
(and (not noninteractive)
(let ((buf (get-buffer-create "*relint*")))
(with-current-buffer buf
(unless (eq major-mode 'relint-mode)
(relint-mode))
(let ((inhibit-read-only t))
(compilation-forget-errors)
(erase-buffer)))
buf)))
(defun relint--add-to-error-buffer (error-buffer string)
(with-current-buffer error-buffer
(goto-char (point-max))
(let ((inhibit-read-only t))
(insert string))))
(defun relint--skip-whitespace ()
(when (looking-at (rx (1+ (or blank "\n" "\f"
(seq ";" (0+ nonl))))))
(goto-char (match-end 0))))
(defun relint--follow-path (path)
"Move point forward along PATH (reversed list of list indices
to follow to target).
For example, if point is before the form (A B (C ((D E F G))))
and PATH is (3 0 1 2), then the returned position is right before G."
(let ((p (reverse path)))
(while p
(relint--skip-whitespace)
(let ((skip (car p)))
;; Enter next sexp and skip past the `skip' first sexps inside.
(when (looking-at (rx "."))
;; Skip `. (' since it represents zero sexps.
(forward-char)
(relint--skip-whitespace)
(when (looking-at (rx "("))
(forward-char)
(relint--skip-whitespace)))
(cond
((looking-at (rx (or "'" "#'" "`" ",@" ",")))
(goto-char (match-end 0))
(setq skip (1- skip)))
((looking-at (rx "("))
(forward-char 1)))
(while (> skip 0)
(relint--skip-whitespace)
(if (looking-at (rx "."))
(progn
(goto-char (match-end 0))
(relint--skip-whitespace)
(cond
((looking-at (rx (or "'" "#'" "`" ",@" ",")))
;; Sugar after dot represents one sexp.
(goto-char (match-end 0))
(setq skip (1- skip)))
((looking-at (rx "("))
;; `. (' represents zero sexps.
(goto-char (match-end 0)))))
(forward-sexp)
(setq skip (1- skip)))))
(setq p (cdr p))))
(relint--skip-whitespace)
(when (looking-at (rx "."))
(forward-char)
(relint--skip-whitespace)))
(defun relint--pos-from-start-pos-path (start-pos path)
"Compute position from START-POS and PATH (reversed list of
list indices to follow to target)."
(save-excursion
(goto-char start-pos)
(relint--follow-path path)
(point)))
(defun relint--literal-string-pos (string-pos n)
"Position of character N in a literal string at STRING-POS."
(save-excursion
(goto-char (1+ string-pos)) ; Skip first double quote.
(dotimes (_ n)
;; Match a single character in a string. Since we already read it,
;; we know that it's well-formed.
(looking-at
(rx (* ?\\ (any " \n")) ; Skip escaped space and newline.
(or (not (any ?\\)) ; Unescaped char.
(seq ?\\
(or (** 1 3 (any "0-7")) ; Octal.
(seq ?x (+ (any "0-9A-Fa-f"))) ; Hex.
(seq ?u (= 4 (any "0-9A-Fa-f"))) ; Unicode.
(seq ?U (= 8 (any "0-9A-Fa-f"))) ; Unicode.
(seq "N{" (+ (not (any "}"))) "}") ; Named.
(seq (any "CMS") "-" anything) ; Keystroke.
anything)))))
(goto-char (match-end 0)))
(point)))
(defun relint--string-pos (pos n endp)
"Position of character N in a string expression at POS,
or nil if no position could be determined.
If ENDP is true, use the last position of the character, otherwise the first,
in case it occupies more than one position in the buffer."
(save-excursion
(goto-char pos)
(pcase (read (current-buffer))
((pred stringp)
(if endp
(1- (relint--literal-string-pos pos (1+ n)))
(relint--literal-string-pos pos n)))
(`(concat . ,args)
;; Find out in which argument the sought position is.
(let ((index 1))
(while (and args (stringp (car args)) (>= n (length (car args))))
(setq n (- n (length (car args))))
(setq index (1+ index))
(setq args (cdr args)))
(and args (stringp (car args))
(let ((string-pos
(relint--pos-from-start-pos-path pos (list index))))
(if endp
(1- (relint--literal-string-pos string-pos (1+ n)))
(relint--literal-string-pos string-pos n)))))))))
(defun relint--suppression (pos message)
"Whether there is a suppression for MESSAGE at POS."
(save-excursion
;; On a preceding line, look for a comment on the form
;;
;; relint suppression: REGEXP
;;
;; where REGEXP matches MESSAGE. There can be
;; multiple suppression lines preceding a line of code with
;; several errors.
(goto-char pos)
(forward-line -1)
(let ((matched nil))
(while (and
(not (setq matched
(and
(looking-at (rx (0+ blank) (1+ ";") (0+ blank)
"relint suppression:" (1+ blank)
(group (0+ nonl)
(not (any "\n" blank)))))
(let ((regexp (match-string 1)))
(string-match-p regexp message)))))
(looking-at (rx bol
(0+ blank) (opt ";" (0+ nonl))
eol))
(not (bobp)))
(forward-line -1))
matched)))
(defun relint--output-message (error-buffer string)
(if error-buffer
(relint--add-to-error-buffer error-buffer (concat string "\n"))
(message "%s" string)))
(defun relint--col-at-pos (pos)
(save-excursion
(goto-char pos)
(1+ (current-column))))
(defun relint--output-complaint (error-buffer file diag)
(let* ((str (relint-diag-string diag))
(beg-idx (relint-diag-beg-idx diag))
(end-idx (relint-diag-end-idx diag))
(severity (relint-diag-severity diag))
(beg (relint-diag-beg-pos diag))
(end (relint-diag-end-pos diag))
(beg-line (line-number-at-pos beg t))
(end-line (cond ((eq beg end) beg-line)
(end (line-number-at-pos end t))))
(beg-col (relint--col-at-pos beg))
(end-col (cond ((eq beg end) beg-col)
(end (relint--col-at-pos end))))
(loc-str (cond
((and end-line (< beg-line end-line))
(format "%d.%d-%d.%d" beg-line beg-col end-line end-col))
(end-col
(format "%d:%d-%d" beg-line beg-col end-col))
(t
(format "%d:%d" beg-line beg-col))))
(quoted-str (and str (relint--quote-string str)))
(caret-str nil))
(when beg-idx
(let* ((bounds (relint--caret-bounds str beg-idx end-idx))
;; Indices into quoted-str, which includes double quotes:
(beg-qs (+ (car bounds) 1))
(end-qs (+ (cdr bounds) 2))) ; exclusive
(cond ((and error-buffer (not relint--force-batch-output))
;; Output to buffer: apply highlight face to part of string.
(put-text-property
beg-qs end-qs 'font-lock-face 'relint-buffer-highlight
quoted-str))
((eq relint-batch-highlight 'caret)
(let* ((col-from (car bounds))
(col-to (cdr bounds)))
(setq caret-str (concat
(make-string col-from ?.)
(make-string (- col-to col-from -1) ?^)))))
((consp relint-batch-highlight)
(setq quoted-str
(concat (substring quoted-str 0 beg-qs)
(car relint-batch-highlight)
(substring quoted-str beg-qs end-qs)
(cdr relint-batch-highlight)
(substring quoted-str end-qs)))))))
(relint--output-message
error-buffer
(concat
(format "%s:%s: " file loc-str)
(cond ((eq severity 'error) "error: ")
((eq severity 'info) "info: "))
(relint-diag-message diag)
(cond ((and beg-idx end-idx (< beg-idx end-idx))
(format " (pos %d..%d)" beg-idx end-idx))
(beg-idx (format " (pos %d)" beg-idx)))
(and quoted-str (format "\n %s" quoted-str))
(and caret-str (format "\n %s" caret-str))))))
(defun relint--output-complaints (buffer file complaints error-buffer)
(with-current-buffer buffer
(dolist (group complaints)
(dolist (complaint group)
(relint--output-complaint error-buffer file complaint)))))
(defvar relint--suppression-count)
(defvar relint--complaints
;; list of lists of `relint-diag' objects
)
(defun relint--report-group (group)
(let ((diag (car group)))
(if (relint--suppression (relint-diag-beg-pos diag)
(relint-diag-message diag))
(setq relint--suppression-count (1+ relint--suppression-count))
(push group relint--complaints))))
(defun relint--report-nonstring (message beg-pos end-pos severity)
(relint--report-group
(list (relint--make-diag message beg-pos end-pos nil nil nil nil severity))))
(defun relint--diag-on-string (expr-pos string message beg-idx end-idx severity)
(let* ((beg-pos (and beg-idx (relint--string-pos expr-pos beg-idx nil)))
(end-pos (and end-idx (relint--string-pos expr-pos end-idx t))))
(relint--make-diag message (or beg-pos expr-pos) end-pos
(and beg-pos end-pos 'string)
string beg-idx end-idx severity)))
(defun relint--report-at-path (start-pos path msg str beg-idx end-idx severity)
(let ((expr-pos (relint--pos-from-start-pos-path start-pos path)))
(relint--report-group
(list (relint--diag-on-string
expr-pos str msg beg-idx end-idx severity)))))
;; FIXME: if all we have is the start of a Lisp sexp, it should be easy to
;; find where it ends!
(defun relint--warn-at-pos (beg-pos end-pos message)
(relint--report-nonstring message beg-pos end-pos 'warning))
(defun relint--warn (start-pos path message &optional str str-beg str-end)
(relint--report-at-path start-pos path message str str-beg str-end 'warning))
(defun relint--err-at-pos (pos message)
(relint--report-nonstring message pos nil 'error))
(defun relint--escape-string (str escape-printable)
(replace-regexp-in-string
(rx (any cntrl ?\177 (#x3fff80 . #x3fffff) ?\\ ?\"))
(lambda (s)
(let ((c (logand (string-to-char s) #xff)))
(or (cdr (assq c '((?\b . "\\b")
(?\t . "\\t")
(?\n . "\\n")
(?\v . "\\v")
(?\f . "\\f")
(?\r . "\\r")
(?\e . "\\e"))))
(if (memq c '(?\\ ?\"))
(if escape-printable (string ?\\ c) (string c))
(format "\\%03o" c)))))
str t t))
(defun relint--quote-string (str)
(concat "\"" (relint--escape-string str t) "\""))
(defun relint--caret-bounds (string beg end)
(let* ((beg-col
(length (relint--escape-string (substring string 0 beg) t)))
(end-col
(if end
;; handle escaped chars such as \n
(1- (length (relint--escape-string
(substring string 0 (1+ end)) t)))
beg-col)))
(cons beg-col end-col)))
(defun relint--expand-name (name)
(pcase-exhaustive name
(`(call-to . ,x) (format "call to %s" x))
(`(parameter . ,x) (format "%s parameter" x))
(`(at ,x ,y) (format "%s (%s)" x y))
((pred stringp) name)
((pred symbolp) (symbol-name name))))
(defun relint--message-with-context (msg name)
(format "In %s: %s" (relint--expand-name name) msg))
(defun relint--string-complaints (complaints string name start-pos path)
(when complaints
(let ((expr-pos (relint--pos-from-start-pos-path start-pos path)))
(dolist (cg complaints)
(relint--report-group
(mapcar (lambda (c)
(let* ((beg (nth 0 c))
(end (nth 1 c))
(msg (nth 2 c))
(severity (nth 3 c))
;; Only use message-with-context for non-info diags
(message (if (eq severity 'info)
msg
(relint--message-with-context msg name))))
(relint--diag-on-string expr-pos string
message beg end severity)))
cg))))))
(defun relint--check-skip-set (skip-set name pos path)
(relint--string-complaints (xr-skip-set-lint skip-set)
skip-set name pos path))
(defun relint--check-re-string (re name pos path)
(relint--string-complaints (xr-lint re nil relint-xr-checks)
re name pos path))
(defun relint--check-file-re-string (re name pos path)
(relint--string-complaints (xr-lint re 'file relint-xr-checks)
re name pos path))
(defun relint--check-syntax-string (syntax name pos path)
(relint--string-complaints (relint--syntax-string-lint syntax)
syntax name pos path))
(defconst relint--syntax-codes
'((?- . 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 relint--syntax-string-lint (syntax)
"Check the syntax-skip string SYNTAX.
Return list of complaint groups, each a list of (BEG END MESSAGE SEVERITY)."
(let ((errs nil)
(start (if (string-prefix-p "^" syntax) 1 0)))
(when (member syntax '("" "^"))
(push (list start nil "Empty syntax string" 'warning) errs))
(let ((seen nil))
(dolist (i (number-sequence start (1- (length syntax))))
(let* ((c (aref syntax i))
(sym (cdr (assq c relint--syntax-codes))))
(if sym
(if (memq sym seen)
(push (list (list i i
(relint--escape-string
(format-message
"Duplicated syntax code `%c'" c)
nil)
'warning))
errs)
(push sym seen))
(push (list (list i i
(relint--escape-string
(format-message
"Invalid char `%c' in syntax string" c)
nil)
'warning))
errs)))))
(nreverse errs)))
(defvar relint--variables nil
"Alist of global variable definitions.
Each element is either (NAME expr EXPR), for unevaluated expressions,
or (NAME val VAL), for values.")
;; List of variables that have been checked, so that we can avoid
;; checking direct uses of it.
(defvar relint--checked-variables)
;; Alist of functions taking regexp argument(s).
;; The names map to a list of the regexp argument indices.
(defvar relint--regexp-functions)
;; List of functions defined in the current file, each element on the
;; form (FUNCTION ARGS BODY), where ARGS is the lambda list and BODY
;; its body expression list.
(defvar relint--function-defs)
;; List of macros defined in the current file, each element on the
;; form (MACRO ARGS BODY), where ARGS is the lambda list and BODY its
;; body expression list.
(defvar relint--macro-defs)
;; Alist of alias definitions in the current file.
(defvar relint--alias-defs)
;; Alist of local variables. Each element is either (NAME VALUE),
;; where VALUE is the (evaluated) value, or just (NAME) if the binding
;; exists but the value is unknown.
(defvar relint--locals)
(defvar relint--eval-mutables nil
"List of local variables mutable in the current evaluation context.")
(eval-and-compile
(defconst relint--safe-functions
'(cons list append
concat
car cdr caar cadr cdar cddr car-safe cdr-safe nth nthcdr
caaar cdaar cadar cddar caadr cdadr caddr cdddr
format format-message
regexp-quote regexp-opt regexp-opt-charset regexp-opt-depth
reverse
member memq memql remove remq member-ignore-case
assoc assq rassoc rassq assoc-string
identity
string make-string make-list
substring substring-no-properties
length safe-length
symbol-name gensym
intern intern-soft make-symbol
null not xor
eq eql equal
string-equal string= string< string-lessp string> string-greaterp
compare-strings
char-equal string-match-p
string-match split-string
wildcard-to-regexp
combine-and-quote-strings split-string-and-unquote
string-to-multibyte string-as-multibyte string-to-unibyte string-as-unibyte
string-join string-trim-left string-trim-right string-trim
string-prefix-p string-suffix-p
string-blank-p string-remove-prefix string-remove-suffix
string-search string-replace
vector aref elt vconcat
char-to-string string-to-char
number-to-string string-to-number int-to-string
string-to-list string-to-vector string-or-null-p string-bytes
upcase downcase capitalize
purecopy copy-sequence copy-alist copy-tree
flatten-tree
member-ignore-case
last butlast number-sequence take
plist-get plist-member
1value
consp atom stringp symbolp listp nlistp booleanp keywordp
integerp numberp natnump fixnump bignump characterp zerop floatp
sequencep vectorp arrayp type-of
+ - * / % mod 1+ 1- max min < <= = > >= /= abs expt sqrt
ash lsh logand logior logxor lognot logb logcount
floor ceiling round truncate float
cl--block-wrapper ; alias for `identity'
)
"Functions that are safe to call during evaluation.
Except for altering the match state, these are side-effect-free
and reasonably pure (some depend on variables in fairly uninteresting ways,
like `case-fold-search').
More functions could be added if there is evidence that it would
help in evaluating more regexp strings.")
)
(defconst relint--safe-alternatives
'((nconc . append)
(delete . remove)
(delq . remq)
(nreverse . reverse)
(nbutlast . butlast)
(ntake . take))
"Alist mapping non-safe functions to semantically equivalent safe
alternatives.")
(defconst relint--safe-cl-alternatives
'((cl-delete-duplicates . cl-remove-duplicates)
(cl-delete . cl-remove)
(cl-delete-if . cl-remove-if)
(cl-delete-if-not . cl-remove-if-not)
(cl-nsubstitute . cl-substitute)
(cl-nunion . cl-union)
(cl-nintersection . cl-intersection)
(cl-nset-difference . cl-set-difference)
(cl-nset-exclusive-or . cl-set-exclusive-or)
(cl-nsublis . cl-sublis))
"Alist mapping non-safe cl functions to semantically equivalent safe
alternatives. They may still require wrapping their function arguments.")
(defun relint--rx-safe (rx)
"Return RX safe to translate; throw `relint-eval' `no-value' if not."
(cond
((atom rx) rx)
;; These cannot contain rx subforms.
((memq (car rx) '(any in char not-char not backref
syntax not-syntax category))
rx)
;; We ignore the differences in evaluation time between `eval' and
;; `regexp', and just use what environment we have.
((eq (car rx) 'eval)
(let ((arg (relint--eval (cadr rx))))
;; For safety, make sure the result isn't another evaluating form.
(when (and (consp arg)
(memq (car arg) '(literal eval regexp regex)))
(throw 'relint-eval 'no-value))
arg))
((memq (car rx) '(literal regexp regex))
(let ((arg (relint--eval (cadr rx))))
(if (stringp arg)
(list (car rx) arg)
(throw 'relint-eval 'no-value))))
(t (cons (car rx) (mapcar #'relint--rx-safe (cdr rx))))))
(defun relint--eval-rx (args)
"Evaluate an `rx-to-string' expression."
(let ((safe-args (cons (relint--rx-safe (car args))
(cdr args))))
(condition-case nil
(apply #'rx-to-string safe-args)
(error (throw 'relint-eval 'no-value)))))
(defun relint--apply (formals actuals body)
"Bind FORMALS to ACTUALS and evaluate BODY."
(let ((bindings nil))
(while formals
(cond
((eq (car formals) '&rest)
(push (cons (cadr formals) (list actuals)) bindings)
(setq formals nil))
((eq (car formals) '&optional)
(setq formals (cdr formals)))
(t
(push (cons (car formals) (list (car actuals))) bindings)
(setq formals (cdr formals))
(setq actuals (cdr actuals)))))
;; This results in dynamic binding, but that doesn't matter for our
;; purposes.
(let ((relint--locals (append bindings relint--locals))
(relint--eval-mutables (append (mapcar #'car bindings)
relint--eval-mutables)))
(relint--eval-body body))))
(defun relint--no-value (&rest _)
"A function that fails when called."
(throw 'relint-eval 'no-value))
(defun relint--wrap-function (form)
"Transform an evaluated function (typically a symbol or lambda expr)
into something that can be called safely."
(cond
((symbolp form)
(if (memq form relint--safe-functions)
form
(or (cdr (assq form relint--safe-alternatives))
(let ((def (cdr (assq form relint--function-defs))))
(if def
(let ((formals (car def))
(body (cadr def)))
(lambda (&rest args)
(relint--apply formals args body)))
'relint--no-value)))))
((and (consp form) (eq (car form) 'lambda))
(let ((formals (cadr form))
(body (cddr form)))
(lambda (&rest args)
(relint--apply formals args body))))
(t 'relint--no-value)))
(defun relint--wrap-cl-keyword-args (args)
"Wrap the function arguments :test, :test-not, :key in ARGS."
(let ((test (plist-get args :test))
(test-not (plist-get args :test-not))
(key (plist-get args :key))
(ret (copy-sequence args)))
(when test
(plist-put ret :test (relint--wrap-function test)))
(when test-not
(plist-put ret :test-not (relint--wrap-function test-not)))
(when key
(plist-put ret :key (relint--wrap-function key)))
ret))
(defun relint--eval-to-binding (form)
"Evaluate a form, returning (VALUE) on success or nil on failure."
(let ((val (catch 'relint-eval
(list (relint--eval form)))))
(if (eq val 'no-value) nil val)))
(defun relint--eval-body (body)
"Evaluate a list of forms; return result of last form."
(if (consp body)
(progn
(while (consp (cdr body))
(relint--eval (car body))
(setq body (cdr body)))
(if (cdr body)
(throw 'relint-eval 'no-value)
(relint--eval (car body))))
(if body
(throw 'relint-eval 'no-value)
nil)))
(defalias 'relint--take
(if (fboundp 'take)
#'take
(lambda (n list)
(cl-loop repeat n for x in list collect x))))
(defalias 'relint--proper-list-p
(if (fboundp 'proper-list-p)
#'proper-list-p
(lambda (x)
(and (listp x) (ignore-errors (length x))))))
(defun relint--eval (form)
"Evaluate a form. Throw `relint-eval' `no-value' if something could
not be evaluated safely."
(if (atom form)
(cond
((booleanp form) form)
((keywordp form) form)
((symbolp form)
(let ((local (assq form relint--locals)))
(if local
(if (cdr local)
(cadr local)
(throw 'relint-eval 'no-value))
(let ((binding (assq form relint--variables)))
(if binding
(if (eq (cadr binding) 'val)
(caddr binding)
(let ((val (relint--eval (caddr binding))))
(setcdr binding (list 'val val))
val))
(throw 'relint-eval 'no-value))))))
(t form))
(let ((head (car form))
(body (cdr form)))
(cond
((eq head 'quote)
(if (and (consp (car body))
(eq (caar body) '\,)) ; In case we are inside a backquote.
(throw 'relint-eval 'no-value)
(car body)))
((memq head '(function cl-function))
;; Treat cl-function like plain function (close enough).
(car body))
((eq head 'lambda)
form)
;; Functions considered safe.
((memq head (eval-when-compile relint--safe-functions))
(let ((args (mapcar #'relint--eval body)))
;; Catching all errors isn't wonderful, but sometimes a global
;; variable argument has an unsuitable default value which is
;; supposed to have been changed at the expression point.
(condition-case nil
(apply head args)
(error (throw 'relint-eval 'no-value)))))
;; replace-regexp-in-string: wrap the rep argument if it's a function.
((eq head 'replace-regexp-in-string)
(let ((all-args (mapcar #'relint--eval body)))
(let* ((rep-arg (cadr all-args))
(rep (if (stringp rep-arg)
rep-arg
(relint--wrap-function rep-arg)))
(args (append (list (car all-args) rep) (cddr all-args))))
(condition-case nil
(apply head args)
(error (throw 'relint-eval 'no-value))))))
;; alist-get: wrap the optional fifth argument (testfn).
((eq head 'alist-get)
(let* ((all-args (mapcar #'relint--eval body))
(testfn (nth 4 all-args))
(args (if testfn
(append (relint--take 4 all-args)
(list (relint--wrap-function testfn)))
all-args)))
(condition-case nil
(apply head args)
(error (throw 'relint-eval 'no-value)))))
((eq head 'if)
(let ((condition (relint--eval (car body))))
(let ((then-part (nth 1 body))
(else-tail (nthcdr 2 body)))
(cond (condition
(relint--eval then-part))
(else-tail
(relint--eval-body else-tail))))))
((eq head 'and)
(if body
(let ((val (relint--eval (car body))))
(if (and val (cdr body))
(relint--eval (cons 'and (cdr body)))
val))
t))
((eq head 'or)
(if body
(let ((val (relint--eval (car body))))
(if (and (not val) (cdr body))
(relint--eval (cons 'or (cdr body)))
val))
nil))
((eq head 'cond)
(and body
(let ((clause (car body)))
(if (consp clause)
(let ((val (relint--eval (car clause))))
(if val
(if (cdr clause)
(relint--eval-body (cdr clause))
val)
(relint--eval (cons 'cond (cdr body)))))
;; Syntax error
(throw 'relint-eval 'no-value)))))
((memq head '(progn ignore-errors eval-when-compile eval-and-compile
with-no-warnings))
(relint--eval-body body))
;; Hand-written implementation of `cl-assert' -- good enough.
((eq head 'cl-assert)
(unless (relint--eval (car body))
(throw 'relint-eval 'no-value)))
((eq head 'prog1)
(let ((val (relint--eval (car body))))
(relint--eval-body (cdr body))
val))
((eq head 'prog2)
(relint--eval (car body))
(let ((val (relint--eval (cadr body))))
(relint--eval-body (cddr body))
val))
;; delete-dups: Work on a copy of the argument.
((eq head 'delete-dups)
(let ((arg (relint--eval (car body))))
(delete-dups (copy-sequence arg))))
;; `cl-flet', `cl-flet*' and `cl-labels': these macroexpand their bodies
;; eagerly which would be unsafe, so instead we transform them into
;; `let' etc, as if it were a Lisp-1. Calls to local functions are then
;; transformed as we encounter them.
((memq head '(cl-flet cl-flet* cl-labels))
(let ((f (cdr (assq head '((cl-flet . let)
(cl-flet* . let*)
(cl-labels . letrec)))))
(bindings (mapcar (lambda (b)
(if (and (consp b)
(symbolp (car b))
(> (length b) 2))
`(,(car b)
(lambda ,(cadr b) ,@(cddr b)))
b))
(car body))))
(relint--eval `(,f ,bindings ,@(cdr body)))))
;; Safe macros that expand to pure code, and their auxiliary macros.
;; FIXME: Is this safe?
((memq head '(when unless
\` backquote-list*
letrec
cl-case cl-block cl-loop))
(relint--eval
;; Suppress any warning message arising from macro-expansion;
;; it will just confuse the user and we can't give a good location.
(let ((inhibit-message t))
(macroexpand-1 form))))
;; catch: as long as nobody throws, this naïve code is fine.
((eq head 'catch)
(relint--eval-body (cdr body)))
;; condition-case: as long as there is no error...
((eq head 'condition-case)
(relint--eval (cadr body)))
;; Functions taking a function as first argument.
((memq head '(apply funcall mapconcat
cl-some cl-every cl-notany cl-notevery))
(let ((fun (relint--wrap-function (relint--eval (car body))))
(args (mapcar #'relint--eval (cdr body))))
(condition-case nil
(apply head fun args)
(error (throw 'relint-eval 'no-value)))))
;; Functions with functions as keyword arguments :test, :test-not, :key
((memq head '(cl-remove-duplicates cl-remove cl-substitute cl-member
cl-find cl-position cl-count cl-mismatch cl-search
cl-union cl-intersection cl-set-difference
cl-set-exclusive-or cl-subsetp
cl-assoc cl-rassoc
cl-sublis))
(let ((args (relint--wrap-cl-keyword-args
(mapcar #'relint--eval body))))
(condition-case nil
(apply head args)
(error (throw 'relint-eval 'no-value)))))
;; Functions taking a function as first argument,
;; and with functions as keyword arguments :test, :test-not, :key
((memq head '(cl-reduce cl-remove-if cl-remove-if-not
cl-find-if cl-find-if-not
cl-position-if cl-position-if-not
cl-count-if cl-count-if-not
cl-member-if cl-member-if-not
cl-assoc-if cl-assoc-if-not
cl-rassoc-if cl-rassoc-if-not))
(let ((fun (relint--wrap-function (relint--eval (car body))))
(args (relint--wrap-cl-keyword-args
(mapcar #'relint--eval (cdr body)))))
(condition-case nil
(apply head fun args)
(error (throw 'relint-eval 'no-value)))))
;; mapcar, mapcan, mapc: accept missing items in the list argument.
((memq head '(mapcar mapcan mapc))
(let* ((fun (relint--wrap-function (relint--eval (car body))))
(arg (relint--eval-list (cadr body)))
(seq (if (listp arg)
(remq nil arg)
arg)))
(condition-case nil
(funcall head fun seq)
(error (throw 'relint-eval 'no-value)))))
;; sort: accept missing items in the list argument.
((eq head 'sort)
;; FIXME: handle new-style `sort' args
(let* ((arg (relint--eval-list (car body)))
(seq (cond ((listp arg) (remq nil arg))
((sequencep arg) (copy-sequence arg))
(arg)))
(pred (relint--wrap-function (relint--eval (cadr body)))))
(condition-case nil
(sort seq pred)
(error (throw 'relint-eval 'no-value)))))
;; rx, rx-to-string: check for lisp expressions in constructs first,
;; then apply.
((eq head 'rx)
(relint--eval-rx (list (cons 'seq body) t)))
((eq head 'rx-to-string)
(let ((args (mapcar #'relint--eval body)))
(relint--eval-rx args)))
;; setq: set local variables if permitted.
((eq head 'setq)
(if (and (symbolp (car body)) (consp (cdr body)))
(let* ((name (car body))
;; FIXME: Consider using relint--eval-to-binding instead,
;; tolerating unevaluatable expressions.
(val (relint--eval (cadr body))))
;; Somewhat dubiously, we ignore the side-effect for
;; non-local (or local non-mutable) variables and hope
;; it doesn't matter.
(when (memq name relint--eval-mutables)
(let ((local (assq name relint--locals)))
(setcdr local (list val))))
(if (cddr body)
(relint--eval (cons 'setq (cddr body)))
val))
(throw 'relint-eval 'no-value))) ; Syntax error.
((eq head 'push)
(let* ((expr (car body))
(name (cadr body))
(local (assq name relint--locals)))
(if (and (memq name relint--eval-mutables)
(cdr local))
(let ((new-val (cons (relint--eval expr) (cadr local))))
(setcdr local (list new-val))
new-val)