]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/elint.el
Add 2012 to FSF copyright years for Emacs files
[gnu-emacs] / lisp / emacs-lisp / elint.el
1 ;;; elint.el --- Lint Emacs Lisp
2
3 ;; Copyright (C) 1997, 2001-2012 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 "\f\nLeaving directory `%s'"
253 default-directory) t)
254 (elint-log-message (format "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 (elint-env-add-env elint-preloaded-env elint-buffer-env))
361 (set (make-local-variable 'elint-last-env-time) (buffer-modified-tick))
362 elint-buffer-forms))
363
364 (defun elint-get-top-forms ()
365 "Collect all the top forms in the current buffer."
366 (save-excursion
367 (let (tops)
368 (goto-char (point-min))
369 (while (elint-find-next-top-form)
370 (let ((elint-current-pos (point)))
371 ;; non-list check could be here too. errors may be out of seq.
372 ;; quoted check cannot be elsewhere, since quotes skipped.
373 (if (looking-back "'")
374 ;; Eg cust-print.el uses ' as a comment syntax.
375 (elint-warning "Skipping quoted form `'%.20s...'"
376 (read (current-buffer)))
377 (condition-case nil
378 (setq tops (cons
379 (elint-make-top-form (read (current-buffer))
380 elint-current-pos)
381 tops))
382 (end-of-file
383 (goto-char elint-current-pos)
384 (error "Missing ')' in top form: %s"
385 (buffer-substring elint-current-pos
386 (line-end-position))))))))
387 (nreverse tops))))
388
389 (defun elint-find-next-top-form ()
390 "Find the next top form from point.
391 Return nil if there are no more forms, t otherwise."
392 (parse-partial-sexp (point) (point-max) nil t)
393 (not (eobp)))
394
395 (defvar elint-env) ; from elint-init-env
396
397 (defun elint-init-form (form)
398 "Process FORM, adding to ELINT-ENV if recognized."
399 (cond
400 ;; Eg nnmaildir seems to use [] as a form of comment syntax.
401 ((not (listp form))
402 (elint-warning "Skipping non-list form `%s'" form))
403 ;; Add defined variable
404 ((memq (car form) '(defvar defconst defcustom))
405 (setq elint-env (elint-env-add-var elint-env (cadr form))))
406 ;; Add function
407 ((memq (car form) '(defun defsubst))
408 (setq elint-env (elint-env-add-func elint-env (cadr form) (nth 2 form))))
409 ;; FIXME needs a handler to say second arg is not a variable when we come
410 ;; to scan the form.
411 ((eq (car form) 'define-derived-mode)
412 (setq elint-env (elint-env-add-func elint-env (cadr form) ())
413 elint-env (elint-env-add-var elint-env (cadr form))
414 elint-env (elint-env-add-var elint-env
415 (intern (format "%s-map" (cadr form))))))
416 ((eq (car form) 'define-minor-mode)
417 (setq elint-env (elint-env-add-func elint-env (cadr form) '(&optional arg))
418 ;; FIXME mode map?
419 elint-env (elint-env-add-var elint-env (cadr form))))
420 ((and (eq (car form) 'easy-menu-define)
421 (cadr form))
422 (setq elint-env (elint-env-add-func elint-env (cadr form) '(event))
423 elint-env (elint-env-add-var elint-env (cadr form))))
424 ;; FIXME it would be nice to check the autoloads are correct.
425 ((eq (car form) 'autoload)
426 (setq elint-env (elint-env-add-func elint-env (cadr (cadr form)) 'unknown)))
427 ((eq (car form) 'declare-function)
428 (setq elint-env (elint-env-add-func
429 elint-env (cadr form)
430 (if (or (< (length form) 4)
431 (eq (nth 3 form) t)
432 (unless (stringp (nth 2 form))
433 (elint-error "Malformed declaration for `%s'"
434 (cadr form))
435 t))
436 'unknown
437 (nth 3 form)))))
438 ((and (eq (car form) 'defalias) (listp (nth 2 form)))
439 ;; If the alias points to something already in the environment,
440 ;; add the alias to the environment with the same arguments.
441 ;; FIXME symbol-function, eg backquote.el?
442 (let ((def (elint-env-find-func elint-env (cadr (nth 2 form)))))
443 (setq elint-env (elint-env-add-func elint-env (cadr (cadr form))
444 (if def (cadr def) 'unknown)))))
445 ;; Add macro, both as a macro and as a function
446 ((eq (car form) 'defmacro)
447 (setq elint-env (elint-env-add-macro elint-env (cadr form)
448 (cons 'lambda (cddr form)))
449 elint-env (elint-env-add-func elint-env (cadr form) (nth 2 form))))
450 ((and (eq (car form) 'put)
451 (= 4 (length form))
452 (eq (car-safe (cadr form)) 'quote)
453 (equal (nth 2 form) '(quote error-conditions)))
454 (set (make-local-variable 'elint-extra-errors)
455 (cons (cadr (cadr form)) elint-extra-errors)))
456 ((eq (car form) 'provide)
457 (add-to-list 'elint-features (eval (cadr form))))
458 ;; Import variable definitions
459 ((memq (car form) '(require cc-require cc-require-when-compile))
460 (let ((name (eval (cadr form)))
461 (file (eval (nth 2 form)))
462 (elint-doing-cl (bound-and-true-p elint-doing-cl)))
463 (unless (memq name elint-features)
464 (add-to-list 'elint-features name)
465 ;; cl loads cl-macs in an opaque manner.
466 ;; Since cl-macs requires cl, we can just process cl-macs.
467 (and (eq name 'cl) (not elint-doing-cl)
468 ;; We need cl if elint-form is to be able to expand cl macros.
469 (require 'cl)
470 (setq name 'cl-macs
471 file nil
472 elint-doing-cl t)) ; blech
473 (setq elint-env (elint-add-required-env elint-env name file))))))
474 elint-env)
475
476 (defun elint-init-env (forms)
477 "Initialize the environment from FORMS."
478 (let ((elint-env (elint-make-env))
479 form)
480 (while forms
481 (setq form (elint-top-form-form (car forms))
482 forms (cdr forms))
483 ;; FIXME eval-when-compile should be treated differently (macros).
484 ;; Could bind something that makes elint-init-form only check
485 ;; defmacros.
486 (if (memq (car-safe form)
487 '(eval-and-compile eval-when-compile progn prog1 prog2
488 with-no-warnings))
489 (mapc 'elint-init-form (cdr form))
490 (elint-init-form form)))
491 elint-env))
492
493 (defun elint-add-required-env (env name file)
494 "Augment ENV with the variables defined by feature NAME in FILE."
495 (condition-case err
496 (let* ((libname (if (stringp file)
497 file
498 (symbol-name name)))
499
500 ;; First try to find .el files, then the raw name
501 (lib1 (locate-library (concat libname ".el") t))
502 (lib (or lib1 (locate-library libname t))))
503 ;; Clear the messages :-/
504 ;; (Messes up the "Initializing elint..." message.)
505 ;;; (message nil)
506 (if lib
507 (with-current-buffer (find-file-noselect lib)
508 ;; FIXME this doesn't use a temp buffer, because it
509 ;; stores the result in buffer-local variables so that
510 ;; it can be reused.
511 (elint-update-env)
512 (setq env (elint-env-add-env env elint-buffer-env)))
513 ;;; (with-temp-buffer
514 ;;; (insert-file-contents lib)
515 ;;; (with-syntax-table emacs-lisp-mode-syntax-table
516 ;;; (elint-update-env))
517 ;;; (setq env (elint-env-add-env env elint-buffer-env))))
518 ;;(message "Elint processed (require '%s)" name))
519 (error "%s.el not found in load-path" libname)))
520 (error
521 (message "Can't get variables from require'd library %s: %s"
522 name (error-message-string err))))
523 env)
524
525 (defvar elint-top-form nil
526 "The currently linted top form, or nil.")
527
528 (defvar elint-top-form-logged nil
529 "The value t if the currently linted top form has been mentioned in the log buffer.")
530
531 (defun elint-top-form (form)
532 "Lint a top FORM."
533 (let ((elint-top-form form)
534 (elint-top-form-logged nil)
535 (elint-current-pos (elint-top-form-pos form)))
536 (elint-form (elint-top-form-form form) elint-buffer-env)))
537
538 ;;;
539 ;;; General form linting functions
540 ;;;
541
542 (defconst elint-special-forms
543 '((let . elint-check-let-form)
544 (let* . elint-check-let-form)
545 (setq . elint-check-setq-form)
546 (quote . elint-check-quote-form)
547 (function . elint-check-quote-form)
548 (cond . elint-check-cond-form)
549 (lambda . elint-check-defun-form)
550 (function . elint-check-function-form)
551 (setq-default . elint-check-setq-form)
552 (defalias . elint-check-defalias-form)
553 (defun . elint-check-defun-form)
554 (defsubst . elint-check-defun-form)
555 (defmacro . elint-check-defun-form)
556 (defvar . elint-check-defvar-form)
557 (defconst . elint-check-defvar-form)
558 (defcustom . elint-check-defcustom-form)
559 (macro . elint-check-macro-form)
560 (condition-case . elint-check-condition-case-form)
561 (if . elint-check-conditional-form)
562 (when . elint-check-conditional-form)
563 (unless . elint-check-conditional-form)
564 (and . elint-check-conditional-form)
565 (or . elint-check-conditional-form))
566 "Functions to call when some special form should be linted.")
567
568 (defun elint-form (form env &optional nohandler)
569 "Lint FORM in the environment ENV.
570 Optional argument NOHANDLER non-nil means ignore `elint-special-forms'.
571 Returns the environment created by the form."
572 (cond
573 ((consp form)
574 (let ((func (cdr (assq (car form) elint-special-forms))))
575 (if (and func (not nohandler))
576 ;; Special form
577 (funcall func form env)
578
579 (let* ((func (car form))
580 (args (elint-get-args func env))
581 (argsok t))
582 (cond
583 ((eq args 'undefined)
584 (setq argsok nil)
585 (or (memq 'undefined-functions elint-ignored-warnings)
586 (elint-error "Call to undefined function: %s" func)))
587
588 ((eq args 'unknown) nil)
589
590 (t (setq argsok (elint-match-args form args))))
591
592 ;; Is this a macro?
593 (if (elint-env-macrop env func)
594 ;; Macro defined in buffer, expand it
595 (if argsok
596 ;; FIXME error if macro uses macro, eg bytecomp.el.
597 (condition-case nil
598 (elint-form
599 (macroexpand form (elint-env-macro-env env)) env)
600 (error
601 (or (memq 'macro-expansion elint-ignored-warnings)
602 (elint-error "Elint failed to expand macro: %s" func))
603 env))
604 env)
605
606 (let ((fcode (if (symbolp func)
607 (if (fboundp func)
608 (indirect-function func))
609 func)))
610 (if (and (listp fcode) (eq (car fcode) 'macro))
611 ;; Macro defined outside buffer
612 (if argsok
613 (elint-form (macroexpand form) env)
614 env)
615 ;; Function, lint its parameters
616 (elint-forms (cdr form) env))))))))
617 ((symbolp form)
618 ;; :foo variables are quoted
619 (and (/= (aref (symbol-name form) 0) ?:)
620 (not (memq 'unbound-reference elint-ignored-warnings))
621 (elint-unbound-variable form env)
622 (elint-warning "Reference to unbound symbol: %s" form))
623 env)
624
625 (t env)))
626
627 (defun elint-forms (forms env)
628 "Lint the FORMS, accumulating an environment, starting with ENV."
629 ;; grumblegrumbletailrecursiongrumblegrumble
630 (if (listp forms)
631 (dolist (f forms env)
632 (setq env (elint-form f env)))
633 ;; Loop macro?
634 (elint-error "Elint failed to parse form: %s" forms)
635 env))
636
637 (defvar elint-bound-variable nil
638 "Name of a temporarily bound symbol.")
639
640 (defun elint-unbound-variable (var env)
641 "Return t if VAR is unbound in ENV."
642 ;; #1063 suggests adding (symbol-file var) here, but I don't think
643 ;; this is right, because it depends on what files you happen to have
644 ;; loaded at the time, which might not be the same when the code runs.
645 ;; It also suggests adding:
646 ;; (numberp (get var 'variable-documentation))
647 ;; (numberp (cdr-safe (get var 'variable-documentation)))
648 ;; but this is not needed now elint-scan-doc-file exists.
649 (not (or (memq var '(nil t))
650 (eq var elint-bound-variable)
651 (elint-env-find-var env var)
652 (memq var elint-builtin-variables)
653 (memq var elint-autoloaded-variables)
654 (memq var elint-standard-variables))))
655
656 ;;;
657 ;;; Function argument checking
658 ;;;
659
660 (defun elint-match-args (arglist argpattern)
661 "Match ARGLIST against ARGPATTERN."
662 (let ((state 'all)
663 (al (cdr arglist))
664 (ap argpattern)
665 (ok t))
666 (while
667 (cond
668 ((and (null al) (null ap)) nil)
669 ((eq (car ap) '&optional)
670 (setq state 'optional)
671 (setq ap (cdr ap))
672 t)
673 ((eq (car ap) '&rest)
674 nil)
675 ((or (and (eq state 'all) (or (null al) (null ap)))
676 (and (eq state 'optional) (and al (null ap))))
677 (elint-error "Wrong number of args: %s, %s" arglist argpattern)
678 (setq ok nil)
679 nil)
680 ((and (eq state 'optional) (null al))
681 nil)
682 (t (setq al (cdr al)
683 ap (cdr ap))
684 t)))
685 ok))
686
687 (defvar elint-bound-function nil
688 "Name of a temporarily bound function symbol.")
689
690 (defun elint-get-args (func env)
691 "Find the args of FUNC in ENV.
692 Returns `unknown' if we couldn't find arguments."
693 (let ((f (elint-env-find-func env func)))
694 (if f
695 (cadr f)
696 (if (symbolp func)
697 (if (eq func elint-bound-function)
698 'unknown
699 (if (fboundp func)
700 (let ((fcode (indirect-function func)))
701 (if (subrp fcode)
702 ;; FIXME builtins with no args have args = nil.
703 (or (get func 'elint-args) 'unknown)
704 (elint-find-args-in-code fcode)))
705 'undefined))
706 (elint-find-args-in-code func)))))
707
708 (defun elint-find-args-in-code (code)
709 "Extract the arguments from CODE.
710 CODE can be a lambda expression, a macro, or byte-compiled code."
711 (cond
712 ((byte-code-function-p code)
713 (aref code 0))
714 ((and (listp code) (eq (car code) 'lambda))
715 (car (cdr code)))
716 ((and (listp code) (eq (car code) 'macro))
717 (elint-find-args-in-code (cdr code)))
718 (t 'unknown)))
719
720 ;;;
721 ;;; Functions to check some special forms
722 ;;;
723
724 (defun elint-check-cond-form (form env)
725 "Lint a cond FORM in ENV."
726 (dolist (f (cdr form))
727 (if (consp f)
728 (let ((test (car f)))
729 (cond ((equal test '(featurep (quote xemacs))))
730 ((equal test '(not (featurep (quote emacs)))))
731 ;; FIXME (and (boundp 'foo)
732 ((and (eq (car-safe test) 'fboundp)
733 (= 2 (length test))
734 (eq (car-safe (cadr test)) 'quote))
735 (let ((elint-bound-function (cadr (cadr test))))
736 (elint-forms f env)))
737 ((and (eq (car-safe test) 'boundp)
738 (= 2 (length test))
739 (eq (car-safe (cadr test)) 'quote))
740 (let ((elint-bound-variable (cadr (cadr test))))
741 (elint-forms f env)))
742 (t (elint-forms f env))))
743 (elint-error "cond clause should be a list: %s" f)))
744 env)
745
746 (defun elint-check-defun-form (form env)
747 "Lint a defun/defmacro/lambda FORM in ENV."
748 (setq form (if (eq (car form) 'lambda) (cdr form) (cddr form)))
749 (mapc (lambda (p)
750 (or (memq p '(&optional &rest))
751 (setq env (elint-env-add-var env p))))
752 (car form))
753 (elint-forms (cdr form) env))
754
755 (defun elint-check-defalias-form (form env)
756 "Lint a defalias FORM in ENV."
757 (let ((alias (cadr form))
758 (target (nth 2 form)))
759 (and (eq (car-safe alias) 'quote)
760 (eq (car-safe target) 'quote)
761 (eq (elint-get-args (cadr target) env) 'undefined)
762 (elint-warning "Alias `%s' has unknown target `%s'"
763 (cadr alias) (cadr target))))
764 (elint-form form env t))
765
766 (defun elint-check-let-form (form env)
767 "Lint the let/let* FORM in ENV."
768 (let ((varlist (cadr form)))
769 (if (not varlist)
770 (if (> (length form) 2)
771 ;; An empty varlist is not really an error. Eg some cl macros
772 ;; can expand to such a form.
773 (progn
774 (or (memq 'empty-let elint-ignored-warnings)
775 (elint-warning "Empty varlist in let: %s" form))
776 ;; Lint the body forms
777 (elint-forms (cddr form) env))
778 (elint-error "Malformed let: %s" form)
779 env)
780 ;; Check for (let (a (car b)) ...) type of error
781 (if (and (= (length varlist) 2)
782 (symbolp (car varlist))
783 (listp (car (cdr varlist)))
784 (fboundp (car (car (cdr varlist)))))
785 (elint-warning "Suspect varlist: %s" form))
786 ;; Add variables to environment, and check the init values
787 (let ((newenv env))
788 (mapc (lambda (s)
789 (cond
790 ((symbolp s)
791 (setq newenv (elint-env-add-var newenv s)))
792 ((and (consp s) (<= (length s) 2))
793 (elint-form (cadr s)
794 (if (eq (car form) 'let)
795 env
796 newenv))
797 (setq newenv
798 (elint-env-add-var newenv (car s))))
799 (t (elint-error
800 "Malformed `let' declaration: %s" s))))
801 varlist)
802
803 ;; Lint the body forms
804 (elint-forms (cddr form) newenv)))))
805
806 (defun elint-check-setq-form (form env)
807 "Lint the setq FORM in ENV."
808 (or (= (mod (length form) 2) 1)
809 ;; (setq foo) is valid and equivalent to (setq foo nil).
810 (elint-warning "Missing value in setq: %s" form))
811 (let ((newenv env)
812 sym val)
813 (setq form (cdr form))
814 (while form
815 (setq sym (car form)
816 val (car (cdr form))
817 form (cdr (cdr form)))
818 (if (symbolp sym)
819 (and (not (memq 'unbound-assignment elint-ignored-warnings))
820 (elint-unbound-variable sym newenv)
821 (elint-warning "Setting previously unbound symbol: %s" sym))
822 (elint-error "Setting non-symbol in setq: %s" sym))
823 (elint-form val newenv)
824 (if (symbolp sym)
825 (setq newenv (elint-env-add-var newenv sym))))
826 newenv))
827
828 (defun elint-check-defvar-form (form env)
829 "Lint the defvar/defconst FORM in ENV."
830 (if (or (= (length form) 2)
831 (= (length form) 3)
832 ;; Eg the defcalcmodevar macro can expand with a nil doc-string.
833 (and (= (length form) 4) (string-or-null-p (nth 3 form))))
834 (elint-env-add-global-var (elint-form (nth 2 form) env)
835 (car (cdr form)))
836 (elint-error "Malformed variable declaration: %s" form)
837 env))
838
839 (defun elint-check-defcustom-form (form env)
840 "Lint the defcustom FORM in ENV."
841 (if (and (> (length form) 3)
842 ;; even no. of keyword/value args ?
843 (zerop (logand (length form) 1)))
844 (elint-env-add-global-var (elint-form (nth 2 form) env)
845 (car (cdr form)))
846 (elint-error "Malformed variable declaration: %s" form)
847 env))
848
849 (defun elint-check-function-form (form env)
850 "Lint the function FORM in ENV."
851 (let ((func (car (cdr-safe form))))
852 (cond
853 ((symbolp func)
854 (or (elint-env-find-func env func)
855 ;; FIXME potentially bogus, since it uses the current
856 ;; environment rather than a clean one.
857 (fboundp func)
858 (elint-warning "Reference to undefined function: %s" form))
859 env)
860 ((and (consp func) (memq (car func) '(lambda macro)))
861 (elint-form func env))
862 ((stringp func) env)
863 (t (elint-error "Not a function object: %s" form)
864 env))))
865
866 (defun elint-check-quote-form (form env)
867 "Lint the quote FORM in ENV."
868 env)
869
870 (defun elint-check-macro-form (form env)
871 "Check the macro FORM in ENV."
872 (elint-check-function-form (list (car form) (cdr form)) env))
873
874 (defun elint-check-condition-case-form (form env)
875 "Check the `condition-case' FORM in ENV."
876 (let ((resenv env))
877 (if (< (length form) 3)
878 (elint-error "Malformed condition-case: %s" form)
879 (or (symbolp (cadr form))
880 (elint-warning "First parameter should be a symbol: %s" form))
881 (setq resenv (elint-form (nth 2 form) env))
882 (let ((newenv (elint-env-add-var env (cadr form)))
883 errlist)
884 (dolist (err (nthcdr 3 form))
885 (setq errlist (car err))
886 (mapc (lambda (s)
887 (or (get s 'error-conditions)
888 (get s 'error-message)
889 (memq s elint-extra-errors)
890 (elint-warning
891 "Not an error symbol in error handler: %s" s)))
892 (cond
893 ((symbolp errlist) (list errlist))
894 ((listp errlist) errlist)
895 (t (elint-error "Bad error list in error handler: %s"
896 errlist)
897 nil)))
898 (elint-forms (cdr err) newenv))))
899 resenv))
900
901 ;; For the featurep parts, an alternative is to have
902 ;; elint-get-top-forms skip the irrelevant branches.
903 (defun elint-check-conditional-form (form env)
904 "Check the when/unless/and/or FORM in ENV.
905 Does basic handling of `featurep' tests."
906 (let ((func (car form))
907 (test (cadr form))
908 sym)
909 ;; Misses things like (and t (featurep 'xemacs))
910 ;; Check byte-compile-maybe-guarded.
911 (cond ((and (memq func '(when and))
912 (eq (car-safe test) 'boundp)
913 (= 2 (length test))
914 (eq (car-safe (cadr test)) 'quote))
915 ;; Cf elint-check-let-form, which modifies the whole ENV.
916 (let ((elint-bound-variable (cadr (cadr test))))
917 (elint-form form env t)))
918 ((and (memq func '(when and))
919 (eq (car-safe test) 'fboundp)
920 (= 2 (length test))
921 (eq (car-safe (cadr test)) 'quote))
922 (let ((elint-bound-function (cadr (cadr test))))
923 (elint-form form env t)))
924 ;; Let's not worry about (if (not (boundp...
925 ((and (eq func 'if)
926 (eq (car-safe test) 'boundp)
927 (= 2 (length test))
928 (eq (car-safe (cadr test)) 'quote))
929 (let ((elint-bound-variable (cadr (cadr test))))
930 (elint-form (nth 2 form) env))
931 (dolist (f (nthcdr 3 form))
932 (elint-form f env)))
933 ((and (eq func 'if)
934 (eq (car-safe test) 'fboundp)
935 (= 2 (length test))
936 (eq (car-safe (cadr test)) 'quote))
937 (let ((elint-bound-function (cadr (cadr test))))
938 (elint-form (nth 2 form) env))
939 (dolist (f (nthcdr 3 form))
940 (elint-form f env)))
941 ((and (memq func '(when and)) ; skip all
942 (or (null test)
943 (member test '((featurep (quote xemacs))
944 (not (featurep (quote emacs)))))
945 (and (eq (car-safe test) 'and)
946 (equal (car-safe (cdr test))
947 '(featurep (quote xemacs)))))))
948 ((and (memq func '(unless or))
949 (equal test '(featurep (quote emacs)))))
950 ((and (eq func 'if)
951 (or (null test) ; eg custom-browse-insert-prefix
952 (member test '((featurep (quote xemacs))
953 (not (featurep (quote emacs)))))
954 (and (eq (car-safe test) 'and)
955 (equal (car-safe (cdr test))
956 '(featurep (quote xemacs))))))
957 (dolist (f (nthcdr 3 form))
958 (elint-form f env))) ; lint the else branch
959 ((and (eq func 'if)
960 (equal test '(featurep (quote emacs))))
961 (elint-form (nth 2 form) env)) ; lint the if branch
962 ;; Process conditional as normal, without handler.
963 (t
964 (elint-form form env t))))
965 env)
966
967 ;;;
968 ;;; Message functions
969 ;;;
970
971 (defvar elint-current-pos) ; dynamically bound in elint-top-form
972
973 (defun elint-log (type string args)
974 (elint-log-message (format "%s:%d:%s: %s"
975 (let ((f (buffer-file-name)))
976 (if f
977 (file-name-nondirectory f)
978 (buffer-name)))
979 (if (boundp 'elint-current-pos)
980 (save-excursion
981 (goto-char elint-current-pos)
982 (1+ (count-lines (point-min)
983 (line-beginning-position))))
984 0) ; unknown position
985 type
986 (apply 'format string args))))
987
988 (defun elint-error (string &rest args)
989 "Report a linting error.
990 STRING and ARGS are thrown on `format' to get the message."
991 (elint-log "Error" string args))
992
993 (defun elint-warning (string &rest args)
994 "Report a linting warning.
995 See `elint-error'."
996 (elint-log "Warning" string args))
997
998 (defun elint-output (string)
999 "Print or insert STRING, depending on value of `noninteractive'."
1000 (if noninteractive
1001 (message "%s" string)
1002 (insert string "\n")))
1003
1004 (defun elint-log-message (errstr &optional top)
1005 "Insert ERRSTR last in the lint log buffer.
1006 Optional argument TOP non-nil means pretend `elint-top-form-logged' is non-nil."
1007 (with-current-buffer (elint-get-log-buffer)
1008 (goto-char (point-max))
1009 (let ((inhibit-read-only t))
1010 (or (bolp) (newline))
1011 ;; Do we have to say where we are?
1012 (unless (or elint-top-form-logged top)
1013 (let* ((form (elint-top-form-form elint-top-form))
1014 (top (car form)))
1015 (elint-output (cond
1016 ((memq top '(defun defsubst))
1017 (format "\nIn function %s:" (cadr form)))
1018 ((eq top 'defmacro)
1019 (format "\nIn macro %s:" (cadr form)))
1020 ((memq top '(defvar defconst))
1021 (format "\nIn variable %s:" (cadr form)))
1022 (t "\nIn top level expression:"))))
1023 (setq elint-top-form-logged t))
1024 (elint-output errstr))))
1025
1026 (defun elint-clear-log (&optional header)
1027 "Clear the lint log buffer.
1028 Insert HEADER followed by a blank line if non-nil."
1029 (let ((dir default-directory))
1030 (with-current-buffer (elint-get-log-buffer)
1031 (setq default-directory dir)
1032 (let ((inhibit-read-only t))
1033 (erase-buffer)
1034 (if header (insert header "\n"))))))
1035
1036 (defun elint-display-log ()
1037 "Display the lint log buffer."
1038 (let ((pop-up-windows t))
1039 (display-buffer (elint-get-log-buffer))
1040 (sit-for 0)))
1041
1042 (defvar elint-running)
1043
1044 (defun elint-set-mode-line (&optional on)
1045 "Set the mode-line-process of the Elint log buffer."
1046 (with-current-buffer (elint-get-log-buffer)
1047 (and (eq major-mode 'compilation-mode)
1048 (setq mode-line-process
1049 (list (if (or on (bound-and-true-p elint-running))
1050 (propertize ":run" 'face 'compilation-warning)
1051 (propertize ":finished" 'face 'compilation-info)))))))
1052
1053 (defun elint-get-log-buffer ()
1054 "Return a log buffer for elint."
1055 (or (get-buffer elint-log-buffer)
1056 (with-current-buffer (get-buffer-create elint-log-buffer)
1057 (or (eq major-mode 'compilation-mode)
1058 (compilation-mode))
1059 (setq buffer-undo-list t)
1060 (current-buffer))))
1061
1062 ;;;
1063 ;;; Initializing code
1064 ;;;
1065
1066 (defun elint-put-function-args (func args)
1067 "Mark function FUNC as having argument list ARGS."
1068 (and (symbolp func)
1069 args
1070 (not (eq args 'unknown))
1071 (put func 'elint-args args)))
1072
1073 ;;;###autoload
1074 (defun elint-initialize (&optional reinit)
1075 "Initialize elint.
1076 If elint is already initialized, this does nothing, unless
1077 optional prefix argument REINIT is non-nil."
1078 (interactive "P")
1079 (if (and elint-builtin-variables (not reinit))
1080 (message "Elint is already initialized")
1081 (message "Initializing elint...")
1082 (setq elint-builtin-variables (elint-scan-doc-file)
1083 elint-autoloaded-variables (elint-find-autoloaded-variables))
1084 (mapc (lambda (x) (elint-put-function-args (car x) (cdr x)))
1085 (elint-find-builtin-args))
1086 (if elint-unknown-builtin-args
1087 (mapc (lambda (x) (elint-put-function-args (car x) (cdr x)))
1088 elint-unknown-builtin-args))
1089 (when elint-scan-preloaded
1090 (dolist (lib preloaded-file-list)
1091 ;; Skip files that contain nothing of use to us.
1092 (unless (string-match elint-preloaded-skip-re lib)
1093 (setq elint-preloaded-env
1094 (elint-add-required-env elint-preloaded-env nil lib)))))
1095 (message "Initializing elint...done")))
1096
1097
1098 ;; This includes all the built-in and dumped things with documentation.
1099 (defun elint-scan-doc-file ()
1100 "Scan the DOC file for function and variables.
1101 Marks the function with their arguments, and returns a list of variables."
1102 ;; Cribbed from help-fns.el.
1103 (let ((docbuf " *DOC*")
1104 vars sym args)
1105 (save-excursion
1106 (if (get-buffer docbuf)
1107 (progn
1108 (set-buffer docbuf)
1109 (goto-char (point-min)))
1110 (set-buffer (get-buffer-create docbuf))
1111 (insert-file-contents-literally
1112 (expand-file-name internal-doc-file-name doc-directory)))
1113 (while (re-search-forward "\1f\\([VF]\\)" nil t)
1114 (when (setq sym (intern-soft (buffer-substring (point)
1115 (line-end-position))))
1116 (if (string-equal (match-string 1) "V")
1117 ;; Excludes platform-specific stuff not relevant to the
1118 ;; running platform.
1119 (if (boundp sym) (setq vars (cons sym vars)))
1120 ;; Function.
1121 (when (fboundp sym)
1122 (when (re-search-forward "\\(^(fn.*)\\)?\1f" nil t)
1123 (backward-char 1)
1124 ;; FIXME distinguish no args from not found.
1125 (and (setq args (match-string 1))
1126 (setq args
1127 (ignore-errors
1128 (read
1129 (replace-regexp-in-string "^(fn ?" "(" args))))
1130 (elint-put-function-args sym args))))))))
1131 vars))
1132
1133 (defun elint-find-autoloaded-variables ()
1134 "Return a list of all autoloaded variables."
1135 (let (var vars)
1136 (with-temp-buffer
1137 (insert-file-contents (locate-library "loaddefs.el"))
1138 (while (re-search-forward "^(defvar \\([[:alnum:]_-]+\\)" nil t)
1139 (and (setq var (intern-soft (match-string 1)))
1140 (boundp var)
1141 (setq vars (cons var vars)))))
1142 vars))
1143
1144 (defun elint-find-builtins ()
1145 "Return a list of all built-in functions."
1146 (let (subrs)
1147 (mapatoms (lambda (s) (and (fboundp s) (subrp (symbol-function s))
1148 (setq subrs (cons s subrs)))))
1149 subrs))
1150
1151 (defun elint-find-builtin-args (&optional list)
1152 "Return a list of the built-in functions and their arguments.
1153 If LIST is nil, call `elint-find-builtins' to get a list of all built-in
1154 functions, otherwise use LIST.
1155
1156 Each function is represented by a cons cell:
1157 \(function-symbol . args)
1158 If no documentation could be found args will be `unknown'."
1159 (mapcar (lambda (f)
1160 (let ((doc (documentation f t)))
1161 (or (and doc
1162 (string-match "\n\n(fn\\(.*)\\)\\'" doc)
1163 (ignore-errors
1164 ;; "BODY...)" -> "&rest BODY)".
1165 (read (replace-regexp-in-string
1166 "\\([^ ]+\\)\\.\\.\\.)\\'" "&rest \\1)"
1167 (format "(%s %s" f (match-string 1 doc)) t))))
1168 (cons f 'unknown))))
1169 (or list (elint-find-builtins))))
1170
1171 (provide 'elint)
1172
1173 ;;; elint.el ends here