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