1 ;;; names.el --- Namespaces for emacs-lisp. Avoid name clobbering without hiding symbols.
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
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
9 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
10 ;; Keywords: extensions lisp
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
23 ;; This file is part of GNU Emacs.
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.
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.
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/>.
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 "")))
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
65 (while (and (symbolp f)
66 (null (setq val (get f prop)))
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'.
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"
79 (symbol-function name)))
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)))
87 (or (eq 'macro (car def))
88 (and (names--autoloadp def) (memq (nth 4 def) '(macro t))))))))
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))))
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
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"
117 ;; Simple default, which covers 99% of the cases.
121 ;;; ---------------------------------------------------------------
123 (defconst names-version "20141119" "Version of the names.el package.")
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'.")
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.")
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.")
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
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.")
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
156 (defvar names--current-run nil
157 "Either 1 or 2, depending on which runthrough we're in.")
159 (defvar names--var-list
160 '(names--name names--regexp names--bound
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.")
169 (defvar names--inside-make-autoload nil
170 "Used in `make-autoload' to indicate we're making autoloads.")
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'.")
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'.")
181 (defvar names--version nil
182 "The version number given by :version.
183 Used to define a constant and a command.")
185 (defconst names--keyword-list
189 (setq names--group-parent x)
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.
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.")
205 (setq names--version x)
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.
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.")
220 (setq names--package x)
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.
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.")
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.")
241 "Indicates variables assigned in let-bind are NOT candidates for namespacing.")
245 "Cause a message to be called on each special form.")
249 "Accept namespaced names from outside current namespace definition.")
253 "Indicate symbols quoted with `quote' should be considered variable names.")
255 (:dont-assume-function-quote
257 "Indicate symbols quoted with `function' should NOT be considered function names.")
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)
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
275 - DOCUMENTATION is a string explaining the keyword's
278 (defmacro names--prepend (sbl)
279 "Return namespace+SBL."
280 (declare (debug (symbolp)))
281 `(intern (format "%s%s" names--name ,sbl)))
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)
290 (mapcar (lambda (x) (when (funcall (or ,pred 'identity) (or (car-safe x) x))
291 (or (car-safe x) x)))
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))
302 (setq n (assoc kar names--keyword-list))
304 (dotimes (it (1+ n) out)
305 (push (pop ,body) out))
308 (defvar names--has-reloaded nil
309 "Whether `names--reload-if-upgraded' has already been called in this run.")
312 ;;; ---------------------------------------------------------------
313 ;;; The Main Macro and Main Function.
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].
322 In summary, this macro has two main effects:
324 1. Any definitions inside BODY will have NAME prepended to the
327 (define-namespace foo-
328 (defvar bar 1 \"docs\")
333 (defvar foo-bar 1 \"docs\")
336 2. Any function calls and variable names get NAME prepended to
337 them if such a variable or function exists. Ex:
339 (define-namespace foo:
340 (defun message (x y) nil)
341 (message \"%s\" my-var)
346 (defun foo:message (x y) nil)
347 (foo:message \"%s\" my-var)
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.
353 ===============================
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
363 ===============================
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'.
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)))
384 (defun names--define-namespace-implementation (name body)
385 "Namespace BODY using NAME.
386 See `define-namespace' for more information."
388 (let* ((names--name name)
390 (concat "\\`" (regexp-quote (symbol-name name))))
391 (names--current-run 0)
392 ;; Use the :protection keyword to change this.
393 (names--protection "\\`::")
395 (names--remove-namespace-from-list
396 (names--filter-if-bound byte-compile-bound-variables)
397 (names--filter-if-bound byte-compile-variables)))
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)))
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)
409 (while (setq key-and-args (names--next-keyword body))
410 (names--handle-keyword key-and-args)
411 (push key-and-args names--keywords))
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))
418 ;; Then we go back and actually namespace the entire form, which
419 ;; we'll later return so that it can be evaluated.
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)
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))
454 ;; Exiting the `unwind-protect'.
455 (mapc (lambda (x) (set x nil)) names--var-list)))
457 (defun names--reload-if-upgraded ()
458 "Verify if there's a more recent version of Names in the `load-path'.
462 (let ((lp (expand-file-name (find-library-name "names")))
465 (not (string= lp names--load-file))
466 (file-readable-p lp))
468 (insert-file-contents-literally lp)
469 (goto-char (point-min))
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)))))))
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'.
483 See macro `namespace' for more information."
488 (let ((kar (car form))
491 ;; If symbol is protected, clean it.
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)))
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.
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))
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)))
513 ;; General functions/macros/special-forms
514 (t (names--handle-args kar (cdr 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)
528 ;;; ---------------------------------------------------------------
529 ;;; Some auxiliary functions
530 (defun names-view-manual ()
531 "Call `browse-url' to view the manual of the Names package."
533 (browse-url "http://github.com/Bruce-Connor/names"))
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."
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'"
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))
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)
560 (list 'defconst (names--prepend '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))
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))
573 (ignore-errors (macroexpand
574 expansion byte-compile-macro-environment))))
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)))
585 byte-compile-macro-environment))))))))
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."
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))))))
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))))))
608 (ad-set-arg 0 short-symbol)
611 (defun names--extract-autoloads (body)
612 "Return a list of the forms in BODY preceded by :autoload."
614 (when (setq acons (memq :autoload body))
617 (names--extract-autoloads (cdr (cdr acons)))))))
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.
628 (if (null (eq (car-safe form) 'define-namespace))
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
637 (mapcar (lambda (x) (names--make-autoload-compat x file))
639 (ad-set-arg 2 'expansion)
643 (defun names--make-autoload-compat (form file)
644 (if (eq (car-safe form) 'defalias)
646 (make-autoload form file)))
648 (defvar names--ignored-forms '(declare)
649 "The name of functions/macros/special-forms which we return without reading.")
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)
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))))))
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)))
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)))
677 (defun names--error-if-using-vars ()
678 "Remind the developer that variables are not customizable."
682 (error "[names] Global value of variable %s should be nil! %s"
683 x "Set it using keywords instead")))
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))))
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))
696 (defun names--remove-protection (symbol)
697 "Remove the leading :: from SYMBOL if possible, otherwise return nil."
698 (names--remove-regexp symbol names--protection))
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)))))
706 (defun names--quote-p (sbl)
707 "Is SBL a function which quotes its argument?"
708 (memq sbl '(quote function)))
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)))))
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)))))
723 (defun names--keyword (keyword)
724 "Was KEYWORD one of the keywords passed to the `namespace' macro?"
725 (assoc keyword names--keywords))
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
731 (and (null (memq sbl names--local-vars))
732 (or (memq sbl names--bound)
733 (and (names--keyword :global)
734 (boundp (names--prepend sbl))))))
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."
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.
745 (names--args-of-function-or-macro function args nil)
746 ;; Macros where nothing is evaluated we can just return.
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))))
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.
760 (and (symbolp indirect)
763 indirect 'edebug-form-spec 'macro))))
764 ;; (edebug-trace "indirection: %s" edebug-form-spec)
765 (setq spec indirect))
768 (defvar names--is-inside-macro nil
769 "Auxiliary var used in `names--macro-args-using-edebug'.")
771 (defvar names--gensym-counter 0
772 "Counter used to uniquify symbols generated `names--gensym'.")
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
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."
787 ((max-lisp-eval-depth 3000)
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))
806 (goto-char (point-min))
808 (edebug-read-top-level-form))
811 "Couldn't namespace this macro using its (debug ...) declaration: %s"
815 (when (equal (car-safe (cdr-safe er))
816 "Lisp nesting exceeds `max-lisp-eval-depth'")
818 "Lisp nesting exceeded `max-lisp-eval-depth' at the following form: %s"
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.")
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.")
832 (defun names--edebug-message (&rest _)
833 (if (or (names--keyword :verbose) names--verbose)
834 (apply names--message-backup _)
835 (when _ (apply 'format _))))
837 (defun names--edebug-make-enter-wrapper (forms)
838 (setq edebug-def-name
841 (names--gensym "edebug-anon")))
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))))
852 (defun names--edebug-form (cursor)
853 "Parse form given by CURSOR using edebug, and namespace it if necessary."
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
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.
867 ;; We DO want to convert the arguments that edebug identifies
868 ;; as forms (level-1). And we do that ourselves, don't pass
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)
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
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)))))
900 ;; Anything else is self-evaluating.
902 (edebug-move-cursor cursor))))
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))
910 (append form `(:group ',(names--package-name)))))
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.
920 Regardless of whether a function was called, the keyword is added
921 to the variable `names--keywords'.
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))))
927 (apply func (cdr body))
931 ;;; ---------------------------------------------------------------
932 ;;; Interpreting the actual forms found in BODY of the main macro.
934 ;; This is where the heavy work is done.
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.
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)
946 (spaced-name (names--prepend name))
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
952 (when (setq decl (ignore-errors (cond
953 ((eq (car-safe (nth 3 form)) 'declare)
955 ((and (stringp (nth 3 form))
956 (eq (car-safe (nth 4 form)) 'declare))
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.
964 (names--convert-lambda
965 (cons spaced-name (cddr form))))))
966 (defalias 'names--convert-defmacro* 'names--convert-defmacro)
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))))
973 (setq name (names--remove-namespace
974 (ignore-errors (eval (cadr form)))))
976 (add-to-list 'names--bound name))
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))))
984 (setq name (names--remove-namespace
985 (ignore-errors (eval (cadr form)))))
987 (add-to-list 'names--fbound name))
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)))
995 (add-to-list 'names--bound name))
999 (names--prepend name))
1000 (mapcar 'names-convert-form (cdr (cdr form))))))
1002 (defalias 'names--convert-defconst 'names--convert-defvar
1003 "Special treatment for `defconst' FORM.")
1005 (defun names--convert-defcustom (form)
1006 "Special treatment for `defcustom' FORM."
1007 (names--maybe-append-group
1008 (names--convert-defvar form)))
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)
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))))))))
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)))
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)))
1046 (names--maybe-append-group
1047 ;; And here we namespace it.
1050 (names--prepend name)
1052 (names-convert-form (nth 3 form))
1053 (names-convert-form (nth 4 form))))
1054 (mapcar #'names-convert-form (cddr form)))))
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)))
1070 (names--maybe-append-group
1071 ;; And here we namespace it.
1074 (names--prepend name)
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)))))
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.
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
1093 (let ((name (names--remove-namespace (cadr form)))
1094 (copy (cl-copy-list form)))
1095 ;; Register the mode 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.
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)
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').
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))
1125 (if (and (eq this-name 'function)
1127 (list this-name (names-convert-form kadr))
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)))
1135 (names--handle-symbol-as-function kadr)))
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))
1142 (or (names--remove-protection kadr)
1143 (if (names--boundp kadr)
1144 (names--prepend kadr)
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)))
1155 (defalias 'names--convert-function 'names--convert-quote)
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))))
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))
1167 (forms (cdr (cdr form))))
1171 (when (stringp (car forms))
1174 (setq forms (cdr forms))))
1175 (when (eq 'interactive (car-safe (car forms)))
1177 (list (list (car (car forms))
1178 (names-convert-form (cadr (car forms)))))
1179 (setq forms (cdr forms))))
1181 ;; (message "%S" forms)
1182 (mapcar 'names-convert-form forms)))))
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))
1190 (forms (cdr (cdr form))))
1193 (names--convert-lambda (cdr form)))))
1195 (defun names--vars-from-arglist (args)
1196 "Get a list of local variables from a generalized arglist ARGS."
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)))
1208 (defun names--convert-defun (form)
1209 "Special treatment for `defun' FORM."
1210 (let* ((name (cadr form)))
1211 (add-to-list 'names--fbound name)
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)
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)
1225 (when add (add-to-list 'names--local-vars name))
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)
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)))
1240 ;; Each var defined in a regular `let' only becomes protected after
1241 ;; all others have been defined.
1243 (setq names--local-vars
1245 (mapcar (lambda (x) (or (car-safe x) x)) vars)
1246 names--local-vars)))
1248 (list (car form) vars)
1249 (mapcar 'names-convert-form (cddr form)))))
1251 (defun names--convert-let* (form)
1252 "Special treatment for `let' FORM."
1253 (names--convert-let form t))
1255 (defun names--convert-cond (form)
1256 "Special treatment for `cond' FORM."
1260 (lambda (x) (mapcar #'names-convert-form x))
1263 (defun names--convert-condition-case (form)
1264 "Special treatment for `condition-case' FORM."
1269 (names-convert-form (cadr (cdr form))))
1273 (mapcar 'names-convert-form (cdr x))))
1274 (cddr (cdr form)))))
1277 ;;; names.el ends here