]> code.delx.au - gnu-emacs-elpa/blob - packages/names/names.el
Merge commit 'a11ba779f588af28f93fd4b7a716849695d5d9f3'
[gnu-emacs-elpa] / packages / names / names.el
1 ;;; names.el --- Namespaces for emacs-lisp. Avoid name clobbering without hiding symbols.
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Artur Malabarba <bruce.connor.am@gmail.com>
6 ;; Maintainer: Artur Malabarba <bruce.connor.am@gmail.com>
7 ;; URL: http://github.com/Bruce-Connor/names
8 ;; Version: 20141119
9 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
10 ;; Keywords: extensions lisp
11 ;; Prefix: names
12 ;; Separator: -
13
14 ;;; Commentary:
15 ;;
16 ;; The description is way too large to sanely write here, below is a
17 ;; summary. For a complete description, please visit the package's
18 ;; frontpage with `M-x names-view-manual', or see the Readme file on
19 ;; https://raw.githubusercontent.com/Bruce-Connor/names/master/Readme.org
20
21 ;;; License:
22 ;;
23 ;; This file is part of GNU Emacs.
24 ;;
25 ;; GNU Emacs is free software: you can redistribute it and/or modify
26 ;; it under the terms of the GNU General Public License as published by
27 ;; the Free Software Foundation, either version 3 of the License, or
28 ;; (at your option) any later version.
29 ;;
30 ;; GNU Emacs is distributed in the hope that it will be useful,
31 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
32 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 ;; GNU General Public License for more details.
34 ;;
35 ;; You should have received a copy of the GNU General Public License
36 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
37
38 ;;; News:
39 ;;; Code:
40 \f
41
42 (require 'cl-lib)
43 ;;; This is a patch because edebug binds under `C-x'.
44 ;; If `C-x' is not a prefix.
45 (unless (consp (key-binding "\C-x"))
46 ;; Disable the `C-xC-a' binds.
47 (setq edebug-inhibit-emacs-lisp-mode-bindings t)
48 ;; And the `C-xX' binds.
49 (when (or (null (boundp 'global-edebug-prefix))
50 (eq 24 (elt global-edebug-prefix 0)))
51 (setq global-edebug-prefix "")))
52 (require 'edebug)
53 (require 'bytecomp)
54 (require 'advice)
55
56 ;;; Support
57 (declare-function names--autoload-do-load "names" 2)
58 (if (fboundp 'function-get)
59 (defalias 'names--function-get #'function-get)
60 (defun names--function-get (f prop &rest _)
61 "Return the value of property PROP of function F.
62 If F is an autoloaded macro, try to autoload it in the hope that
63 it will set PROP."
64 (let ((val nil))
65 (while (and (symbolp f)
66 (null (setq val (get f prop)))
67 (fboundp f))
68 (let ((fundef (symbol-function f)))
69 (if (and (names--autoloadp fundef)
70 (not (equal fundef (names--autoload-do-load fundef f))))
71 nil ;Re-try `get' on the same `f'.
72 (setq f fundef))))
73 val))
74 (defun names--autoload-do-load (def name)
75 "Load autoloaded definition DEF from function named NAME."
76 (unless (load (cadr def) 'noerror)
77 (error "Macro `%s' is autoloaded, but its file (%s) couldn't be loaded"
78 name (cadr def)))
79 (symbol-function name)))
80
81 (if (fboundp 'macrop)
82 (defalias 'names--compat-macrop #'macrop)
83 (defun names--compat-macrop (object)
84 "Non-nil if and only if OBJECT is a macro."
85 (let ((def (indirect-function object t)))
86 (when (consp def)
87 (or (eq 'macro (car def))
88 (and (names--autoloadp def) (memq (nth 4 def) '(macro t))))))))
89
90 (if (fboundp 'autoloadp)
91 (defalias 'names--autoloadp #'autoloadp)
92 (defsubst names--autoloadp (object)
93 "Non-nil if OBJECT is an autoload."
94 (eq 'autoload (car-safe object))))
95
96 (unless (get-edebug-spec 'cl-defun)
97 (def-edebug-spec cl-defun defun*))
98 (unless (get-edebug-spec 'cl-defmacro)
99 (def-edebug-spec cl-defmacro defmacro*))
100 (unless (get-edebug-spec 'setq-local)
101 (def-edebug-spec setq-local setq))
102 (unless (get-edebug-spec 'loop)
103 (def-edebug-spec loop
104 (&rest &or
105 ;; These are usually followed by a symbol, but it can
106 ;; actually be any destructuring-bind pattern, which
107 ;; would erroneously match `form'.
108 [[&or "for" "as" "with" "and"] sexp]
109 ;; These are followed by expressions which could
110 ;; erroneously match `symbolp'.
111 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
112 "above" "below" "by" "in" "on" "=" "across"
113 "repeat" "while" "until" "always" "never"
114 "thereis" "collect" "append" "nconc" "sum"
115 "count" "maximize" "minimize" "if" "unless"
116 "return"] form]
117 ;; Simple default, which covers 99% of the cases.
118 symbolp form)))
119
120 \f
121 ;;; ---------------------------------------------------------------
122 ;;; Variables
123 (defconst names-version "20141119" "Version of the names.el package.")
124
125 (defvar names--name nil
126 "Name of the current namespace inside the `define-namespace' macro.")
127 (defvar names--regexp nil "Regexp matching `names--name'.")
128
129 (defvar names--load-file (and load-file-name (expand-file-name load-file-name))
130 "The file where the current version of Names was loaded.
131 This is used by `names--check-for-update' to check if a new
132 version has been installed.")
133
134 (defvar names--bound nil
135 "List of variables defined in this namespace.")
136 (defvar names--fbound nil
137 "List of functions defined in this namespace.")
138 (defvar names--macro nil
139 "List of macros defined in this namespace.")
140
141 (defvar names--keywords nil
142 "Keywords that were passed to the current namespace.
143 See `names--keyword-list' for a list and description of possible
144 keywords.")
145
146 (defvar names--local-vars nil
147 "Non-global vars that are let/lambda bound at the moment.
148 These won't be namespaced, as local takes priority over namespace.")
149
150 (defvar names--protection nil
151 "Leading chars used to identify protected symbols.
152 Don't customise this.
153 Instead use the :protection keyword when defining the
154 namespace.")
155
156 (defvar names--current-run nil
157 "Either 1 or 2, depending on which runthrough we're in.")
158
159 (defvar names--var-list
160 '(names--name names--regexp names--bound
161 names--version
162 names--package names--group-parent
163 names--macro names--current-run
164 names--fbound names--keywords
165 names--local-vars names--protection)
166 "List of variables the user shouldn't touch.")
167
168 ;;;###autoload
169 (defvar names--inside-make-autoload nil
170 "Used in `make-autoload' to indicate we're making autoloads.")
171
172 (defvar names--package nil
173 "Package, name to be used by the :group and :version keywords.
174 Is derived from `load-file-name', unless the :package keyword is
175 passed to `define-namespace'.")
176
177 (defvar names--group-parent nil
178 "The name of the parent to be given to `defgroup'.
179 Is only non-nil if the :group keyword is passed to `define-namespace'.")
180
181 (defvar names--version nil
182 "The version number given by :version.
183 Used to define a constant and a command.")
184
185 (defconst names--keyword-list
186 '((:group
187 1 (lambda (x)
188 (if (symbolp x)
189 (setq names--group-parent x)
190 (names--warn
191 "Argument given to :group is not a symbol: %s" x)))
192 "Indicate `define-namespace' should make a `defgroup' for you.
193 The name of the group is the package name (see :package keyword).
194 This keyword should be given one argument, the name of the PARENT
195 group as an unquoted symbol.
196
197 If this keyword is provided, besides including a defgroup, Names
198 will also include a :group keyword in every `defcustom' (and
199 similar forms) that don't already contain one.")
200
201 (:version
202 1
203 (lambda (x)
204 (if (stringp x)
205 (setq names--version x)
206 (names--warn
207 "Argument given to :version is not a string: %s" x)))
208 "Indicate `define-namespace' should define the version number.
209 This keyword should be given one argument, a string describing
210 the package's version number.
211
212 With this, Names will generate a `defconst' and an interactive
213 `defun', each named `PACKAGE-NAME-version'. The function messages
214 and returns the version number. See the :package keyword.")
215
216 (:package
217 1
218 (lambda (x)
219 (if (symbolp x)
220 (setq names--package x)
221 (names--warn
222 "Argument given to :package is not a symbol: %s" x)))
223 "Set the name of this package to the given symbol.
224 This keyword should be given one argument, a symbol corresponding
225 to the name of this package.
226
227 If this keyword isn't used, the package name is taken as the the
228 file's basename, but only if its actually needed. This name is
229 needed by the :version and :group keywords.")
230
231 (:protection
232 1
233 (lambda (x)
234 (let ((val (symbol-name x)))
235 (setq names--protection
236 (format "\\`%s" (regexp-quote val)))))
237 "Change the value of the `names--protection' variable.")
238
239 (:no-let-vars
240 0 nil
241 "Indicates variables assigned in let-bind are NOT candidates for namespacing.")
242
243 (:verbose
244 0 nil
245 "Cause a message to be called on each special form.")
246
247 (:global
248 0 nil
249 "Accept namespaced names from outside current namespace definition.")
250
251 (:assume-var-quote
252 0 nil
253 "Indicate symbols quoted with `quote' should be considered variable names.")
254
255 (:dont-assume-function-quote
256 0 nil
257 "Indicate symbols quoted with `function' should NOT be considered function names.")
258
259 (:clean-output
260 0 nil
261 "Indicate only forms actually inside the namespace should be present in the output.
262 This is for internal use. It is used by `names-eval-defun' to
263 prevent `define-namespace' from adding things like `defgroup' or
264 `defconst's to the output."))
265 "List of keywords used by `define-namespace'.
266 Each element is a list containing
267 (KEYWORD N DEFINITION DOCUMENTATION)
268 where:
269
270 - KEYWORD is the keyword's name, a symbol satifying `keywordp'.
271 - N is the number of arguments it takes, an integer.
272 - DEFINITION is a function (symbol or lambda) that takes N
273 arguments and does whatever you need for implementing the
274 keyword.
275 - DOCUMENTATION is a string explaining the keyword's
276 behaviour.")
277
278 (defmacro names--prepend (sbl)
279 "Return namespace+SBL."
280 (declare (debug (symbolp)))
281 `(intern (format "%s%s" names--name ,sbl)))
282
283
284 (defmacro names--filter-if-bound (var &optional pred)
285 "If VAR is bound and is a list, take the car of its elements which satify PRED."
286 (declare (debug (symbolp &optional function-form)))
287 `(when (boundp ',var)
288 (remove
289 nil
290 (mapcar (lambda (x) (when (funcall (or ,pred 'identity) (or (car-safe x) x))
291 (or (car-safe x) x)))
292 ,var))))
293
294 (defmacro names--next-keyword (body)
295 "If car of BODY is a known keyword, `pop' it (and its arguments) from body.
296 Returns a list (KEYWORD . ARGUMENTLIST)."
297 (declare (debug sexp))
298 `(let ((kar (car-safe ,body))
299 out n)
300 (and kar
301 (keywordp kar)
302 (setq n (assoc kar names--keyword-list))
303 (setq n (cadr n))
304 (dotimes (it (1+ n) out)
305 (push (pop ,body) out))
306 (nreverse out))))
307
308 (defvar names--has-reloaded nil
309 "Whether `names--reload-if-upgraded' has already been called in this run.")
310
311 \f
312 ;;; ---------------------------------------------------------------
313 ;;; The Main Macro and Main Function.
314 ;;;###autoload
315 (defmacro define-namespace (name &rest body)
316 "Inside the namespace NAME, execute BODY.
317 NAME can be any symbol (not quoted), but it's highly recommended
318 to use some form of separator (such as :, /, or -). For a
319 complete description of this macro, please visit the frontpage
320 with \\[names-view-manual].
321
322 In summary, this macro has two main effects:
323
324 1. Any definitions inside BODY will have NAME prepended to the
325 symbol given. Ex:
326
327 (define-namespace foo-
328 (defvar bar 1 \"docs\")
329 )
330
331 expands to
332
333 (defvar foo-bar 1 \"docs\")
334
335
336 2. Any function calls and variable names get NAME prepended to
337 them if such a variable or function exists. Ex:
338
339 (define-namespace foo:
340 (defun message (x y) nil)
341 (message \"%s\" my-var)
342 )
343
344 expands to
345
346 (defun foo:message (x y) nil)
347 (foo:message \"%s\" my-var)
348
349 Note how `message' is expanded to `foo:message' in the second
350 form, because that function exists. Meanwhile, `bar' is left
351 untouched because `foo:bar' is not a known variable name.
352
353 ===============================
354
355 AUTOLOAD
356
357 In order for `define-namespace' to work with \";;;###autoload\"
358 comments must replace all instances of \";;;###autoload\" inside
359 your `define-namespace' with `:autoload'.
360 Afterwards, add an \";;;###autoload\" comment just above your
361 `define-namespace'.
362
363 ===============================
364
365 KEYWORDS
366
367 Immediately after NAME you may add keywords which customize the
368 behaviour of `define-namespace'. For a list of possible keywords
369 and a description of their effects, see the variable
370 `names--keyword-list'.
371
372 \(fn NAME [KEYWORD ...] BODY)"
373 (declare (indent (lambda (&rest x) 0))
374 (debug (&define name [&rest keywordp &optional [&or symbolp (symbolp . symbolp)]] body)))
375 (let ((names--has-reloaded names--has-reloaded))
376 ;; This was to avoid an infinite recursion, but the bug turned out
377 ;; to be somewhere else. Still, I see no reason to erase this.
378 (unless names--has-reloaded
379 (setq names--has-reloaded t)
380 (names--reload-if-upgraded))
381 (names--error-if-using-vars)
382 (names--define-namespace-implementation name body)))
383
384 (defun names--define-namespace-implementation (name body)
385 "Namespace BODY using NAME.
386 See `define-namespace' for more information."
387 (unwind-protect
388 (let* ((names--name name)
389 (names--regexp
390 (concat "\\`" (regexp-quote (symbol-name name))))
391 (names--current-run 0)
392 ;; Use the :protection keyword to change this.
393 (names--protection "\\`::")
394 (names--bound
395 (names--remove-namespace-from-list
396 (names--filter-if-bound byte-compile-bound-variables)
397 (names--filter-if-bound byte-compile-variables)))
398 (names--fbound
399 (names--remove-namespace-from-list
400 (names--filter-if-bound byte-compile-macro-environment 'names--compat-macrop)
401 (names--filter-if-bound byte-compile-function-environment 'names--compat-macrop)))
402 (names--macro
403 (names--remove-namespace-from-list
404 (names--filter-if-bound byte-compile-macro-environment (lambda (x) (not (names--compat-macrop x))))
405 (names--filter-if-bound byte-compile-function-environment (lambda (x) (not (names--compat-macrop x))))))
406 names--keywords names--local-vars key-and-args
407 names--version names--package names--group-parent)
408 ;; Read keywords
409 (while (setq key-and-args (names--next-keyword body))
410 (names--handle-keyword key-and-args)
411 (push key-and-args names--keywords))
412
413 ;; First have to populate the bound and fbound lists. So we read
414 ;; the entire form (without evaluating it).
415 (mapc 'names-convert-form body)
416 (setq names--current-run (1+ names--current-run))
417
418 ;; Then we go back and actually namespace the entire form, which
419 ;; we'll later return so that it can be evaluated.
420 (setq body
421 (cons
422 'progn
423 (append
424 (when (and names--group-parent
425 (null (names--keyword :clean-output)))
426 (list (names--generate-defgroup)))
427 (when (and names--version
428 (null (names--keyword :clean-output)))
429 ;; `names--generate-version' returns a list.
430 (names--generate-version))
431 (mapcar 'names-convert-form
432 ;; Unless we're in `make-autoload', then just return autoloads.
433 (if names--inside-make-autoload
434 (names--extract-autoloads body)
435 body)))))
436
437 ;; On emacs-version < 24.4, the byte-compiler cannot expand a
438 ;; macro if it is being called in the same top-level form as
439 ;; it was defined. That's a problem for us, since the entire
440 ;; namespace is a single top-level form (we return a `progn').
441 ;; The solution is for us to add the macros to
442 ;; `byte-compile-macro-environment' ourselves.
443 (if (and (boundp 'byte-compile-current-buffer)
444 byte-compile-current-buffer
445 (null names--inside-make-autoload)
446 (version< emacs-version "24.4"))
447 (let ((byte-compile-macro-environment
448 (when (boundp 'byte-compile-macro-environment)
449 byte-compile-macro-environment)))
450 (mapc #'names--add-macro-to-environment (cdr body))
451 (macroexpand-all body byte-compile-macro-environment))
452 body))
453
454 ;; Exiting the `unwind-protect'.
455 (mapc (lambda (x) (set x nil)) names--var-list)))
456
457 (defun names--reload-if-upgraded ()
458 "Verify if there's a more recent version of Names in the `load-path'.
459 If so, evaluate it."
460 (ignore-errors
461 (require 'find-func)
462 (let ((lp (expand-file-name (find-library-name "names")))
463 new-version)
464 (when (and lp
465 (not (string= lp names--load-file))
466 (file-readable-p lp))
467 (with-temp-buffer
468 (insert-file-contents-literally lp)
469 (goto-char (point-min))
470 (setq new-version
471 (save-excursion
472 (when (search-forward-regexp
473 "(defconst\\s-+names-version\\s-+\"\\([^\"]+\\)\"" nil t)
474 (match-string-no-properties 1))))
475 (when (and new-version (version< names-version new-version))
476 (eval-buffer nil lp)))))))
477
478 (defun names-convert-form (form)
479 "Do namespace conversion on FORM.
480 FORM is any legal elisp form.
481 Namespace name is defined by the global variable `names--name'.
482
483 See macro `namespace' for more information."
484 (cond
485 ((null form) form)
486 ;; Function calls
487 ((consp form)
488 (let ((kar (car form))
489 func)
490 (cond
491 ;; If symbol is protected, clean it.
492 ((and (symbolp kar)
493 (setq func (names--remove-protection kar)))
494 (names--message "Protected: %s" kar)
495 ;; And decide what to do with it.
496 (names--handle-args func (cdr form)))
497
498 ;; If kar is a list, either 1) it's a lambda form, 2) it's a
499 ;; macro we don't know about yet, 3) we have a bug.
500 ((consp kar)
501 (when (and (null (functionp kar))
502 (> names--current-run 1))
503 (names--warn "Ran into the following strange form.
504 Either it's an undefined macro, a macro with a bad debug declaration, or we have a bug.\n%s" form))
505 (mapcar 'names-convert-form form))
506
507 ;; Namespaced Functions/Macros
508 ((names--fboundp kar)
509 (names--message "Namespaced: %s" kar)
510 (names--args-of-function-or-macro
511 (names--prepend kar) (cdr form) (names--macrop kar)))
512
513 ;; General functions/macros/special-forms
514 (t (names--handle-args kar (cdr form))))))
515 ;; Variables
516 ((symbolp form)
517 (names--message "Symbol handling: %s" form)
518 ;; If symbol is protected, clean it and don't namespace it.
519 (or (names--remove-protection form)
520 ;; Otherwise, namespace if possible.
521 (if (names--boundp form)
522 (names--prepend form)
523 form)))
524 ;; Values
525 (t form)))
526
527 \f
528 ;;; ---------------------------------------------------------------
529 ;;; Some auxiliary functions
530 (defun names-view-manual ()
531 "Call `browse-url' to view the manual of the Names package."
532 (interactive)
533 (browse-url "http://github.com/Bruce-Connor/names"))
534
535 (defun names--package-name ()
536 "Return the package name as a symbol.
537 Decide package name based on several factors. In order:
538 1. The :package keyword,
539 2. The namespace NAME, removing the final char."
540 (or names--package
541 (let ((package (symbol-name names--name)))
542 (prog1 (setq names--package
543 (intern (substring package 0 -1)))
544 (names--warn "No :package given. Guessing `%s'"
545 names--package)))))
546
547 (defun names--generate-defgroup ()
548 "Return a `defgroup' form for the current namespace."
549 (list 'defgroup (names--package-name) nil
550 (format "Customization group for %s." (names--package-name))
551 :prefix (symbol-name names--name)
552 :group `',names--group-parent))
553
554 (defun names--generate-version ()
555 "Return a `defun' and a `defconst' forms declaring the package version.
556 Also adds `version' to `names--fbound' and `names--bound'."
557 (add-to-list 'names--fbound 'version)
558 (add-to-list 'names--bound 'version)
559 (list
560 (list 'defconst (names--prepend 'version)
561 names--version
562 (format "Version of the %s package." (names--package-name)))
563 (list 'defun (names--prepend 'version) nil
564 (format "Version of the %s package." (names--package-name))
565 '(interactive)
566 names--version)))
567
568 (defun names--add-macro-to-environment (form)
569 "If FORM declares a macro, add it to `byte-compile-macro-environment'."
570 (let ((expansion form))
571 (while (names--compat-macrop (car-safe expansion))
572 (setq expansion
573 (ignore-errors (macroexpand
574 expansion byte-compile-macro-environment))))
575 (and expansion
576 (car-safe expansion)
577 (or (and (memq (car-safe expansion) '(progn prog1 prog2))
578 (mapc #'names--add-macro-to-environment (cdr expansion)))
579 (and (eq 'defalias (car-safe expansion))
580 (let ((def (ignore-errors (eval (nth 2 expansion)))))
581 (and (names--compat-macrop def)
582 (push (cons (ignore-errors
583 (eval (nth 1 expansion)))
584 (cdr-safe def))
585 byte-compile-macro-environment))))))))
586
587 ;;;###autoload
588 (defadvice find-function-search-for-symbol
589 (around names-around-find-function-search-for-symbol-advice
590 (symbol type library) activate)
591 "Make sure `find-function-search-for-symbol' understands namespaces."
592 ad-do-it
593 (ignore-errors
594 (unless (cdr ad-return-value)
595 (with-current-buffer (car ad-return-value)
596 (search-forward-regexp "^(define-namespace\\_>")
597 (skip-chars-forward "\r\n[:blank:]")
598 (let* ((names--regexp
599 (concat "\\`" (regexp-quote
600 (symbol-name (read (current-buffer))))))
601 (short-symbol
602 ;; We manually implement `names--remove-namespace'
603 ;; because it might not be loaded.
604 (let ((name (symbol-name symbol)))
605 (when (string-match names--regexp name)
606 (intern (replace-match "" nil nil name))))))
607 (when short-symbol
608 (ad-set-arg 0 short-symbol)
609 ad-do-it))))))
610
611 (defun names--extract-autoloads (body)
612 "Return a list of the forms in BODY preceded by :autoload."
613 (let (acons)
614 (when (setq acons (memq :autoload body))
615 (cons
616 (cadr acons)
617 (names--extract-autoloads (cdr (cdr acons)))))))
618
619 ;;;###autoload
620 (defadvice make-autoload (around names-before-make-autoload-advice
621 (form file &optional expansion) activate)
622 "Make sure `make-autoload' understands `define-namespace'.
623 Use the `names--inside-make-autoload' variable to indicate to
624 `define-namespace' that we're generating autoloads."
625 ;; We used to have a letbind here, but this was causing a void
626 ;; variable bug on Emacs 24.3.
627 (require 'names)
628 (if (null (eq (car-safe form) 'define-namespace))
629 ad-do-it
630 (setq names--inside-make-autoload t)
631 (setq form (macroexpand form))
632 (setq names--inside-make-autoload nil)
633 ;; Up to 24.2 `make-autoload' couldn't handle `progn's.
634 (if (version< emacs-version "24.3")
635 (setq ad-return-value
636 (cons 'progn
637 (mapcar (lambda (x) (names--make-autoload-compat x file))
638 (cdr form))))
639 (ad-set-arg 2 'expansion)
640 (ad-set-arg 0 form)
641 ad-do-it)))
642
643 (defun names--make-autoload-compat (form file)
644 (if (eq (car-safe form) 'defalias)
645 form
646 (make-autoload form file)))
647
648 (defvar names--ignored-forms '(declare)
649 "The name of functions/macros/special-forms which we return without reading.")
650
651 (defun names--handle-args (func args)
652 "Generic handling for the form (FUNC . ARGS), without namespacing FUNC."
653 (if (memq func names--ignored-forms)
654 (cons func args)
655 ;; TODO: Speed this up. Just change it to an alist or a hash-table.
656 (let ((handler (intern-soft (format "names--convert-%s" func))))
657 ;; Some function-like forms get special handling.
658 ;; That's anything with a names--convert-%s function defined.
659 (if (fboundp handler)
660 (progn (names--message "Special handling: %s" handler)
661 (funcall handler (cons func args)))
662 ;; If it isn't special, it's either a function or a macro.
663 (names--args-of-function-or-macro func args (names--compat-macrop func))))))
664
665 (defun names--message (f &rest rest)
666 "If :verbose is on, pass F and REST to `message'."
667 (when (names--keyword :verbose)
668 (apply 'message (concat "[names] " f) rest)))
669
670 (defun names--warn (f &rest rest)
671 "Pass F and REST to `message', unless byte-compiling or non-interactive."
672 (unless (and (null (names--keyword :verbose))
673 (and (boundp 'byte-compile-function-environment)
674 byte-compile-function-environment))
675 (apply 'message (concat "[names] " f) rest)))
676
677 (defun names--error-if-using-vars ()
678 "Remind the developer that variables are not customizable."
679 (mapcar
680 (lambda (x)
681 (when (eval x)
682 (error "[names] Global value of variable %s should be nil! %s"
683 x "Set it using keywords instead")))
684 names--var-list))
685
686 (defun names--remove-namespace-from-list (&rest lists)
687 "Return a concatenated un-namespaced version of LISTS.
688 Symbols in LISTS that aren't namespaced are removed, symbols that
689 are namespaced become un-namespaced."
690 (delq nil (mapcar 'names--remove-namespace (apply 'append lists))))
691
692 (defun names--remove-namespace (symbol)
693 "Return SYMBOL with namespace removed, or nil if it wasn't namespaced."
694 (names--remove-regexp symbol names--regexp))
695
696 (defun names--remove-protection (symbol)
697 "Remove the leading :: from SYMBOL if possible, otherwise return nil."
698 (names--remove-regexp symbol names--protection))
699
700 (defun names--remove-regexp (s r)
701 "Return S with regexp R removed, or nil if S didn't match."
702 (let ((name (symbol-name s)))
703 (when (string-match r name)
704 (intern (replace-match "" nil nil name)))))
705
706 (defun names--quote-p (sbl)
707 "Is SBL a function which quotes its argument?"
708 (memq sbl '(quote function)))
709
710 (defun names--fboundp (sbl)
711 "Is namespace+SBL a fboundp symbol?"
712 (or (memq sbl names--fbound)
713 (memq sbl names--macro)
714 (and (names--keyword :global)
715 (fboundp (names--prepend sbl)))))
716
717 (defun names--macrop (sbl)
718 "Is namespace+SBL a fboundp symbol?"
719 (or (memq sbl names--macro)
720 (and (names--keyword :global)
721 (names--compat-macrop (names--prepend sbl)))))
722
723 (defun names--keyword (keyword)
724 "Was KEYWORD one of the keywords passed to the `namespace' macro?"
725 (assoc keyword names--keywords))
726
727 (defun names--boundp (sbl)
728 "Is namespace+SBL a boundp symbol?
729 If SBL has a let binding, that takes precendence so this also
730 returns nil."
731 (and (null (memq sbl names--local-vars))
732 (or (memq sbl names--bound)
733 (and (names--keyword :global)
734 (boundp (names--prepend sbl))))))
735
736 ;;; This is calling edebug even on `when' and `unless'
737 (defun names--args-of-function-or-macro (function args macro)
738 "Namespace FUNCTION's arguments ARGS, with special treatment if MACRO is non-nil."
739 (if macro
740 (let ((it (names--get-edebug-spec function))
741 (names--verbose (eq function 'push)))
742 (names--message "Edebug-spec of `%s' is %s" function it)
743 ;; Macros where we evaluate all arguments are like functions.
744 (if (equal it t)
745 (names--args-of-function-or-macro function args nil)
746 ;; Macros where nothing is evaluated we can just return.
747 (if (equal it 0)
748 (cons function args)
749 ;; Other macros are complicated. Ask edebug for help.
750 (names--macro-args-using-edebug (cons function args)))))
751 ;; We just convert the arguments of functions.
752 (cons function (mapcar 'names-convert-form args))))
753
754 (defun names--get-edebug-spec (name)
755 "Get 'edebug-form-spec property of symbol NAME."
756 ;; Get the spec of symbol resolving all indirection.
757 (let ((spec nil)
758 (indirect name))
759 (while (progn
760 (and (symbolp indirect)
761 (setq indirect
762 (names--function-get
763 indirect 'edebug-form-spec 'macro))))
764 ;; (edebug-trace "indirection: %s" edebug-form-spec)
765 (setq spec indirect))
766 spec))
767
768 (defvar names--is-inside-macro nil
769 "Auxiliary var used in `names--macro-args-using-edebug'.")
770
771 (defvar names--gensym-counter 0
772 "Counter used to uniquify symbols generated `names--gensym'.")
773
774 (defun names--macro-args-using-edebug (form)
775 "Namespace the arguments of macro FORM by hacking into edebug.
776 This takes advantage of the fact that macros (should) declare a
777 `debug' specification which tells us which arguments are actually
778 Elisp forms.
779
780 Ideally, we would read this specification ourselves and see how
781 it matches (cdr FORM), but that would take a lot of work and
782 we'd be reimplementing something that edebug already does
783 phenomenally. So we hack into edebug instead."
784 (require 'edebug)
785 (require 'cl-lib)
786 (cl-letf
787 ((max-lisp-eval-depth 3000)
788 (edebug-all-forms t)
789 (edebug-all-defs t)
790 (names--is-inside-macro form)
791 ;; Prevent excessive messaging.
792 ;; TODO: Don't do this if `message' is advised.
793 ((symbol-function 'message) #'names--edebug-message)
794 ;; Older edebugs have poor `get-edebug-spec'.
795 ((symbol-function 'get-edebug-spec) #'names--get-edebug-spec)
796 ;; Give symbols our own name.
797 ((symbol-function 'cl-gensym) #'names--gensym)
798 ;; Stop at one level deep.
799 ((symbol-function 'edebug-form) #'names--edebug-form)
800 ;; Don't actually wrap anything.
801 ((symbol-function 'edebug-make-enter-wrapper)
802 #'names--edebug-make-enter-wrapper))
803 (condition-case er
804 (with-temp-buffer
805 (pp form 'insert)
806 (goto-char (point-min))
807 ;; Do the magic!
808 (edebug-read-top-level-form))
809 (invalid-read-syntax
810 (names--warn
811 "Couldn't namespace this macro using its (debug ...) declaration: %s"
812 form)
813 form)
814 (error
815 (when (equal (car-safe (cdr-safe er))
816 "Lisp nesting exceeds `max-lisp-eval-depth'")
817 (names--warn
818 "Lisp nesting exceeded `max-lisp-eval-depth' at the following form: %s"
819 form))
820 form))))
821
822 (defvar names--message-backup
823 (if (ad-is-advised 'message)
824 (ad-get-orig-definition 'message)
825 (symbol-function 'message))
826 "Where names stores `message's definition while overriding it.")
827
828 (defvar names--verbose nil
829 "If non-nil, verbose message are printed regardless of the :verbose keyword.
830 Use this to easily turn on verbosity during tests.")
831
832 (defun names--edebug-message (&rest _)
833 (if (or (names--keyword :verbose) names--verbose)
834 (apply names--message-backup _)
835 (when _ (apply 'format _))))
836
837 (defun names--edebug-make-enter-wrapper (forms)
838 (setq edebug-def-name
839 (or edebug-def-name
840 edebug-old-def-name
841 (names--gensym "edebug-anon")))
842 (cons 'progn forms))
843
844 (defun names--gensym (prefix)
845 "Generate a new uninterned symbol.
846 The name is made by appending a number to PREFIX and preppending \"names\", default \"G\"."
847 (let ((num (prog1 names--gensym-counter
848 (setq names--gensym-counter
849 (1+ names--gensym-counter)))))
850 (make-symbol (format "names-%s%d" (if (stringp prefix) prefix "G") num))))
851
852 (defun names--edebug-form (cursor)
853 "Parse form given by CURSOR using edebug, and namespace it if necessary."
854 (require 'edebug)
855 ;; Return the instrumented form for the following form.
856 ;; Add the point offsets to the edebug-offset-list for the form.
857 (let* ((form (edebug-top-element-required cursor "Expected form"))
858 (offset (edebug-top-offset cursor))
859 ;; We don't want to convert the entire form that was passed
860 ;; to `names--macro-args-using-edebug', since the head of
861 ;; that was already converted and it would lead to an
862 ;; infinite loop.
863 ;; So we check for (equal names--is-inside-macro form)
864 ;; Simply incrementing a depth counter didn't work, for a
865 ;; reason I can no longer remember.
866
867 ;; We DO want to convert the arguments that edebug identifies
868 ;; as forms (level-1). And we do that ourselves, don't pass
869 ;; them to edebug.
870 (func (if (or (eq names--is-inside-macro t)
871 (equal names--is-inside-macro form))
872 'identity 'names-convert-form))
873 (names--is-inside-macro
874 (if (eq func 'names-convert-form)
875 t names--is-inside-macro)))
876 (names--message " [Edebug] Ran into this: %S" form)
877 (names--message " Cursor: %S" cursor)
878 (prog1
879 (cond
880 ((consp form) ;; The first offset for a list form is for the list form itself.
881 (if (eq func 'names-convert-form)
882 (names-convert-form form)
883 (let* ((head (car form))
884 (spec (and (symbolp head) (get-edebug-spec head)))
885 (new-cursor (edebug-new-cursor form offset)))
886 ;; Find out if this is a defining form from first symbol.
887 ;; An indirect spec would not work here, yet.
888 (if (and (consp spec) (eq '&define (car spec)))
889 (edebug-defining-form
890 new-cursor
891 (car offset) ;; before the form
892 (edebug-after-offset cursor)
893 (cons (symbol-name head) (cdr spec)))
894 ;; Wrap a regular form.
895 (edebug-list-form new-cursor)))))
896
897 ((symbolp form)
898 (funcall func form))
899
900 ;; Anything else is self-evaluating.
901 (t form))
902 (edebug-move-cursor cursor))))
903
904 (defun names--maybe-append-group (form)
905 "Append (:group `names--package') to FORM.
906 Only if the :group keyword was passed to `define-namespace' and
907 if the form doesn't already have a :group."
908 (if (or (null names--group-parent) (memq :group form))
909 form
910 (append form `(:group ',(names--package-name)))))
911
912 \f
913 ;;; ---------------------------------------------------------------
914 ;;; Interpreting keywords passed to the main macro.
915 (defun names--handle-keyword (body)
916 "Call the function that handles the keyword at the car of BODY.
917 Such function must be listed in `names--keyword-list'. If it is
918 nil, this function just returns.
919
920 Regardless of whether a function was called, the keyword is added
921 to the variable `names--keywords'.
922
923 The car of BODY is the keyword itself and the other elements are
924 the keyword arguments, if any."
925 (let ((func (nth 2 (assoc (car body) names--keyword-list))))
926 (if (functionp func)
927 (apply func (cdr body))
928 nil)))
929
930 \f
931 ;;; ---------------------------------------------------------------
932 ;;; Interpreting the actual forms found in BODY of the main macro.
933 ;;
934 ;; This is where the heavy work is done.
935 ;;
936 ;; If you'd like to implement support for some special form, simply
937 ;; define a function called `names--convert-FORM-NAME' along the
938 ;; lines of the functions defined below. It will be automatically used
939 ;; whenever that form is found.
940
941 ;;; Defun, defmacro, and defsubst macros are pretty predictable.
942 (defun names--convert-defmacro (form)
943 "Special treatment for `defmacro' FORM."
944 (let* ((names--name-already-prefixed t)
945 (name (cadr form))
946 (spaced-name (names--prepend name))
947 decl)
948 (add-to-list 'names--macro name)
949 (add-to-list 'names--fbound name)
950 ;; Set the macros debug spec if possible. It will be relevant on
951 ;; the next run.
952 (when (setq decl (ignore-errors (cond
953 ((eq (car-safe (nth 3 form)) 'declare)
954 (nth 3 form))
955 ((and (stringp (nth 3 form))
956 (eq (car-safe (nth 4 form)) 'declare))
957 (nth 4 form))
958 (t nil))))
959 (setq decl (car (cdr-safe (assoc 'debug (cdr decl)))))
960 (when decl (put spaced-name 'edebug-form-spec decl)))
961 ;; Then convert the macro as a defalias.
962 (cons
963 (car form)
964 (names--convert-lambda
965 (cons spaced-name (cddr form))))))
966 (defalias 'names--convert-defmacro* 'names--convert-defmacro)
967
968 (defun names--convert-defvaralias (form)
969 "Special treatment for `defvaralias' FORM."
970 (let ((form (cons (car form)
971 (mapcar #'names-convert-form (cdr form))))
972 (name))
973 (setq name (names--remove-namespace
974 (ignore-errors (eval (cadr form)))))
975 (when name
976 (add-to-list 'names--bound name))
977 form))
978
979 (defun names--convert-defalias (form)
980 "Special treatment for `defalias' FORM."
981 (let ((form (cons (car form)
982 (mapcar #'names-convert-form (cdr form))))
983 (name))
984 (setq name (names--remove-namespace
985 (ignore-errors (eval (cadr form)))))
986 (when name
987 (add-to-list 'names--fbound name))
988 form))
989
990 (defun names--convert-defvar (form &optional dont-add)
991 "Special treatment for `defvar' FORM.
992 If DONT-ADD is nil, the FORM's `cadr' is added to `names--bound'."
993 (let ((name (cadr form)))
994 (unless dont-add
995 (add-to-list 'names--bound name))
996 (append
997 (list
998 (car form)
999 (names--prepend name))
1000 (mapcar 'names-convert-form (cdr (cdr form))))))
1001
1002 (defalias 'names--convert-defconst 'names--convert-defvar
1003 "Special treatment for `defconst' FORM.")
1004
1005 (defun names--convert-defcustom (form)
1006 "Special treatment for `defcustom' FORM."
1007 (names--maybe-append-group
1008 (names--convert-defvar form)))
1009
1010 (defun names--convert-custom-declare-variable (form)
1011 "Special treatment for `custom-declare-variable' FORM."
1012 (let ((name (eval (cadr form))) ;;ignore-errors
1013 (val (car (cddr form))))
1014 (add-to-list 'names--bound name)
1015 (append
1016 (list
1017 (car form)
1018 (list 'quote (names--prepend name)) ;cadr
1019 ;; The DEFAULT argument is explicitly evaluated by
1020 ;; `custom-declare-variable', so it should be safe to namespace
1021 ;; even when quoted. Plus, we need to do this because
1022 ;; defcustom quotes this part.
1023 (if (names--quote-p (car-safe val))
1024 (list (car val) (names-convert-form (cadr val)))
1025 (names-convert-form val))
1026 (names-convert-form (car (cdr (cdr (cdr form))))))
1027 (mapcar 'names-convert-form (cdr (cdr (cdr (cdr form))))))))
1028
1029 (defun names--convert-defface (form)
1030 "Special treatment for `defface' FORM.
1031 Identical to defvar, just doesn't add the symbol to the boundp
1032 list. And maybe use a :group."
1033 (names--maybe-append-group
1034 (names--convert-defvar form :dont-add)))
1035
1036 (defun names--convert-define-derived-mode (form)
1037 "Special treatment for `define-derived-mode' FORM."
1038 (let ((name (cadr form)))
1039 (add-to-list 'names--fbound name)
1040 (add-to-list 'names--bound name)
1041 (add-to-list 'names--bound
1042 (intern (format "%s-map" name)))
1043 (add-to-list 'names--bound
1044 (intern (format "%s-hook" name)))
1045 (append
1046 (names--maybe-append-group
1047 ;; And here we namespace it.
1048 (list
1049 (car form)
1050 (names--prepend name)
1051 (nth 2 form)
1052 (names-convert-form (nth 3 form))
1053 (names-convert-form (nth 4 form))))
1054 (mapcar #'names-convert-form (cddr form)))))
1055
1056 (defun names--convert-define-minor-mode (form)
1057 "Special treatment for `define-minor-mode' FORM."
1058 (let ((name (cadr form))
1059 (keymap (nth 5 form)))
1060 ;; Register the mode name
1061 (add-to-list 'names--fbound name)
1062 (add-to-list 'names--bound name)
1063 (add-to-list 'names--bound (intern (format "%s-hook" name)))
1064 ;; Register the keymap
1065 (if (or (null keymap) (null (symbolp keymap)))
1066 (add-to-list 'names--bound (intern (format "%s-map" name)))
1067 (when (setq keymap (names--remove-namespace keymap))
1068 (add-to-list 'names--bound keymap)))
1069 (append
1070 (names--maybe-append-group
1071 ;; And here we namespace it.
1072 (list
1073 (car form)
1074 (names--prepend name)
1075 (nth 2 form)
1076 (names-convert-form (nth 3 form))
1077 (names-convert-form (nth 4 form))
1078 (names-convert-form (nth 5 form))
1079 (names-convert-form (nth 6 form))))
1080 (mapcar #'names-convert-form (cddr form)))))
1081
1082 (defun names--convert-define-globalized-minor-mode (form)
1083 "Special treatment for `define-globalized-minor-mode' FORM.
1084 The NAME of the global mode will NOT be namespaced, despite being
1085 a definition. It is kept verbatim.
1086 This is because people tend to name their global modes as
1087 `global-foo-mode', and namespacing would make this impossible.
1088
1089 The MODE and TURN-ON arguments are converted as function names.
1090 Everything else is converted as regular forms (which usually
1091 means no conversion will happen since it's usually keywords and
1092 quoted symbols)."
1093 (let ((name (names--remove-namespace (cadr form)))
1094 (copy (cl-copy-list form)))
1095 ;; Register the mode name
1096 (when name
1097 (add-to-list 'names--fbound name)
1098 (add-to-list 'names--bound name)
1099 (add-to-list 'names--bound (intern (format "%s-hook" name))))
1100 (names--maybe-append-group
1101 ;; And here we namespace it.
1102 (append
1103 (list
1104 (pop copy)
1105 (pop copy)
1106 (names--handle-symbol-as-function (pop copy))
1107 (names--handle-symbol-as-function (pop copy)))
1108 (mapcar #'names-convert-form copy)))))
1109 (defalias #'names--convert-define-global-minor-mode
1110 #'names--convert-define-globalized-minor-mode)
1111 (defalias #'names--convert-easy-mmode-define-global-mode
1112 #'names--convert-define-globalized-minor-mode)
1113
1114 (defun names--convert-quote (form)
1115 "Special treatment for `quote' FORM.
1116 When FORM is (quote argument), argument too arbitrary to be
1117 logically namespaced and is never parsed for namespacing
1118 (but see :assume-var-quote in `names--keyword-list').
1119
1120 When FORM is (function form), a symbol is namespaced as a
1121 function name, a list is namespaced as a lambda form."
1122 (let ((kadr (cadr form))
1123 (this-name (car form))
1124 func)
1125 (if (and (eq this-name 'function)
1126 (listp kadr))
1127 (list this-name (names-convert-form kadr))
1128 (if (symbolp kadr)
1129 (cond
1130 ;; A symbol inside a function quote should be a function,
1131 ;; unless the user disabled that.
1132 ((and (eq this-name 'function)
1133 (null (names--keyword :dont-assume-function-quote)))
1134 (list 'function
1135 (names--handle-symbol-as-function kadr)))
1136
1137 ;; A symbol inside a regular quote should be a function, if
1138 ;; the user asked for that.
1139 ((and (eq this-name 'quote)
1140 (names--keyword :assume-var-quote))
1141 (list 'quote
1142 (or (names--remove-protection kadr)
1143 (if (names--boundp kadr)
1144 (names--prepend kadr)
1145 kadr))))
1146
1147 (t form))
1148 form))))
1149
1150 (defun names--handle-symbol-as-function (s)
1151 "Namespace symbol S as a function name."
1152 (or (names--remove-protection s)
1153 (if (names--fboundp s) (names--prepend s) s)))
1154
1155 (defalias 'names--convert-function 'names--convert-quote)
1156
1157 (defun names--convert-macro (form)
1158 "Special treatment for `macro' form.
1159 Return (macro . (names-convert-form (cdr FORM)))."
1160 (cons 'macro (names-convert-form (cdr form))))
1161
1162 (defun names--convert-lambda (form)
1163 "Special treatment for `lambda' FORM."
1164 (let ((names--local-vars
1165 (append (names--vars-from-arglist (cadr form))
1166 names--local-vars))
1167 (forms (cdr (cdr form))))
1168 (append
1169 (list (car form)
1170 (cadr form))
1171 (when (stringp (car forms))
1172 (prog1
1173 (list (car forms))
1174 (setq forms (cdr forms))))
1175 (when (eq 'interactive (car-safe (car forms)))
1176 (prog1
1177 (list (list (car (car forms))
1178 (names-convert-form (cadr (car forms)))))
1179 (setq forms (cdr forms))))
1180 (progn
1181 ;; (message "%S" forms)
1182 (mapcar 'names-convert-form forms)))))
1183
1184 (defun names--convert-clojure (form)
1185 "Special treatment for `clojure' FORM."
1186 (names--warn "Found a `closure'! You should use `lambda's instead")
1187 (let ((names--local-vars
1188 (append (names--vars-from-arglist (cadr form))
1189 names--local-vars))
1190 (forms (cdr (cdr form))))
1191 (cons
1192 (car form)
1193 (names--convert-lambda (cdr form)))))
1194
1195 (defun names--vars-from-arglist (args)
1196 "Get a list of local variables from a generalized arglist ARGS."
1197 (remove
1198 nil
1199 (mapcar
1200 (lambda (x)
1201 (let ((symb (or (cdr-safe (car-safe x)) (car-safe x) x)))
1202 (when (and (symbolp symb)
1203 (null (string-match "^&" (symbol-name symb)))
1204 (null (eq symb t)))
1205 symb)))
1206 args)))
1207
1208 (defun names--convert-defun (form)
1209 "Special treatment for `defun' FORM."
1210 (let* ((name (cadr form)))
1211 (add-to-list 'names--fbound name)
1212 (cons (car form)
1213 (names--convert-lambda
1214 (cons (names--prepend name) (cddr form))))))
1215 (defalias 'names--convert-defun* 'names--convert-defun)
1216 (defalias 'names--convert-defsubst 'names--convert-defun)
1217 (defalias 'names--convert-defsubst* 'names--convert-defun)
1218
1219 (defun names--let-var-convert-then-add (sym add)
1220 "Try to convert SYM unless :no-let-vars is in use.
1221 If ADD is non-nil, add resulting symbol to `names--local-vars'."
1222 (let ((name (if (null (names--keyword :no-let-vars))
1223 (names-convert-form sym)
1224 sym)))
1225 (when add (add-to-list 'names--local-vars name))
1226 name))
1227
1228 (defun names--convert-let (form &optional star)
1229 "Special treatment for `let' FORM.
1230 If STAR is non-nil, parse as a `let*'."
1231 (let* ((names--local-vars names--local-vars)
1232 (vars
1233 (mapcar
1234 (lambda (x)
1235 (if (car-safe x)
1236 (list (names--let-var-convert-then-add (car x) star)
1237 (names-convert-form (cadr x)))
1238 (names--let-var-convert-then-add x star)))
1239 (cadr form))))
1240 ;; Each var defined in a regular `let' only becomes protected after
1241 ;; all others have been defined.
1242 (unless star
1243 (setq names--local-vars
1244 (append
1245 (mapcar (lambda (x) (or (car-safe x) x)) vars)
1246 names--local-vars)))
1247 (append
1248 (list (car form) vars)
1249 (mapcar 'names-convert-form (cddr form)))))
1250
1251 (defun names--convert-let* (form)
1252 "Special treatment for `let' FORM."
1253 (names--convert-let form t))
1254
1255 (defun names--convert-cond (form)
1256 "Special treatment for `cond' FORM."
1257 (cons
1258 (car form)
1259 (mapcar
1260 (lambda (x) (mapcar #'names-convert-form x))
1261 (cdr form))))
1262
1263 (defun names--convert-condition-case (form)
1264 "Special treatment for `condition-case' FORM."
1265 (append
1266 (list
1267 (car form)
1268 (cadr form)
1269 (names-convert-form (cadr (cdr form))))
1270 (mapcar
1271 (lambda (x)
1272 (cons (car x)
1273 (mapcar 'names-convert-form (cdr x))))
1274 (cddr (cdr form)))))
1275
1276 (provide 'names)
1277 ;;; names.el ends here