Stylistic changes in tramp-cache.el
[emacs.git] / lisp / emacs-lisp / elint.el
blobcce9553ff6ad5e3b208bcab0607fd35a83aba772
1 ;;; elint.el --- Lint Emacs Lisp -*- lexical-binding: t -*-
3 ;; Copyright (C) 1997, 2001-2017 Free Software Foundation, Inc.
5 ;; Author: Peter Liljenberg <petli@lysator.liu.se>
6 ;; Created: May 1997
7 ;; Keywords: lisp
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Commentary:
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.
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.
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.
38 ;;; To do:
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.
47 ;;; Code:
49 (defgroup elint nil
50 "Linting for Emacs Lisp."
51 :prefix "elint-"
52 :group 'maint)
54 (defcustom elint-log-buffer "*Elint*"
55 "The buffer in which to log lint messages."
56 :type 'string
57 :safe 'stringp
58 :group 'elint)
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")
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))
104 value)))))
105 :version "23.2"
106 :group 'elint)
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")
117 ;;; Data
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.")
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.")
134 (defvar elint-autoloaded-variables nil
135 "List of `loaddefs.el' variables. Set by `elint-initialize'.")
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.")
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.")
147 (defvar elint-extra-errors '(file-locked file-supersession ftp-error)
148 "Errors without `error-message' or `error-conditions' properties.")
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.")
157 (defvar elint-running)
158 (defvar elint-current-pos) ; dynamically bound in elint-top-form
161 ;;; ADT: top-form
164 (defsubst elint-make-top-form (form pos)
165 "Create a top form.
166 FORM is the form, and POS is the point where it starts in the buffer."
167 (cons form pos))
169 (defsubst elint-top-form-form (top-form)
170 "Extract the form from a TOP-FORM."
171 (car top-form))
173 (defsubst elint-top-form-pos (top-form)
174 "Extract the position from a TOP-FORM."
175 (cdr top-form))
178 ;;; ADT: env
181 (defsubst elint-make-env ()
182 "Create an empty environment."
183 (list (list nil) nil nil))
185 (defsubst elint-env-add-env (env newenv)
186 "Augment ENV with NEWENV.
187 None of them is modified, and the new env is returned."
188 (list (append (car env) (car newenv))
189 (append (cadr env) (cadr newenv))
190 (append (car (cdr (cdr env))) (car (cdr (cdr newenv))))))
192 (defsubst elint-env-add-var (env var)
193 "Augment ENV with the variable VAR.
194 The new environment is returned, the old is unmodified."
195 (cons (cons (list var) (car env)) (cdr env)))
197 (defsubst elint-env-add-global-var (env var)
198 "Augment ENV with the variable VAR.
199 ENV is modified so VAR is seen everywhere.
200 ENV is returned."
201 (nconc (car env) (list (list var)))
202 env)
204 (defsubst elint-env-find-var (env var)
205 "Non-nil if ENV contains the variable VAR.
206 Actually, a list with VAR as a single element is returned."
207 (assq var (car env)))
209 (defsubst elint-env-add-func (env func args)
210 "Augment ENV with the function FUNC, which has the arguments ARGS.
211 The new environment is returned, the old is unmodified."
212 (list (car env)
213 (cons (list func args) (cadr env))
214 (car (cdr (cdr env)))))
216 (defsubst elint-env-find-func (env func)
217 "Non-nil if ENV contains the function FUNC.
218 Actually, a list of (FUNC ARGS) is returned."
219 (assq func (cadr env)))
221 (defsubst elint-env-add-macro (env macro def)
222 "Augment ENV with the macro named MACRO.
223 DEF is the macro definition (a lambda expression or similar).
224 The new environment is returned, the old is unmodified."
225 (list (car env)
226 (cadr env)
227 (cons (cons macro def) (car (cdr (cdr env))))))
229 (defsubst elint-env-macro-env (env)
230 "Return the macro environment of ENV.
231 This environment can be passed to `macroexpand'."
232 (car (cdr (cdr env))))
234 (defsubst elint-env-macrop (env macro)
235 "Non-nil if ENV contains MACRO."
236 (assq macro (elint-env-macro-env env)))
239 ;;; User interface
242 ;;;###autoload
243 (defun elint-file (file)
244 "Lint the file FILE."
245 (interactive "fElint file: ")
246 (setq file (expand-file-name file))
247 (or elint-builtin-variables
248 (elint-initialize))
249 (let ((dir (file-name-directory file)))
250 (let ((default-directory dir))
251 (elint-display-log))
252 (elint-set-mode-line t)
253 (with-current-buffer elint-log-buffer
254 (unless (string-equal default-directory dir)
255 (elint-log-message (format-message "\f\nLeaving directory `%s'"
256 default-directory) t)
257 (elint-log-message (format-message "Entering directory `%s'" dir) t)
258 (setq default-directory dir))))
259 (let ((str (format "Linting file %s" file)))
260 (message "%s..." str)
261 (or noninteractive
262 (elint-log-message (format "\f\n%s at %s" str (current-time-string)) t))
263 ;; elint-current-buffer clears log.
264 (with-temp-buffer
265 (insert-file-contents file)
266 (let ((buffer-file-name file)
267 (max-lisp-eval-depth (max 1000 max-lisp-eval-depth)))
268 (with-syntax-table emacs-lisp-mode-syntax-table
269 (mapc 'elint-top-form (elint-update-env)))))
270 (elint-set-mode-line)
271 (message "%s...done" str)))
273 ;; cf byte-recompile-directory.
274 ;;;###autoload
275 (defun elint-directory (directory)
276 "Lint all the .el files in DIRECTORY.
277 A complicated directory may require a lot of memory."
278 (interactive "DElint directory: ")
279 (let ((elint-running t))
280 (dolist (file (directory-files directory t))
281 ;; Bytecomp has emacs-lisp-file-regexp.
282 (when (and (string-match "\\.el\\'" file)
283 (file-readable-p file)
284 (not (auto-save-file-name-p file)))
285 (if (string-match elint-directory-skip-re file)
286 (message "Skipping file %s" file)
287 (elint-file file)))))
288 (elint-set-mode-line))
290 ;;;###autoload
291 (defun elint-current-buffer ()
292 "Lint the current buffer.
293 If necessary, this first calls `elint-initialize'."
294 (interactive)
295 (or elint-builtin-variables
296 (elint-initialize))
297 (elint-clear-log (format "Linting %s" (or (buffer-file-name)
298 (buffer-name))))
299 (elint-display-log)
300 (elint-set-mode-line t)
301 (mapc 'elint-top-form (elint-update-env))
302 ;; Tell the user we're finished. This is terribly kludgy: we set
303 ;; elint-top-form-logged so elint-log-message doesn't print the
304 ;; ** top form ** header...
305 (elint-set-mode-line)
306 (elint-log-message "\nLinting finished.\n" t))
309 ;;;###autoload
310 (defun elint-defun ()
311 "Lint the function at point.
312 If necessary, this first calls `elint-initialize'."
313 (interactive)
314 (or elint-builtin-variables
315 (elint-initialize))
316 (save-excursion
317 (or (beginning-of-defun) (error "Lint what?"))
318 (let ((pos (point))
319 (def (read (current-buffer))))
320 (elint-display-log)
321 (elint-update-env)
322 (elint-top-form (elint-make-top-form def pos)))))
325 ;;; Top form functions
328 (defvar elint-buffer-env nil
329 "The environment of an elisp buffer.
330 Will be local in linted buffers.")
332 (defvar elint-buffer-forms nil
333 "The top forms in a buffer.
334 Will be local in linted buffers.")
336 (defvar elint-last-env-time nil
337 "The last time the buffers env was updated.
338 Is measured in buffer-modified-ticks and is local in linted buffers.")
340 ;; This is a minor optimization. It is local to every buffer, and so
341 ;; does not prevent recursive requires. It does not list the requires
342 ;; of requires.
343 (defvar elint-features nil
344 "List of all libraries this buffer has required, or that have been provided.")
346 (defun elint-update-env ()
347 "Update the elint environment in the current buffer.
348 Don't do anything if the buffer hasn't been changed since this
349 function was called the last time.
350 Returns the forms."
351 (if (and (local-variable-p 'elint-buffer-env (current-buffer))
352 (local-variable-p 'elint-buffer-forms (current-buffer))
353 (local-variable-p 'elint-last-env-time (current-buffer))
354 (= (buffer-modified-tick) elint-last-env-time))
355 ;; Env is up to date
356 elint-buffer-forms
357 ;; Remake env
358 (set (make-local-variable 'elint-buffer-forms) (elint-get-top-forms))
359 (set (make-local-variable 'elint-features) nil)
360 (set (make-local-variable 'elint-buffer-env)
361 (elint-init-env elint-buffer-forms))
362 (if elint-preloaded-env
363 ;; FIXME: This doesn't do anything! Should we setq the result to
364 ;; elint-buffer-env?
365 (elint-env-add-env elint-preloaded-env elint-buffer-env))
366 (set (make-local-variable 'elint-last-env-time) (buffer-modified-tick))
367 elint-buffer-forms))
369 (defun elint-get-top-forms ()
370 "Collect all the top forms in the current buffer."
371 (save-excursion
372 (let (tops)
373 (goto-char (point-min))
374 (while (elint-find-next-top-form)
375 (let ((elint-current-pos (point)))
376 ;; non-list check could be here too. errors may be out of seq.
377 ;; quoted check cannot be elsewhere, since quotes skipped.
378 (if (= (preceding-char) ?\')
379 ;; Eg cust-print.el uses ' as a comment syntax.
380 (elint-warning "Skipping quoted form `%c%.20s...'" ?\'
381 (read (current-buffer)))
382 (condition-case nil
383 (setq tops (cons
384 (elint-make-top-form (read (current-buffer))
385 elint-current-pos)
386 tops))
387 (end-of-file
388 (goto-char elint-current-pos)
389 (error "Missing `)' in top form: %s"
390 (buffer-substring elint-current-pos
391 (line-end-position))))))))
392 (nreverse tops))))
394 (defun elint-find-next-top-form ()
395 "Find the next top form from point.
396 Return nil if there are no more forms, t otherwise."
397 (parse-partial-sexp (point) (point-max) nil t)
398 (not (eobp)))
400 (defvar elint-env) ; from elint-init-env
402 (defun elint-init-form (form)
403 "Process FORM, adding to ELINT-ENV if recognized."
404 (cond
405 ;; Eg nnmaildir seems to use [] as a form of comment syntax.
406 ((not (listp form))
407 (elint-warning "Skipping non-list form `%s'" form))
408 ;; Add defined variable
409 ((memq (car form) '(defvar defconst defcustom))
410 (setq elint-env (elint-env-add-var elint-env (cadr form))))
411 ;; Add function
412 ((memq (car form) '(defun defsubst))
413 (setq elint-env (elint-env-add-func elint-env (cadr form) (nth 2 form))))
414 ;; FIXME needs a handler to say second arg is not a variable when we come
415 ;; to scan the form.
416 ((eq (car form) 'define-derived-mode)
417 (setq elint-env (elint-env-add-func elint-env (cadr form) ())
418 elint-env (elint-env-add-var elint-env (cadr form))
419 elint-env (elint-env-add-var elint-env
420 (intern (format "%s-map" (cadr form))))))
421 ((eq (car form) 'define-minor-mode)
422 (setq elint-env (elint-env-add-func elint-env (cadr form) '(&optional arg))
423 ;; FIXME mode map?
424 elint-env (elint-env-add-var elint-env (cadr form))))
425 ((and (eq (car form) 'easy-menu-define)
426 (cadr form))
427 (setq elint-env (elint-env-add-func elint-env (cadr form) '(event))
428 elint-env (elint-env-add-var elint-env (cadr form))))
429 ;; FIXME it would be nice to check the autoloads are correct.
430 ((eq (car form) 'autoload)
431 (setq elint-env (elint-env-add-func elint-env (cadr (cadr form)) 'unknown)))
432 ((eq (car form) 'declare-function)
433 (setq elint-env (elint-env-add-func
434 elint-env (cadr form)
435 (if (or (< (length form) 4)
436 (eq (nth 3 form) t)
437 (unless (stringp (nth 2 form))
438 (elint-error "Malformed declaration for `%s'"
439 (cadr form))
441 'unknown
442 (nth 3 form)))))
443 ((and (eq (car form) 'defalias) (listp (nth 2 form)))
444 ;; If the alias points to something already in the environment,
445 ;; add the alias to the environment with the same arguments.
446 ;; FIXME symbol-function, eg backquote.el?
447 (let ((def (elint-env-find-func elint-env (cadr (nth 2 form)))))
448 (setq elint-env (elint-env-add-func elint-env (cadr (cadr form))
449 (if def (cadr def) 'unknown)))))
450 ;; Add macro, both as a macro and as a function
451 ((eq (car form) 'defmacro)
452 (setq elint-env (elint-env-add-macro elint-env (cadr form)
453 (cons 'lambda (cddr form)))
454 elint-env (elint-env-add-func elint-env (cadr form) (nth 2 form))))
455 ((and (eq (car form) 'put)
456 (= 4 (length form))
457 (eq (car-safe (cadr form)) 'quote)
458 (equal (nth 2 form) '(quote error-conditions)))
459 (set (make-local-variable 'elint-extra-errors)
460 (cons (cadr (cadr form)) elint-extra-errors)))
461 ((eq (car form) 'provide)
462 (add-to-list 'elint-features (eval (cadr form))))
463 ;; Import variable definitions
464 ((memq (car form) '(require cc-require cc-require-when-compile))
465 (let ((name (eval (cadr form)))
466 (file (eval (nth 2 form)))
467 (elint-doing-cl (bound-and-true-p elint-doing-cl)))
468 (unless (memq name elint-features)
469 (add-to-list 'elint-features name)
470 ;; cl loads cl-macs in an opaque manner.
471 ;; Since cl-macs requires cl, we can just process cl-macs.
472 ;; FIXME: AFAIK, `cl' now behaves properly and does not need any
473 ;; special treatment any more. Can someone who understands this
474 ;; code confirm? --Stef
475 (and (eq name 'cl) (not elint-doing-cl)
476 ;; We need cl if elint-form is to be able to expand cl macros.
477 (require 'cl)
478 (setq name 'cl-macs
479 file nil
480 elint-doing-cl t)) ; blech
481 (setq elint-env (elint-add-required-env elint-env name file))))))
482 elint-env)
484 (defun elint-init-env (forms)
485 "Initialize the environment from FORMS."
486 (let ((elint-env (elint-make-env))
487 form)
488 (while forms
489 (setq form (elint-top-form-form (car forms))
490 forms (cdr forms))
491 ;; FIXME eval-when-compile should be treated differently (macros).
492 ;; Could bind something that makes elint-init-form only check
493 ;; defmacros.
494 (if (memq (car-safe form)
495 '(eval-and-compile eval-when-compile progn prog1 prog2
496 with-no-warnings))
497 (mapc 'elint-init-form (cdr form))
498 (elint-init-form form)))
499 elint-env))
501 (defun elint-add-required-env (env name file)
502 "Augment ENV with the variables defined by feature NAME in FILE."
503 (condition-case err
504 (let* ((libname (if (stringp file)
505 file
506 (symbol-name name)))
508 ;; First try to find .el files, then the raw name
509 (lib1 (locate-library (concat libname ".el") t))
510 (lib (or lib1 (locate-library libname t))))
511 ;; Clear the messages :-/
512 ;; (Messes up the "Initializing elint..." message.)
513 ;;; (message nil)
514 (if lib
515 (with-current-buffer (find-file-noselect lib)
516 ;; FIXME this doesn't use a temp buffer, because it
517 ;; stores the result in buffer-local variables so that
518 ;; it can be reused.
519 (elint-update-env)
520 (setq env (elint-env-add-env env elint-buffer-env)))
521 ;;; (with-temp-buffer
522 ;;; (insert-file-contents lib)
523 ;;; (with-syntax-table emacs-lisp-mode-syntax-table
524 ;;; (elint-update-env))
525 ;;; (setq env (elint-env-add-env env elint-buffer-env))))
526 ;;(message "%s" (format "Elint processed (require '%s)" name))
527 (error "%s.el not found in load-path" libname)))
528 (error
529 (message "Can't get variables from require'd library %s: %s"
530 name (error-message-string err))))
531 env)
533 (defvar elint-top-form nil
534 "The currently linted top form, or nil.")
536 (defvar elint-top-form-logged nil
537 "The value t if the currently linted top form has been mentioned in the log buffer.")
539 (defun elint-top-form (form)
540 "Lint a top FORM."
541 (let ((elint-top-form form)
542 (elint-top-form-logged nil)
543 (elint-current-pos (elint-top-form-pos form)))
544 (elint-form (elint-top-form-form form) elint-buffer-env)))
547 ;;; General form linting functions
550 (defconst elint-special-forms
551 '((let . elint-check-let-form)
552 (let* . elint-check-let-form)
553 (setq . elint-check-setq-form)
554 (quote . elint-check-quote-form)
555 (function . elint-check-quote-form)
556 (cond . elint-check-cond-form)
557 (lambda . elint-check-defun-form)
558 (function . elint-check-function-form)
559 (setq-default . elint-check-setq-form)
560 (defalias . elint-check-defalias-form)
561 (defun . elint-check-defun-form)
562 (defsubst . elint-check-defun-form)
563 (defmacro . elint-check-defun-form)
564 (defvar . elint-check-defvar-form)
565 (defconst . elint-check-defvar-form)
566 (defcustom . elint-check-defcustom-form)
567 (macro . elint-check-macro-form)
568 (condition-case . elint-check-condition-case-form)
569 (if . elint-check-conditional-form)
570 (when . elint-check-conditional-form)
571 (unless . elint-check-conditional-form)
572 (and . elint-check-conditional-form)
573 (or . elint-check-conditional-form))
574 "Functions to call when some special form should be linted.")
576 (defun elint-form (form env &optional nohandler)
577 "Lint FORM in the environment ENV.
578 Optional argument NOHANDLER non-nil means ignore `elint-special-forms'.
579 Returns the environment created by the form."
580 (cond
581 ((consp form)
582 (let ((func (cdr (assq (car form) elint-special-forms))))
583 (if (and func (not nohandler))
584 ;; Special form
585 (funcall func form env)
587 (let* ((func (car form))
588 (args (elint-get-args func env))
589 (argsok t))
590 (cond
591 ((eq args 'undefined)
592 (setq argsok nil)
593 (or (memq 'undefined-functions elint-ignored-warnings)
594 (elint-error "Call to undefined function: %s" func)))
596 ((eq args 'unknown) nil)
598 (t (setq argsok (elint-match-args form args))))
600 ;; Is this a macro?
601 (if (elint-env-macrop env func)
602 ;; Macro defined in buffer, expand it
603 (if argsok
604 ;; FIXME error if macro uses macro, eg bytecomp.el.
605 (condition-case nil
606 (elint-form
607 (macroexpand form (elint-env-macro-env env)) env)
608 (error
609 (or (memq 'macro-expansion elint-ignored-warnings)
610 (elint-error "Elint failed to expand macro: %s" func))
611 env))
612 env)
614 (let ((fcode (if (symbolp func)
615 (if (fboundp func)
616 (indirect-function func))
617 func)))
618 (if (and (listp fcode) (eq (car fcode) 'macro))
619 ;; Macro defined outside buffer
620 (if argsok
621 (elint-form (macroexpand form) env)
622 env)
623 ;; Function, lint its parameters
624 (elint-forms (cdr form) env))))))))
625 ((symbolp form)
626 ;; :foo variables are quoted
627 (and (/= (aref (symbol-name form) 0) ?:)
628 (not (memq 'unbound-reference elint-ignored-warnings))
629 (elint-unbound-variable form env)
630 (elint-warning "Reference to unbound symbol: %s" form))
631 env)
633 (t env)))
635 (defun elint-forms (forms env)
636 "Lint the FORMS, accumulating an environment, starting with ENV."
637 ;; grumblegrumbletailrecursiongrumblegrumble
638 (if (listp forms)
639 (dolist (f forms env)
640 (setq env (elint-form f env)))
641 ;; Loop macro?
642 (elint-error "Elint failed to parse form: %s" forms)
643 env))
645 (defvar elint-bound-variable nil
646 "Name of a temporarily bound symbol.")
648 (defun elint-unbound-variable (var env)
649 "Return t if VAR is unbound in ENV."
650 ;; #1063 suggests adding (symbol-file var) here, but I don't think
651 ;; this is right, because it depends on what files you happen to have
652 ;; loaded at the time, which might not be the same when the code runs.
653 ;; It also suggests adding:
654 ;; (numberp (get var 'variable-documentation))
655 ;; (numberp (cdr-safe (get var 'variable-documentation)))
656 ;; but this is not needed now elint-scan-doc-file exists.
657 (not (or (memq var '(nil t))
658 (eq var elint-bound-variable)
659 (elint-env-find-var env var)
660 (memq var elint-builtin-variables)
661 (memq var elint-autoloaded-variables)
662 (memq var elint-standard-variables))))
665 ;;; Function argument checking
668 (defun elint-match-args (arglist argpattern)
669 "Match ARGLIST against ARGPATTERN."
670 (let ((state 'all)
671 (al (cdr arglist))
672 (ap argpattern)
673 (ok t))
674 (while
675 (cond
676 ((and (null al) (null ap)) nil)
677 ((eq (car ap) '&optional)
678 (setq state 'optional)
679 (setq ap (cdr ap))
681 ((eq (car ap) '&rest)
682 nil)
683 ((or (and (eq state 'all) (or (null al) (null ap)))
684 (and (eq state 'optional) (and al (null ap))))
685 (elint-error "Wrong number of args: %s, %s" arglist argpattern)
686 (setq ok nil)
687 nil)
688 ((and (eq state 'optional) (null al))
689 nil)
690 (t (setq al (cdr al)
691 ap (cdr ap))
692 t)))
693 ok))
695 (defvar elint-bound-function nil
696 "Name of a temporarily bound function symbol.")
698 (defun elint-get-args (func env)
699 "Find the args of FUNC in ENV.
700 Returns `unknown' if we couldn't find arguments."
701 (let ((f (elint-env-find-func env func)))
702 (if f
703 (cadr f)
704 (if (symbolp func)
705 (if (eq func elint-bound-function)
706 'unknown
707 (if (fboundp func)
708 (let ((fcode (indirect-function func)))
709 (if (subrp fcode)
710 ;; FIXME builtins with no args have args = nil.
711 (or (get func 'elint-args) 'unknown)
712 (elint-find-args-in-code fcode)))
713 'undefined))
714 (elint-find-args-in-code func)))))
716 (defun elint-find-args-in-code (code)
717 "Extract the arguments from CODE.
718 CODE can be a lambda expression, a macro, or byte-compiled code."
719 (let ((args (help-function-arglist code)))
720 (if (listp args) args 'unknown)))
723 ;;; Functions to check some special forms
726 (defun elint-check-cond-form (form env)
727 "Lint a cond FORM in ENV."
728 (dolist (f (cdr form))
729 (if (consp f)
730 (let ((test (car f)))
731 (cond ((equal test '(featurep (quote xemacs))))
732 ((equal test '(not (featurep (quote emacs)))))
733 ;; FIXME (and (boundp 'foo)
734 ((and (eq (car-safe test) 'fboundp)
735 (= 2 (length test))
736 (eq (car-safe (cadr test)) 'quote))
737 (let ((elint-bound-function (cadr (cadr test))))
738 (elint-forms f env)))
739 ((and (eq (car-safe test) 'boundp)
740 (= 2 (length test))
741 (eq (car-safe (cadr test)) 'quote))
742 (let ((elint-bound-variable (cadr (cadr test))))
743 (elint-forms f env)))
744 (t (elint-forms f env))))
745 (elint-error "cond clause should be a list: %s" f)))
746 env)
748 (defun elint-check-defun-form (form env)
749 "Lint a defun/defmacro/lambda FORM in ENV."
750 (setq form (if (eq (car form) 'lambda) (cdr form) (cddr form)))
751 (mapc (lambda (p)
752 (or (memq p '(&optional &rest))
753 (setq env (elint-env-add-var env p))))
754 (car form))
755 (elint-forms (cdr form) env))
757 (defun elint-check-defalias-form (form env)
758 "Lint a defalias FORM in ENV."
759 (let ((alias (cadr form))
760 (target (nth 2 form)))
761 (and (eq (car-safe alias) 'quote)
762 (eq (car-safe target) 'quote)
763 (eq (elint-get-args (cadr target) env) 'undefined)
764 (elint-warning "Alias `%s' has unknown target `%s'"
765 (cadr alias) (cadr target))))
766 (elint-form form env t))
768 (defun elint-check-let-form (form env)
769 "Lint the let/let* FORM in ENV."
770 (let ((varlist (cadr form)))
771 (if (not varlist)
772 (if (> (length form) 2)
773 ;; An empty varlist is not really an error. Eg some cl macros
774 ;; can expand to such a form.
775 (progn
776 (or (memq 'empty-let elint-ignored-warnings)
777 (elint-warning "Empty varlist in let: %s" form))
778 ;; Lint the body forms
779 (elint-forms (cddr form) env))
780 (elint-error "Malformed let: %s" form)
781 env)
782 ;; Check for (let (a (car b)) ...) type of error
783 (if (and (= (length varlist) 2)
784 (symbolp (car varlist))
785 (listp (car (cdr varlist)))
786 (fboundp (car (car (cdr varlist)))))
787 (elint-warning "Suspect varlist: %s" form))
788 ;; Add variables to environment, and check the init values
789 (let ((newenv env))
790 (mapc (lambda (s)
791 (cond
792 ((symbolp s)
793 (setq newenv (elint-env-add-var newenv s)))
794 ((and (consp s) (<= (length s) 2))
795 (elint-form (cadr s)
796 (if (eq (car form) 'let)
798 newenv))
799 (setq newenv
800 (elint-env-add-var newenv (car s))))
801 (t (elint-error
802 "Malformed `let' declaration: %s" s))))
803 varlist)
805 ;; Lint the body forms
806 (elint-forms (cddr form) newenv)))))
808 (defun elint-check-setq-form (form env)
809 "Lint the setq FORM in ENV."
810 (or (= (mod (length form) 2) 1)
811 ;; (setq foo) is valid and equivalent to (setq foo nil).
812 (elint-warning "Missing value in setq: %s" form))
813 (let ((newenv env)
814 sym val)
815 (setq form (cdr form))
816 (while form
817 (setq sym (car form)
818 val (car (cdr form))
819 form (cdr (cdr form)))
820 (if (symbolp sym)
821 (and (not (memq 'unbound-assignment elint-ignored-warnings))
822 (elint-unbound-variable sym newenv)
823 (elint-warning "Setting previously unbound symbol: %s" sym))
824 (elint-error "Setting non-symbol in setq: %s" sym))
825 (elint-form val newenv)
826 (if (symbolp sym)
827 (setq newenv (elint-env-add-var newenv sym))))
828 newenv))
830 (defun elint-check-defvar-form (form env)
831 "Lint the defvar/defconst FORM in ENV."
832 (if (or (= (length form) 2)
833 (= (length form) 3)
834 ;; Eg the defcalcmodevar macro can expand with a nil doc-string.
835 (and (= (length form) 4) (string-or-null-p (nth 3 form))))
836 (elint-env-add-global-var (elint-form (nth 2 form) env)
837 (car (cdr form)))
838 (elint-error "Malformed variable declaration: %s" form)
839 env))
841 (defun elint-check-defcustom-form (form env)
842 "Lint the defcustom FORM in ENV."
843 (if (and (> (length form) 3)
844 ;; even no. of keyword/value args ?
845 (zerop (logand (length form) 1)))
846 (elint-env-add-global-var (elint-form (nth 2 form) env)
847 (car (cdr form)))
848 (elint-error "Malformed variable declaration: %s" form)
849 env))
851 (defun elint-check-function-form (form env)
852 "Lint the function FORM in ENV."
853 (let ((func (car (cdr-safe form))))
854 (cond
855 ((symbolp func)
856 (or (elint-env-find-func env func)
857 ;; FIXME potentially bogus, since it uses the current
858 ;; environment rather than a clean one.
859 (fboundp func)
860 (elint-warning "Reference to undefined function: %s" form))
861 env)
862 ((and (consp func) (memq (car func) '(lambda macro)))
863 (elint-form func env))
864 ((stringp func) env)
865 (t (elint-error "Not a function object: %s" form)
866 env))))
868 (defun elint-check-quote-form (_form env)
869 "Lint the quote FORM in ENV."
870 env)
872 (defun elint-check-macro-form (form env)
873 "Check the macro FORM in ENV."
874 (elint-check-function-form (list (car form) (cdr form)) env))
876 (defun elint-check-condition-case-form (form env)
877 "Check the `condition-case' FORM in ENV."
878 (let ((resenv env))
879 (if (< (length form) 3)
880 (elint-error "Malformed condition-case: %s" form)
881 (or (symbolp (cadr form))
882 (elint-warning "First parameter should be a symbol: %s" form))
883 (setq resenv (elint-form (nth 2 form) env))
884 (let ((newenv (elint-env-add-var env (cadr form)))
885 errlist)
886 (dolist (err (nthcdr 3 form))
887 (setq errlist (car err))
888 (mapc (lambda (s)
889 (or (get s 'error-conditions)
890 (get s 'error-message)
891 (memq s elint-extra-errors)
892 (elint-warning
893 "Not an error symbol in error handler: %s" s)))
894 (cond
895 ((symbolp errlist) (list errlist))
896 ((listp errlist) errlist)
897 (t (elint-error "Bad error list in error handler: %s"
898 errlist)
899 nil)))
900 (elint-forms (cdr err) newenv))))
901 resenv))
903 ;; For the featurep parts, an alternative is to have
904 ;; elint-get-top-forms skip the irrelevant branches.
905 (defun elint-check-conditional-form (form env)
906 "Check the when/unless/and/or FORM in ENV.
907 Does basic handling of `featurep' tests."
908 (let ((func (car form))
909 (test (cadr form)))
910 ;; Misses things like (and t (featurep 'xemacs))
911 ;; Check byte-compile-maybe-guarded.
912 (cond ((and (memq func '(when and))
913 (eq (car-safe test) 'boundp)
914 (= 2 (length test))
915 (eq (car-safe (cadr test)) 'quote))
916 ;; Cf elint-check-let-form, which modifies the whole ENV.
917 (let ((elint-bound-variable (cadr (cadr test))))
918 (elint-form form env t)))
919 ((and (memq func '(when and))
920 (eq (car-safe test) 'fboundp)
921 (= 2 (length test))
922 (eq (car-safe (cadr test)) 'quote))
923 (let ((elint-bound-function (cadr (cadr test))))
924 (elint-form form env t)))
925 ;; Let's not worry about (if (not (boundp...
926 ((and (eq func 'if)
927 (eq (car-safe test) 'boundp)
928 (= 2 (length test))
929 (eq (car-safe (cadr test)) 'quote))
930 (let ((elint-bound-variable (cadr (cadr test))))
931 (elint-form (nth 2 form) env))
932 (dolist (f (nthcdr 3 form))
933 (elint-form f env)))
934 ((and (eq func 'if)
935 (eq (car-safe test) 'fboundp)
936 (= 2 (length test))
937 (eq (car-safe (cadr test)) 'quote))
938 (let ((elint-bound-function (cadr (cadr test))))
939 (elint-form (nth 2 form) env))
940 (dolist (f (nthcdr 3 form))
941 (elint-form f env)))
942 ((and (memq func '(when and)) ; skip all
943 (or (null test)
944 (member test '((featurep (quote xemacs))
945 (not (featurep (quote emacs)))))
946 (and (eq (car-safe test) 'and)
947 (equal (car-safe (cdr test))
948 '(featurep (quote xemacs)))))))
949 ((and (memq func '(unless or))
950 (equal test '(featurep (quote emacs)))))
951 ((and (eq func 'if)
952 (or (null test) ; eg custom-browse-insert-prefix
953 (member test '((featurep (quote xemacs))
954 (not (featurep (quote emacs)))))
955 (and (eq (car-safe test) 'and)
956 (equal (car-safe (cdr test))
957 '(featurep (quote xemacs))))))
958 (dolist (f (nthcdr 3 form))
959 (elint-form f env))) ; lint the else branch
960 ((and (eq func 'if)
961 (equal test '(featurep (quote emacs))))
962 (elint-form (nth 2 form) env)) ; lint the if branch
963 ;; Process conditional as normal, without handler.
965 (elint-form form env t))))
966 env)
969 ;;; Message functions
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))))
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))
992 (defun elint-warning (string &rest args)
993 "Report a linting warning.
994 See `elint-error'."
995 (elint-log "Warning" string args))
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")))
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))))
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"))))))
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)))
1041 (defun elint-set-mode-line (&optional on)
1042 "Set the mode-line-process of the Elint log buffer."
1043 (with-current-buffer (elint-get-log-buffer)
1044 (and (eq major-mode 'compilation-mode)
1045 (setq mode-line-process
1046 (list (if (or on (bound-and-true-p elint-running))
1047 (propertize ":run" 'face 'compilation-warning)
1048 (propertize ":finished" 'face 'compilation-info)))))))
1050 (defun elint-get-log-buffer ()
1051 "Return a log buffer for elint."
1052 (or (get-buffer elint-log-buffer)
1053 (with-current-buffer (get-buffer-create elint-log-buffer)
1054 (or (eq major-mode 'compilation-mode)
1055 (compilation-mode))
1056 (setq buffer-undo-list t)
1057 (current-buffer))))
1060 ;;; Initializing code
1063 (defun elint-put-function-args (func args)
1064 "Mark function FUNC as having argument list ARGS."
1065 (and (symbolp func)
1066 args
1067 (not (eq args 'unknown))
1068 (put func 'elint-args args)))
1070 ;;;###autoload
1071 (defun elint-initialize (&optional reinit)
1072 "Initialize elint.
1073 If elint is already initialized, this does nothing, unless
1074 optional prefix argument REINIT is non-nil."
1075 (interactive "P")
1076 (if (and elint-builtin-variables (not reinit))
1077 (message "Elint is already initialized")
1078 (message "Initializing elint...")
1079 (setq elint-builtin-variables (elint-scan-doc-file)
1080 elint-autoloaded-variables (elint-find-autoloaded-variables))
1081 (mapc (lambda (x) (elint-put-function-args (car x) (cdr x)))
1082 (elint-find-builtin-args))
1083 (if elint-unknown-builtin-args
1084 (mapc (lambda (x) (elint-put-function-args (car x) (cdr x)))
1085 elint-unknown-builtin-args))
1086 (when elint-scan-preloaded
1087 (dolist (lib preloaded-file-list)
1088 ;; Skip files that contain nothing of use to us.
1089 (unless (string-match elint-preloaded-skip-re lib)
1090 (setq elint-preloaded-env
1091 (elint-add-required-env elint-preloaded-env nil lib)))))
1092 (message "Initializing elint...done")))
1095 ;; This includes all the built-in and dumped things with documentation.
1096 (defun elint-scan-doc-file ()
1097 "Scan the DOC file for function and variables.
1098 Marks the function with their arguments, and returns a list of variables."
1099 ;; Cribbed from help-fns.el.
1100 (let ((docbuf " *DOC*")
1101 vars sym args)
1102 (save-excursion
1103 (if (get-buffer docbuf)
1104 (progn
1105 (set-buffer docbuf)
1106 (goto-char (point-min)))
1107 (set-buffer (get-buffer-create docbuf))
1108 (insert-file-contents-literally
1109 (expand-file-name internal-doc-file-name doc-directory)))
1110 (while (re-search-forward "\x1f\\([VF]\\)" nil t)
1111 (when (setq sym (intern-soft (buffer-substring (point)
1112 (line-end-position))))
1113 (if (string-equal (match-string 1) "V")
1114 ;; Excludes platform-specific stuff not relevant to the
1115 ;; running platform.
1116 (if (boundp sym) (setq vars (cons sym vars)))
1117 ;; Function.
1118 (when (fboundp sym)
1119 (when (re-search-forward "\\(^(fn.*)\\)?\x1f" nil t)
1120 (backward-char 1)
1121 ;; FIXME distinguish no args from not found.
1122 (and (setq args (match-string 1))
1123 (setq args
1124 (ignore-errors
1125 (read
1126 (replace-regexp-in-string "^(fn ?" "(" args))))
1127 (elint-put-function-args sym args))))))))
1128 vars))
1130 (defun elint-find-autoloaded-variables ()
1131 "Return a list of all autoloaded variables."
1132 (let (var vars)
1133 (with-temp-buffer
1134 (insert-file-contents (locate-library "loaddefs.el"))
1135 (while (re-search-forward "^(defvar \\([[:alnum:]_-]+\\)" nil t)
1136 (and (setq var (intern-soft (match-string 1)))
1137 (boundp var)
1138 (setq vars (cons var vars)))))
1139 vars))
1141 (defun elint-find-builtins ()
1142 "Return a list of all built-in functions."
1143 (let (subrs)
1144 (mapatoms (lambda (s) (and (subrp (symbol-function s))
1145 (push s subrs))))
1146 subrs))
1148 (defun elint-find-builtin-args (&optional list)
1149 "Return a list of the built-in functions and their arguments.
1150 If LIST is nil, call `elint-find-builtins' to get a list of all built-in
1151 functions, otherwise use LIST.
1153 Each function is represented by a cons cell:
1154 \(function-symbol . args)
1155 If no documentation could be found args will be `unknown'."
1156 (mapcar (lambda (f)
1157 (let ((doc (documentation f t)))
1158 (or (and doc
1159 (string-match "\n\n(fn\\(.*)\\)\\'" doc)
1160 (ignore-errors
1161 ;; "BODY...)" -> "&rest BODY)".
1162 (read (replace-regexp-in-string
1163 "\\([^ ]+\\)\\.\\.\\.)\\'" "&rest \\1)"
1164 (format "(%s %s" f (match-string 1 doc)) t))))
1165 (cons f 'unknown))))
1166 (or list (elint-find-builtins))))
1168 (provide 'elint)
1170 ;;; elint.el ends here