]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/elint.el
Don’t create unnecessary marker in ‘delete-trailing-whitespace’
[gnu-emacs] / lisp / emacs-lisp / elint.el
1 ;;; elint.el --- Lint Emacs Lisp
2
3 ;; Copyright (C) 1997, 2001-2016 Free Software Foundation, Inc.
4
5 ;; Author: Peter Liljenberg <petli@lysator.liu.se>
6 ;; Created: May 1997
7 ;; Keywords: lisp
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This is a linter for Emacs Lisp. Currently, it mainly catches
27 ;; misspellings and undefined variables, although it can also catch
28 ;; function calls with the wrong number of arguments.
29
30 ;; To use, call elint-current-buffer or elint-defun to lint a buffer
31 ;; or defun. The first call runs `elint-initialize' to set up some
32 ;; argument data, which may take a while.
33
34 ;; The linter will try to "include" any require'd libraries to find
35 ;; the variables defined in those. There is a fair amount of voodoo
36 ;; involved in this, but it seems to work in normal situations.
37
38 ;;; To do:
39
40 ;; * Adding type checking. (Stop that sniggering!)
41 ;; * Make eval-when-compile be sensitive to the difference between
42 ;; funcs and macros.
43 ;; * Requires within function bodies.
44 ;; * Handle defstruct.
45 ;; * Prevent recursive requires.
46
47 ;;; Code:
48
49 (defgroup elint nil
50 "Linting for Emacs Lisp."
51 :prefix "elint-"
52 :group 'maint)
53
54 (defcustom elint-log-buffer "*Elint*"
55 "The buffer in which to log lint messages."
56 :type 'string
57 :safe 'stringp
58 :group 'elint)
59
60 (defcustom elint-scan-preloaded t
61 "Non-nil means to scan `preloaded-file-list' when initializing.
62 Otherwise, just scan the DOC file for functions and variables.
63 This is faster, but less accurate, since it misses undocumented features.
64 This may result in spurious warnings about unknown functions, etc."
65 :type 'boolean
66 :safe 'booleanp
67 :group 'elint
68 :version "23.2")
69
70 (defcustom elint-ignored-warnings nil
71 "If non-nil, a list of issue types that Elint should ignore.
72 This is useful if Elint has trouble understanding your code and
73 you need to suppress lots of spurious warnings. The valid list elements
74 are as follows, and suppress messages about the indicated features:
75 undefined-functions - calls to unknown functions
76 unbound-reference - reference to unknown variables
77 unbound-assignment - assignment to unknown variables
78 macro-expansions - failure to expand macros
79 empty-let - let-bindings with empty variable lists"
80 :type '(choice (const :tag "Don't suppress any warnings" nil)
81 (repeat :tag "List of issues to ignore"
82 (choice (const undefined-functions
83 :tag "Calls to unknown functions")
84 (const unbound-reference
85 :tag "Reference to unknown variables")
86 (const unbound-assignment
87 :tag "Assignment to unknown variables")
88 (const macro-expansion
89 :tag "Failure to expand macros")
90 (const empty-let
91 :tag "Let-binding with empty varlist"))))
92 :safe (lambda (value) (or (null value)
93 (and (listp value)
94 (equal value
95 (mapcar
96 (lambda (e)
97 (if (memq e
98 '(undefined-functions
99 unbound-reference
100 unbound-assignment
101 macro-expansion
102 empty-let))
103 e))
104 value)))))
105 :version "23.2"
106 :group 'elint)
107
108 (defcustom elint-directory-skip-re "\\(ldefs-boot\\|loaddefs\\)\\.el\\'"
109 "If nil, a regexp matching files to skip when linting a directory."
110 :type '(choice (const :tag "Lint all files" nil)
111 (regexp :tag "Regexp to skip"))
112 :safe 'string-or-null-p
113 :group 'elint
114 :version "23.2")
115
116 ;;;
117 ;;; Data
118 ;;;
119
120 (defconst elint-standard-variables
121 ;; Most of these are defined in C with no documentation.
122 ;; FIXME I don't see why they shouldn't just get doc-strings.
123 '(vc-mode local-write-file-hooks activate-menubar-hook buffer-name-history
124 coding-system-history extended-command-history
125 yes-or-no-p-history)
126 "Standard variables, excluding `elint-builtin-variables'.
127 These are variables that we cannot detect automatically for some reason.")
128
129 (defvar elint-builtin-variables nil
130 "List of built-in variables. Set by `elint-initialize'.
131 This is actually all those documented in the DOC file, which includes
132 built-in variables and those from dumped Lisp files.")
133
134 (defvar elint-autoloaded-variables nil
135 "List of `loaddefs.el' variables. Set by `elint-initialize'.")
136
137 (defvar elint-preloaded-env nil
138 "Environment defined by the preloaded (dumped) Lisp files.
139 Set by `elint-initialize', if `elint-scan-preloaded' is non-nil.")
140
141 (defconst elint-unknown-builtin-args
142 ;; encode-time allows extra arguments for use with decode-time.
143 ;; For some reason, some people seem to like to use them in other cases.
144 '((encode-time second minute hour day month year &rest zone))
145 "Those built-ins for which we can't find arguments, if any.")
146
147 (defvar elint-extra-errors '(file-locked file-supersession ftp-error)
148 "Errors without `error-message' or `error-conditions' properties.")
149
150 (defconst elint-preloaded-skip-re
151 (regexp-opt '("loaddefs.el" "loadup.el" "cus-start" "language/"
152 "eucjp-ms" "mule-conf" "/characters" "/charprop"
153 "cp51932"))
154 "Regexp matching elements of `preloaded-file-list' to ignore.
155 We ignore them because they contain no definitions of use to Elint.")
156
157 ;;;
158 ;;; ADT: top-form
159 ;;;
160
161 (defsubst elint-make-top-form (form pos)
162 "Create a top form.
163 FORM is the form, and POS is the point where it starts in the buffer."
164 (cons form pos))
165
166 (defsubst elint-top-form-form (top-form)
167 "Extract the form from a TOP-FORM."
168 (car top-form))
169
170 (defsubst elint-top-form-pos (top-form)
171 "Extract the position from a TOP-FORM."
172 (cdr top-form))
173
174 ;;;
175 ;;; ADT: env
176 ;;;
177
178 (defsubst elint-make-env ()
179 "Create an empty environment."
180 (list (list nil) nil nil))
181
182 (defsubst elint-env-add-env (env newenv)
183 "Augment ENV with NEWENV.
184 None of them is modified, and the new env is returned."
185 (list (append (car env) (car newenv))
186 (append (cadr env) (cadr newenv))
187 (append (car (cdr (cdr env))) (car (cdr (cdr newenv))))))
188
189 (defsubst elint-env-add-var (env var)
190 "Augment ENV with the variable VAR.
191 The new environment is returned, the old is unmodified."
192 (cons (cons (list var) (car env)) (cdr env)))
193
194 (defsubst elint-env-add-global-var (env var)
195 "Augment ENV with the variable VAR.
196 ENV is modified so VAR is seen everywhere.
197 ENV is returned."
198 (nconc (car env) (list (list var)))
199 env)
200
201 (defsubst elint-env-find-var (env var)
202 "Non-nil if ENV contains the variable VAR.
203 Actually, a list with VAR as a single element is returned."
204 (assq var (car env)))
205
206 (defsubst elint-env-add-func (env func args)
207 "Augment ENV with the function FUNC, which has the arguments ARGS.
208 The new environment is returned, the old is unmodified."
209 (list (car env)
210 (cons (list func args) (cadr env))
211 (car (cdr (cdr env)))))
212
213 (defsubst elint-env-find-func (env func)
214 "Non-nil if ENV contains the function FUNC.
215 Actually, a list of (FUNC ARGS) is returned."
216 (assq func (cadr env)))
217
218 (defsubst elint-env-add-macro (env macro def)
219 "Augment ENV with the macro named MACRO.
220 DEF is the macro definition (a lambda expression or similar).
221 The new environment is returned, the old is unmodified."
222 (list (car env)
223 (cadr env)
224 (cons (cons macro def) (car (cdr (cdr env))))))
225
226 (defsubst elint-env-macro-env (env)
227 "Return the macro environment of ENV.
228 This environment can be passed to `macroexpand'."
229 (car (cdr (cdr env))))
230
231 (defsubst elint-env-macrop (env macro)
232 "Non-nil if ENV contains MACRO."
233 (assq macro (elint-env-macro-env env)))
234
235 ;;;
236 ;;; User interface
237 ;;;
238
239 ;;;###autoload
240 (defun elint-file (file)
241 "Lint the file FILE."
242 (interactive "fElint file: ")
243 (setq file (expand-file-name file))
244 (or elint-builtin-variables
245 (elint-initialize))
246 (let ((dir (file-name-directory file)))
247 (let ((default-directory dir))
248 (elint-display-log))
249 (elint-set-mode-line t)
250 (with-current-buffer elint-log-buffer
251 (unless (string-equal default-directory dir)
252 (elint-log-message (format-message "\f\nLeaving directory `%s'"
253 default-directory) t)
254 (elint-log-message (format-message "Entering directory `%s'" dir) t)
255 (setq default-directory dir))))
256 (let ((str (format "Linting file %s" file)))
257 (message "%s..." str)
258 (or noninteractive
259 (elint-log-message (format "\f\n%s at %s" str (current-time-string)) t))
260 ;; elint-current-buffer clears log.
261 (with-temp-buffer
262 (insert-file-contents file)
263 (let ((buffer-file-name file)
264 (max-lisp-eval-depth (max 1000 max-lisp-eval-depth)))
265 (with-syntax-table emacs-lisp-mode-syntax-table
266 (mapc 'elint-top-form (elint-update-env)))))
267 (elint-set-mode-line)
268 (message "%s...done" str)))
269
270 ;; cf byte-recompile-directory.
271 ;;;###autoload
272 (defun elint-directory (directory)
273 "Lint all the .el files in DIRECTORY.
274 A complicated directory may require a lot of memory."
275 (interactive "DElint directory: ")
276 (let ((elint-running t))
277 (dolist (file (directory-files directory t))
278 ;; Bytecomp has emacs-lisp-file-regexp.
279 (when (and (string-match "\\.el\\'" file)
280 (file-readable-p file)
281 (not (auto-save-file-name-p file)))
282 (if (string-match elint-directory-skip-re file)
283 (message "Skipping file %s" file)
284 (elint-file file)))))
285 (elint-set-mode-line))
286
287 ;;;###autoload
288 (defun elint-current-buffer ()
289 "Lint the current buffer.
290 If necessary, this first calls `elint-initialize'."
291 (interactive)
292 (or elint-builtin-variables
293 (elint-initialize))
294 (elint-clear-log (format "Linting %s" (or (buffer-file-name)
295 (buffer-name))))
296 (elint-display-log)
297 (elint-set-mode-line t)
298 (mapc 'elint-top-form (elint-update-env))
299 ;; Tell the user we're finished. This is terribly kludgy: we set
300 ;; elint-top-form-logged so elint-log-message doesn't print the
301 ;; ** top form ** header...
302 (elint-set-mode-line)
303 (elint-log-message "\nLinting finished.\n" t))
304
305
306 ;;;###autoload
307 (defun elint-defun ()
308 "Lint the function at point.
309 If necessary, this first calls `elint-initialize'."
310 (interactive)
311 (or elint-builtin-variables
312 (elint-initialize))
313 (save-excursion
314 (or (beginning-of-defun) (error "Lint what?"))
315 (let ((pos (point))
316 (def (read (current-buffer))))
317 (elint-display-log)
318 (elint-update-env)
319 (elint-top-form (elint-make-top-form def pos)))))
320
321 ;;;
322 ;;; Top form functions
323 ;;;
324
325 (defvar elint-buffer-env nil
326 "The environment of an elisp buffer.
327 Will be local in linted buffers.")
328
329 (defvar elint-buffer-forms nil
330 "The top forms in a buffer.
331 Will be local in linted buffers.")
332
333 (defvar elint-last-env-time nil
334 "The last time the buffers env was updated.
335 Is measured in buffer-modified-ticks and is local in linted buffers.")
336
337 ;; This is a minor optimization. It is local to every buffer, and so
338 ;; does not prevent recursive requires. It does not list the requires
339 ;; of requires.
340 (defvar elint-features nil
341 "List of all libraries this buffer has required, or that have been provided.")
342
343 (defun elint-update-env ()
344 "Update the elint environment in the current buffer.
345 Don't do anything if the buffer hasn't been changed since this
346 function was called the last time.
347 Returns the forms."
348 (if (and (local-variable-p 'elint-buffer-env (current-buffer))
349 (local-variable-p 'elint-buffer-forms (current-buffer))
350 (local-variable-p 'elint-last-env-time (current-buffer))
351 (= (buffer-modified-tick) elint-last-env-time))
352 ;; Env is up to date
353 elint-buffer-forms
354 ;; Remake env
355 (set (make-local-variable 'elint-buffer-forms) (elint-get-top-forms))
356 (set (make-local-variable 'elint-features) nil)
357 (set (make-local-variable 'elint-buffer-env)
358 (elint-init-env elint-buffer-forms))
359 (if elint-preloaded-env
360 ;; FIXME: This doesn't do anything! Should we setq the result to
361 ;; elint-buffer-env?
362 (elint-env-add-env elint-preloaded-env elint-buffer-env))
363 (set (make-local-variable 'elint-last-env-time) (buffer-modified-tick))
364 elint-buffer-forms))
365
366 (defun elint-get-top-forms ()
367 "Collect all the top forms in the current buffer."
368 (save-excursion
369 (let (tops)
370 (goto-char (point-min))
371 (while (elint-find-next-top-form)
372 (let ((elint-current-pos (point)))
373 ;; non-list check could be here too. errors may be out of seq.
374 ;; quoted check cannot be elsewhere, since quotes skipped.
375 (if (looking-back "'" (1- (point)))
376 ;; Eg cust-print.el uses ' as a comment syntax.
377 (elint-warning "Skipping quoted form `%c%.20s...'" ?\'
378 (read (current-buffer)))
379 (condition-case nil
380 (setq tops (cons
381 (elint-make-top-form (read (current-buffer))
382 elint-current-pos)
383 tops))
384 (end-of-file
385 (goto-char elint-current-pos)
386 (error "Missing `)' in top form: %s"
387 (buffer-substring elint-current-pos
388 (line-end-position))))))))
389 (nreverse tops))))
390
391 (defun elint-find-next-top-form ()
392 "Find the next top form from point.
393 Return nil if there are no more forms, t otherwise."
394 (parse-partial-sexp (point) (point-max) nil t)
395 (not (eobp)))
396
397 (defvar elint-env) ; from elint-init-env
398
399 (defun elint-init-form (form)
400 "Process FORM, adding to ELINT-ENV if recognized."
401 (cond
402 ;; Eg nnmaildir seems to use [] as a form of comment syntax.
403 ((not (listp form))
404 (elint-warning "Skipping non-list form `%s'" form))
405 ;; Add defined variable
406 ((memq (car form) '(defvar defconst defcustom))
407 (setq elint-env (elint-env-add-var elint-env (cadr form))))
408 ;; Add function
409 ((memq (car form) '(defun defsubst))
410 (setq elint-env (elint-env-add-func elint-env (cadr form) (nth 2 form))))
411 ;; FIXME needs a handler to say second arg is not a variable when we come
412 ;; to scan the form.
413 ((eq (car form) 'define-derived-mode)
414 (setq elint-env (elint-env-add-func elint-env (cadr form) ())
415 elint-env (elint-env-add-var elint-env (cadr form))
416 elint-env (elint-env-add-var elint-env
417 (intern (format "%s-map" (cadr form))))))
418 ((eq (car form) 'define-minor-mode)
419 (setq elint-env (elint-env-add-func elint-env (cadr form) '(&optional arg))
420 ;; FIXME mode map?
421 elint-env (elint-env-add-var elint-env (cadr form))))
422 ((and (eq (car form) 'easy-menu-define)
423 (cadr form))
424 (setq elint-env (elint-env-add-func elint-env (cadr form) '(event))
425 elint-env (elint-env-add-var elint-env (cadr form))))
426 ;; FIXME it would be nice to check the autoloads are correct.
427 ((eq (car form) 'autoload)
428 (setq elint-env (elint-env-add-func elint-env (cadr (cadr form)) 'unknown)))
429 ((eq (car form) 'declare-function)
430 (setq elint-env (elint-env-add-func
431 elint-env (cadr form)
432 (if (or (< (length form) 4)
433 (eq (nth 3 form) t)
434 (unless (stringp (nth 2 form))
435 (elint-error "Malformed declaration for `%s'"
436 (cadr form))
437 t))
438 'unknown
439 (nth 3 form)))))
440 ((and (eq (car form) 'defalias) (listp (nth 2 form)))
441 ;; If the alias points to something already in the environment,
442 ;; add the alias to the environment with the same arguments.
443 ;; FIXME symbol-function, eg backquote.el?
444 (let ((def (elint-env-find-func elint-env (cadr (nth 2 form)))))
445 (setq elint-env (elint-env-add-func elint-env (cadr (cadr form))
446 (if def (cadr def) 'unknown)))))
447 ;; Add macro, both as a macro and as a function
448 ((eq (car form) 'defmacro)
449 (setq elint-env (elint-env-add-macro elint-env (cadr form)
450 (cons 'lambda (cddr form)))
451 elint-env (elint-env-add-func elint-env (cadr form) (nth 2 form))))
452 ((and (eq (car form) 'put)
453 (= 4 (length form))
454 (eq (car-safe (cadr form)) 'quote)
455 (equal (nth 2 form) '(quote error-conditions)))
456 (set (make-local-variable 'elint-extra-errors)
457 (cons (cadr (cadr form)) elint-extra-errors)))
458 ((eq (car form) 'provide)
459 (add-to-list 'elint-features (eval (cadr form))))
460 ;; Import variable definitions
461 ((memq (car form) '(require cc-require cc-require-when-compile))
462 (let ((name (eval (cadr form)))
463 (file (eval (nth 2 form)))
464 (elint-doing-cl (bound-and-true-p elint-doing-cl)))
465 (unless (memq name elint-features)
466 (add-to-list 'elint-features name)
467 ;; cl loads cl-macs in an opaque manner.
468 ;; Since cl-macs requires cl, we can just process cl-macs.
469 ;; FIXME: AFAIK, `cl' now behaves properly and does not need any
470 ;; special treatment any more. Can someone who understands this
471 ;; code confirm? --Stef
472 (and (eq name 'cl) (not elint-doing-cl)
473 ;; We need cl if elint-form is to be able to expand cl macros.
474 (require 'cl)
475 (setq name 'cl-macs
476 file nil
477 elint-doing-cl t)) ; blech
478 (setq elint-env (elint-add-required-env elint-env name file))))))
479 elint-env)
480
481 (defun elint-init-env (forms)
482 "Initialize the environment from FORMS."
483 (let ((elint-env (elint-make-env))
484 form)
485 (while forms
486 (setq form (elint-top-form-form (car forms))
487 forms (cdr forms))
488 ;; FIXME eval-when-compile should be treated differently (macros).
489 ;; Could bind something that makes elint-init-form only check
490 ;; defmacros.
491 (if (memq (car-safe form)
492 '(eval-and-compile eval-when-compile progn prog1 prog2
493 with-no-warnings))
494 (mapc 'elint-init-form (cdr form))
495 (elint-init-form form)))
496 elint-env))
497
498 (defun elint-add-required-env (env name file)
499 "Augment ENV with the variables defined by feature NAME in FILE."
500 (condition-case err
501 (let* ((libname (if (stringp file)
502 file
503 (symbol-name name)))
504
505 ;; First try to find .el files, then the raw name
506 (lib1 (locate-library (concat libname ".el") t))
507 (lib (or lib1 (locate-library libname t))))
508 ;; Clear the messages :-/
509 ;; (Messes up the "Initializing elint..." message.)
510 ;;; (message nil)
511 (if lib
512 (with-current-buffer (find-file-noselect lib)
513 ;; FIXME this doesn't use a temp buffer, because it
514 ;; stores the result in buffer-local variables so that
515 ;; it can be reused.
516 (elint-update-env)
517 (setq env (elint-env-add-env env elint-buffer-env)))
518 ;;; (with-temp-buffer
519 ;;; (insert-file-contents lib)
520 ;;; (with-syntax-table emacs-lisp-mode-syntax-table
521 ;;; (elint-update-env))
522 ;;; (setq env (elint-env-add-env env elint-buffer-env))))
523 ;;(message "%s" (format "Elint processed (require '%s)" name))
524 (error "%s.el not found in load-path" libname)))
525 (error
526 (message "Can't get variables from require'd library %s: %s"
527 name (error-message-string err))))
528 env)
529
530 (defvar elint-top-form nil
531 "The currently linted top form, or nil.")
532
533 (defvar elint-top-form-logged nil
534 "The value t if the currently linted top form has been mentioned in the log buffer.")
535
536 (defun elint-top-form (form)
537 "Lint a top FORM."
538 (let ((elint-top-form form)
539 (elint-top-form-logged nil)
540 (elint-current-pos (elint-top-form-pos form)))
541 (elint-form (elint-top-form-form form) elint-buffer-env)))
542
543 ;;;
544 ;;; General form linting functions
545 ;;;
546
547 (defconst elint-special-forms
548 '((let . elint-check-let-form)
549 (let* . elint-check-let-form)
550 (setq . elint-check-setq-form)
551 (quote . elint-check-quote-form)
552 (function . elint-check-quote-form)
553 (cond . elint-check-cond-form)
554 (lambda . elint-check-defun-form)
555 (function . elint-check-function-form)
556 (setq-default . elint-check-setq-form)
557 (defalias . elint-check-defalias-form)
558 (defun . elint-check-defun-form)
559 (defsubst . elint-check-defun-form)
560 (defmacro . elint-check-defun-form)
561 (defvar . elint-check-defvar-form)
562 (defconst . elint-check-defvar-form)
563 (defcustom . elint-check-defcustom-form)
564 (macro . elint-check-macro-form)
565 (condition-case . elint-check-condition-case-form)
566 (if . elint-check-conditional-form)
567 (when . elint-check-conditional-form)
568 (unless . elint-check-conditional-form)
569 (and . elint-check-conditional-form)
570 (or . elint-check-conditional-form))
571 "Functions to call when some special form should be linted.")
572
573 (defun elint-form (form env &optional nohandler)
574 "Lint FORM in the environment ENV.
575 Optional argument NOHANDLER non-nil means ignore `elint-special-forms'.
576 Returns the environment created by the form."
577 (cond
578 ((consp form)
579 (let ((func (cdr (assq (car form) elint-special-forms))))
580 (if (and func (not nohandler))
581 ;; Special form
582 (funcall func form env)
583
584 (let* ((func (car form))
585 (args (elint-get-args func env))
586 (argsok t))
587 (cond
588 ((eq args 'undefined)
589 (setq argsok nil)
590 (or (memq 'undefined-functions elint-ignored-warnings)
591 (elint-error "Call to undefined function: %s" func)))
592
593 ((eq args 'unknown) nil)
594
595 (t (setq argsok (elint-match-args form args))))
596
597 ;; Is this a macro?
598 (if (elint-env-macrop env func)
599 ;; Macro defined in buffer, expand it
600 (if argsok
601 ;; FIXME error if macro uses macro, eg bytecomp.el.
602 (condition-case nil
603 (elint-form
604 (macroexpand form (elint-env-macro-env env)) env)
605 (error
606 (or (memq 'macro-expansion elint-ignored-warnings)
607 (elint-error "Elint failed to expand macro: %s" func))
608 env))
609 env)
610
611 (let ((fcode (if (symbolp func)
612 (if (fboundp func)
613 (indirect-function func))
614 func)))
615 (if (and (listp fcode) (eq (car fcode) 'macro))
616 ;; Macro defined outside buffer
617 (if argsok
618 (elint-form (macroexpand form) env)
619 env)
620 ;; Function, lint its parameters
621 (elint-forms (cdr form) env))))))))
622 ((symbolp form)
623 ;; :foo variables are quoted
624 (and (/= (aref (symbol-name form) 0) ?:)
625 (not (memq 'unbound-reference elint-ignored-warnings))
626 (elint-unbound-variable form env)
627 (elint-warning "Reference to unbound symbol: %s" form))
628 env)
629
630 (t env)))
631
632 (defun elint-forms (forms env)
633 "Lint the FORMS, accumulating an environment, starting with ENV."
634 ;; grumblegrumbletailrecursiongrumblegrumble
635 (if (listp forms)
636 (dolist (f forms env)
637 (setq env (elint-form f env)))
638 ;; Loop macro?
639 (elint-error "Elint failed to parse form: %s" forms)
640 env))
641
642 (defvar elint-bound-variable nil
643 "Name of a temporarily bound symbol.")
644
645 (defun elint-unbound-variable (var env)
646 "Return t if VAR is unbound in ENV."
647 ;; #1063 suggests adding (symbol-file var) here, but I don't think
648 ;; this is right, because it depends on what files you happen to have
649 ;; loaded at the time, which might not be the same when the code runs.
650 ;; It also suggests adding:
651 ;; (numberp (get var 'variable-documentation))
652 ;; (numberp (cdr-safe (get var 'variable-documentation)))
653 ;; but this is not needed now elint-scan-doc-file exists.
654 (not (or (memq var '(nil t))
655 (eq var elint-bound-variable)
656 (elint-env-find-var env var)
657 (memq var elint-builtin-variables)
658 (memq var elint-autoloaded-variables)
659 (memq var elint-standard-variables))))
660
661 ;;;
662 ;;; Function argument checking
663 ;;;
664
665 (defun elint-match-args (arglist argpattern)
666 "Match ARGLIST against ARGPATTERN."
667 (let ((state 'all)
668 (al (cdr arglist))
669 (ap argpattern)
670 (ok t))
671 (while
672 (cond
673 ((and (null al) (null ap)) nil)
674 ((eq (car ap) '&optional)
675 (setq state 'optional)
676 (setq ap (cdr ap))
677 t)
678 ((eq (car ap) '&rest)
679 nil)
680 ((or (and (eq state 'all) (or (null al) (null ap)))
681 (and (eq state 'optional) (and al (null ap))))
682 (elint-error "Wrong number of args: %s, %s" arglist argpattern)
683 (setq ok nil)
684 nil)
685 ((and (eq state 'optional) (null al))
686 nil)
687 (t (setq al (cdr al)
688 ap (cdr ap))
689 t)))
690 ok))
691
692 (defvar elint-bound-function nil
693 "Name of a temporarily bound function symbol.")
694
695 (defun elint-get-args (func env)
696 "Find the args of FUNC in ENV.
697 Returns `unknown' if we couldn't find arguments."
698 (let ((f (elint-env-find-func env func)))
699 (if f
700 (cadr f)
701 (if (symbolp func)
702 (if (eq func elint-bound-function)
703 'unknown
704 (if (fboundp func)
705 (let ((fcode (indirect-function func)))
706 (if (subrp fcode)
707 ;; FIXME builtins with no args have args = nil.
708 (or (get func 'elint-args) 'unknown)
709 (elint-find-args-in-code fcode)))
710 'undefined))
711 (elint-find-args-in-code func)))))
712
713 (defun elint-find-args-in-code (code)
714 "Extract the arguments from CODE.
715 CODE can be a lambda expression, a macro, or byte-compiled code."
716 (let ((args (help-function-arglist code)))
717 (if (listp args) args 'unknown)))
718
719 ;;;
720 ;;; Functions to check some special forms
721 ;;;
722
723 (defun elint-check-cond-form (form env)
724 "Lint a cond FORM in ENV."
725 (dolist (f (cdr form))
726 (if (consp f)
727 (let ((test (car f)))
728 (cond ((equal test '(featurep (quote xemacs))))
729 ((equal test '(not (featurep (quote emacs)))))
730 ;; FIXME (and (boundp 'foo)
731 ((and (eq (car-safe test) 'fboundp)
732 (= 2 (length test))
733 (eq (car-safe (cadr test)) 'quote))
734 (let ((elint-bound-function (cadr (cadr test))))
735 (elint-forms f env)))
736 ((and (eq (car-safe test) 'boundp)
737 (= 2 (length test))
738 (eq (car-safe (cadr test)) 'quote))
739 (let ((elint-bound-variable (cadr (cadr test))))
740 (elint-forms f env)))
741 (t (elint-forms f env))))
742 (elint-error "cond clause should be a list: %s" f)))
743 env)
744
745 (defun elint-check-defun-form (form env)
746 "Lint a defun/defmacro/lambda FORM in ENV."
747 (setq form (if (eq (car form) 'lambda) (cdr form) (cddr form)))
748 (mapc (lambda (p)
749 (or (memq p '(&optional &rest))
750 (setq env (elint-env-add-var env p))))
751 (car form))
752 (elint-forms (cdr form) env))
753
754 (defun elint-check-defalias-form (form env)
755 "Lint a defalias FORM in ENV."
756 (let ((alias (cadr form))
757 (target (nth 2 form)))
758 (and (eq (car-safe alias) 'quote)
759 (eq (car-safe target) 'quote)
760 (eq (elint-get-args (cadr target) env) 'undefined)
761 (elint-warning "Alias `%s' has unknown target `%s'"
762 (cadr alias) (cadr target))))
763 (elint-form form env t))
764
765 (defun elint-check-let-form (form env)
766 "Lint the let/let* FORM in ENV."
767 (let ((varlist (cadr form)))
768 (if (not varlist)
769 (if (> (length form) 2)
770 ;; An empty varlist is not really an error. Eg some cl macros
771 ;; can expand to such a form.
772 (progn
773 (or (memq 'empty-let elint-ignored-warnings)
774 (elint-warning "Empty varlist in let: %s" form))
775 ;; Lint the body forms
776 (elint-forms (cddr form) env))
777 (elint-error "Malformed let: %s" form)
778 env)
779 ;; Check for (let (a (car b)) ...) type of error
780 (if (and (= (length varlist) 2)
781 (symbolp (car varlist))
782 (listp (car (cdr varlist)))
783 (fboundp (car (car (cdr varlist)))))
784 (elint-warning "Suspect varlist: %s" form))
785 ;; Add variables to environment, and check the init values
786 (let ((newenv env))
787 (mapc (lambda (s)
788 (cond
789 ((symbolp s)
790 (setq newenv (elint-env-add-var newenv s)))
791 ((and (consp s) (<= (length s) 2))
792 (elint-form (cadr s)
793 (if (eq (car form) 'let)
794 env
795 newenv))
796 (setq newenv
797 (elint-env-add-var newenv (car s))))
798 (t (elint-error
799 "Malformed `let' declaration: %s" s))))
800 varlist)
801
802 ;; Lint the body forms
803 (elint-forms (cddr form) newenv)))))
804
805 (defun elint-check-setq-form (form env)
806 "Lint the setq FORM in ENV."
807 (or (= (mod (length form) 2) 1)
808 ;; (setq foo) is valid and equivalent to (setq foo nil).
809 (elint-warning "Missing value in setq: %s" form))
810 (let ((newenv env)
811 sym val)
812 (setq form (cdr form))
813 (while form
814 (setq sym (car form)
815 val (car (cdr form))
816 form (cdr (cdr form)))
817 (if (symbolp sym)
818 (and (not (memq 'unbound-assignment elint-ignored-warnings))
819 (elint-unbound-variable sym newenv)
820 (elint-warning "Setting previously unbound symbol: %s" sym))
821 (elint-error "Setting non-symbol in setq: %s" sym))
822 (elint-form val newenv)
823 (if (symbolp sym)
824 (setq newenv (elint-env-add-var newenv sym))))
825 newenv))
826
827 (defun elint-check-defvar-form (form env)
828 "Lint the defvar/defconst FORM in ENV."
829 (if (or (= (length form) 2)
830 (= (length form) 3)
831 ;; Eg the defcalcmodevar macro can expand with a nil doc-string.
832 (and (= (length form) 4) (string-or-null-p (nth 3 form))))
833 (elint-env-add-global-var (elint-form (nth 2 form) env)
834 (car (cdr form)))
835 (elint-error "Malformed variable declaration: %s" form)
836 env))
837
838 (defun elint-check-defcustom-form (form env)
839 "Lint the defcustom FORM in ENV."
840 (if (and (> (length form) 3)
841 ;; even no. of keyword/value args ?
842 (zerop (logand (length form) 1)))
843 (elint-env-add-global-var (elint-form (nth 2 form) env)
844 (car (cdr form)))
845 (elint-error "Malformed variable declaration: %s" form)
846 env))
847
848 (defun elint-check-function-form (form env)
849 "Lint the function FORM in ENV."
850 (let ((func (car (cdr-safe form))))
851 (cond
852 ((symbolp func)
853 (or (elint-env-find-func env func)
854 ;; FIXME potentially bogus, since it uses the current
855 ;; environment rather than a clean one.
856 (fboundp func)
857 (elint-warning "Reference to undefined function: %s" form))
858 env)
859 ((and (consp func) (memq (car func) '(lambda macro)))
860 (elint-form func env))
861 ((stringp func) env)
862 (t (elint-error "Not a function object: %s" form)
863 env))))
864
865 (defun elint-check-quote-form (form env)
866 "Lint the quote FORM in ENV."
867 env)
868
869 (defun elint-check-macro-form (form env)
870 "Check the macro FORM in ENV."
871 (elint-check-function-form (list (car form) (cdr form)) env))
872
873 (defun elint-check-condition-case-form (form env)
874 "Check the `condition-case' FORM in ENV."
875 (let ((resenv env))
876 (if (< (length form) 3)
877 (elint-error "Malformed condition-case: %s" form)
878 (or (symbolp (cadr form))
879 (elint-warning "First parameter should be a symbol: %s" form))
880 (setq resenv (elint-form (nth 2 form) env))
881 (let ((newenv (elint-env-add-var env (cadr form)))
882 errlist)
883 (dolist (err (nthcdr 3 form))
884 (setq errlist (car err))
885 (mapc (lambda (s)
886 (or (get s 'error-conditions)
887 (get s 'error-message)
888 (memq s elint-extra-errors)
889 (elint-warning
890 "Not an error symbol in error handler: %s" s)))
891 (cond
892 ((symbolp errlist) (list errlist))
893 ((listp errlist) errlist)
894 (t (elint-error "Bad error list in error handler: %s"
895 errlist)
896 nil)))
897 (elint-forms (cdr err) newenv))))
898 resenv))
899
900 ;; For the featurep parts, an alternative is to have
901 ;; elint-get-top-forms skip the irrelevant branches.
902 (defun elint-check-conditional-form (form env)
903 "Check the when/unless/and/or FORM in ENV.
904 Does basic handling of `featurep' tests."
905 (let ((func (car form))
906 (test (cadr form))
907 sym)
908 ;; Misses things like (and t (featurep 'xemacs))
909 ;; Check byte-compile-maybe-guarded.
910 (cond ((and (memq func '(when and))
911 (eq (car-safe test) 'boundp)
912 (= 2 (length test))
913 (eq (car-safe (cadr test)) 'quote))
914 ;; Cf elint-check-let-form, which modifies the whole ENV.
915 (let ((elint-bound-variable (cadr (cadr test))))
916 (elint-form form env t)))
917 ((and (memq func '(when and))
918 (eq (car-safe test) 'fboundp)
919 (= 2 (length test))
920 (eq (car-safe (cadr test)) 'quote))
921 (let ((elint-bound-function (cadr (cadr test))))
922 (elint-form form env t)))
923 ;; Let's not worry about (if (not (boundp...
924 ((and (eq func 'if)
925 (eq (car-safe test) 'boundp)
926 (= 2 (length test))
927 (eq (car-safe (cadr test)) 'quote))
928 (let ((elint-bound-variable (cadr (cadr test))))
929 (elint-form (nth 2 form) env))
930 (dolist (f (nthcdr 3 form))
931 (elint-form f env)))
932 ((and (eq func 'if)
933 (eq (car-safe test) 'fboundp)
934 (= 2 (length test))
935 (eq (car-safe (cadr test)) 'quote))
936 (let ((elint-bound-function (cadr (cadr test))))
937 (elint-form (nth 2 form) env))
938 (dolist (f (nthcdr 3 form))
939 (elint-form f env)))
940 ((and (memq func '(when and)) ; skip all
941 (or (null test)
942 (member test '((featurep (quote xemacs))
943 (not (featurep (quote emacs)))))
944 (and (eq (car-safe test) 'and)
945 (equal (car-safe (cdr test))
946 '(featurep (quote xemacs)))))))
947 ((and (memq func '(unless or))
948 (equal test '(featurep (quote emacs)))))
949 ((and (eq func 'if)
950 (or (null test) ; eg custom-browse-insert-prefix
951 (member test '((featurep (quote xemacs))
952 (not (featurep (quote emacs)))))
953 (and (eq (car-safe test) 'and)
954 (equal (car-safe (cdr test))
955 '(featurep (quote xemacs))))))
956 (dolist (f (nthcdr 3 form))
957 (elint-form f env))) ; lint the else branch
958 ((and (eq func 'if)
959 (equal test '(featurep (quote emacs))))
960 (elint-form (nth 2 form) env)) ; lint the if branch
961 ;; Process conditional as normal, without handler.
962 (t
963 (elint-form form env t))))
964 env)
965
966 ;;;
967 ;;; Message functions
968 ;;;
969
970 (defvar elint-current-pos) ; dynamically bound in elint-top-form
971
972 (defun elint-log (type string args)
973 (elint-log-message (format "%s:%d:%s: %s"
974 (let ((f (buffer-file-name)))
975 (if f
976 (file-name-nondirectory f)
977 (buffer-name)))
978 (if (boundp 'elint-current-pos)
979 (save-excursion
980 (goto-char elint-current-pos)
981 (1+ (count-lines (point-min)
982 (line-beginning-position))))
983 0) ; unknown position
984 type
985 (apply #'format-message string args))))
986
987 (defun elint-error (string &rest args)
988 "Report a linting error.
989 STRING and ARGS are thrown on `format' to get the message."
990 (elint-log "Error" string args))
991
992 (defun elint-warning (string &rest args)
993 "Report a linting warning.
994 See `elint-error'."
995 (elint-log "Warning" string args))
996
997 (defun elint-output (string)
998 "Print or insert STRING, depending on value of `noninteractive'."
999 (if noninteractive
1000 (message "%s" string)
1001 (insert string "\n")))
1002
1003 (defun elint-log-message (errstr &optional top)
1004 "Insert ERRSTR last in the lint log buffer.
1005 Optional argument TOP non-nil means pretend `elint-top-form-logged' is non-nil."
1006 (with-current-buffer (elint-get-log-buffer)
1007 (goto-char (point-max))
1008 (let ((inhibit-read-only t))
1009 (or (bolp) (newline))
1010 ;; Do we have to say where we are?
1011 (unless (or elint-top-form-logged top)
1012 (let* ((form (elint-top-form-form elint-top-form))
1013 (top (car form)))
1014 (elint-output (cond
1015 ((memq top '(defun defsubst))
1016 (format "\nIn function %s:" (cadr form)))
1017 ((eq top 'defmacro)
1018 (format "\nIn macro %s:" (cadr form)))
1019 ((memq top '(defvar defconst))
1020 (format "\nIn variable %s:" (cadr form)))
1021 (t "\nIn top level expression:"))))
1022 (setq elint-top-form-logged t))
1023 (elint-output errstr))))
1024
1025 (defun elint-clear-log (&optional header)
1026 "Clear the lint log buffer.
1027 Insert HEADER followed by a blank line if non-nil."
1028 (let ((dir default-directory))
1029 (with-current-buffer (elint-get-log-buffer)
1030 (setq default-directory dir)
1031 (let ((inhibit-read-only t))
1032 (erase-buffer)
1033 (if header (insert header "\n"))))))
1034
1035 (defun elint-display-log ()
1036 "Display the lint log buffer."
1037 (let ((pop-up-windows t))
1038 (display-buffer (elint-get-log-buffer))
1039 (sit-for 0)))
1040
1041 (defvar elint-running)
1042
1043 (defun elint-set-mode-line (&optional on)
1044 "Set the mode-line-process of the Elint log buffer."
1045 (with-current-buffer (elint-get-log-buffer)
1046 (and (eq major-mode 'compilation-mode)
1047 (setq mode-line-process
1048 (list (if (or on (bound-and-true-p elint-running))
1049 (propertize ":run" 'face 'compilation-warning)
1050 (propertize ":finished" 'face 'compilation-info)))))))
1051
1052 (defun elint-get-log-buffer ()
1053 "Return a log buffer for elint."
1054 (or (get-buffer elint-log-buffer)
1055 (with-current-buffer (get-buffer-create elint-log-buffer)
1056 (or (eq major-mode 'compilation-mode)
1057 (compilation-mode))
1058 (setq buffer-undo-list t)
1059 (current-buffer))))
1060
1061 ;;;
1062 ;;; Initializing code
1063 ;;;
1064
1065 (defun elint-put-function-args (func args)
1066 "Mark function FUNC as having argument list ARGS."
1067 (and (symbolp func)
1068 args
1069 (not (eq args 'unknown))
1070 (put func 'elint-args args)))
1071
1072 ;;;###autoload
1073 (defun elint-initialize (&optional reinit)
1074 "Initialize elint.
1075 If elint is already initialized, this does nothing, unless
1076 optional prefix argument REINIT is non-nil."
1077 (interactive "P")
1078 (if (and elint-builtin-variables (not reinit))
1079 (message "Elint is already initialized")
1080 (message "Initializing elint...")
1081 (setq elint-builtin-variables (elint-scan-doc-file)
1082 elint-autoloaded-variables (elint-find-autoloaded-variables))
1083 (mapc (lambda (x) (elint-put-function-args (car x) (cdr x)))
1084 (elint-find-builtin-args))
1085 (if elint-unknown-builtin-args
1086 (mapc (lambda (x) (elint-put-function-args (car x) (cdr x)))
1087 elint-unknown-builtin-args))
1088 (when elint-scan-preloaded
1089 (dolist (lib preloaded-file-list)
1090 ;; Skip files that contain nothing of use to us.
1091 (unless (string-match elint-preloaded-skip-re lib)
1092 (setq elint-preloaded-env
1093 (elint-add-required-env elint-preloaded-env nil lib)))))
1094 (message "Initializing elint...done")))
1095
1096
1097 ;; This includes all the built-in and dumped things with documentation.
1098 (defun elint-scan-doc-file ()
1099 "Scan the DOC file for function and variables.
1100 Marks the function with their arguments, and returns a list of variables."
1101 ;; Cribbed from help-fns.el.
1102 (let ((docbuf " *DOC*")
1103 vars sym args)
1104 (save-excursion
1105 (if (get-buffer docbuf)
1106 (progn
1107 (set-buffer docbuf)
1108 (goto-char (point-min)))
1109 (set-buffer (get-buffer-create docbuf))
1110 (insert-file-contents-literally
1111 (expand-file-name internal-doc-file-name doc-directory)))
1112 (while (re-search-forward "\1f\\([VF]\\)" nil t)
1113 (when (setq sym (intern-soft (buffer-substring (point)
1114 (line-end-position))))
1115 (if (string-equal (match-string 1) "V")
1116 ;; Excludes platform-specific stuff not relevant to the
1117 ;; running platform.
1118 (if (boundp sym) (setq vars (cons sym vars)))
1119 ;; Function.
1120 (when (fboundp sym)
1121 (when (re-search-forward "\\(^(fn.*)\\)?\1f" nil t)
1122 (backward-char 1)
1123 ;; FIXME distinguish no args from not found.
1124 (and (setq args (match-string 1))
1125 (setq args
1126 (ignore-errors
1127 (read
1128 (replace-regexp-in-string "^(fn ?" "(" args))))
1129 (elint-put-function-args sym args))))))))
1130 vars))
1131
1132 (defun elint-find-autoloaded-variables ()
1133 "Return a list of all autoloaded variables."
1134 (let (var vars)
1135 (with-temp-buffer
1136 (insert-file-contents (locate-library "loaddefs.el"))
1137 (while (re-search-forward "^(defvar \\([[:alnum:]_-]+\\)" nil t)
1138 (and (setq var (intern-soft (match-string 1)))
1139 (boundp var)
1140 (setq vars (cons var vars)))))
1141 vars))
1142
1143 (defun elint-find-builtins ()
1144 "Return a list of all built-in functions."
1145 (let (subrs)
1146 (mapatoms (lambda (s) (and (subrp (symbol-function s))
1147 (push s subrs))))
1148 subrs))
1149
1150 (defun elint-find-builtin-args (&optional list)
1151 "Return a list of the built-in functions and their arguments.
1152 If LIST is nil, call `elint-find-builtins' to get a list of all built-in
1153 functions, otherwise use LIST.
1154
1155 Each function is represented by a cons cell:
1156 \(function-symbol . args)
1157 If no documentation could be found args will be `unknown'."
1158 (mapcar (lambda (f)
1159 (let ((doc (documentation f t)))
1160 (or (and doc
1161 (string-match "\n\n(fn\\(.*)\\)\\'" doc)
1162 (ignore-errors
1163 ;; "BODY...)" -> "&rest BODY)".
1164 (read (replace-regexp-in-string
1165 "\\([^ ]+\\)\\.\\.\\.)\\'" "&rest \\1)"
1166 (format "(%s %s" f (match-string 1 doc)) t))))
1167 (cons f 'unknown))))
1168 (or list (elint-find-builtins))))
1169
1170 (provide 'elint)
1171
1172 ;;; elint.el ends here