1 ;;; names.el --- Namespaces for emacs-lisp. Avoid name clobbering without hiding symbols. -*- lexical-binding:t -*-
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
5 ;; Author: Artur Malabarba <emacs@endlessparentheses.com>
6 ;; URL: https://github.com/Malabarba/names
8 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
9 ;; Keywords: extensions lisp
13 ;; The description is way too large to sanely write here, below is a
14 ;; summary. For a complete description, please visit the package's
15 ;; frontpage with `M-x names-view-manual', or see the Readme file on
16 ;; https://raw.githubusercontent.com/Malabarba/names/master/Readme.org
20 ;; This file is part of GNU Emacs.
22 ;; GNU Emacs is free software: you can redistribute it and/or modify
23 ;; it under the terms of the GNU General Public License as published by
24 ;; the Free Software Foundation, either version 3 of the License, or
25 ;; (at your option) any later version.
27 ;; GNU Emacs is distributed in the hope that it will be useful,
28 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
29 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 ;; GNU General Public License for more details.
32 ;; You should have received a copy of the GNU General Public License
33 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
40 ;;; This is a patch because edebug binds under `C-x'.
41 ;; If `C-x' is not a prefix.
42 (unless (consp (key-binding "\C-x"))
43 ;; Disable the `C-xC-a' binds.
44 (defvar edebug-inhibit-emacs-lisp-mode-bindings)
45 (setq edebug-inhibit-emacs-lisp-mode-bindings t)
46 ;; And the `C-xX' binds.
47 (defvar global-edebug-prefix)
49 (or (null (boundp 'global-edebug-prefix))
50 (eq ?\C-x (elt global-edebug-prefix 0))))
51 (setq global-edebug-prefix "")))
57 (declare-function names--autoload-do-load "names" 2)
58 (defalias 'names--function-get
59 (if (fboundp 'function-get) #'function-get
61 (defun names--autoload-do-load (def name)
62 "Load autoloaded definition DEF from function named NAME."
63 (unless (load (cadr def) 'noerror)
64 (error "Macro `%s' is autoloaded, but its file (%s) couldn't be loaded"
66 (symbol-function name))
68 (lambda (f prop &rest _)
69 "Return the value of property PROP of function F.
70 If F is an autoloaded macro, try to autoload it in the hope that
73 (while (and (symbolp f)
74 (null (setq val (get f prop)))
76 (let ((fundef (symbol-function f)))
77 (if (and (names--autoloadp fundef)
78 (not (equal fundef (names--autoload-do-load fundef f))))
79 nil ;Re-try `get' on the same `f'.
83 (defalias 'names--compat-macrop
84 (if (fboundp 'macrop) #'macrop
86 "Non-nil if and only if OBJECT is a macro."
87 (let ((def (or (ignore-errors (indirect-function object t))
88 (ignore-errors (indirect-function object)))))
90 (or (eq 'macro (car def))
91 (and (names--autoloadp def) (memq (nth 4 def) '(macro t)))))))))
93 (defalias 'names--autoloadp
94 (if (fboundp 'autoloadp) #'autoloadp
96 "Non-nil if OBJECT is an autoload."
97 (eq 'autoload (car-safe object)))))
99 (unless (get-edebug-spec 'cl-defun)
100 (def-edebug-spec cl-defun defun*))
101 (unless (get-edebug-spec 'cl-defmacro)
102 (def-edebug-spec cl-defmacro defmacro*))
103 (unless (get-edebug-spec 'setq-local)
104 (def-edebug-spec setq-local setq))
105 (unless (get-edebug-spec 'loop)
106 (def-edebug-spec loop
108 ;; These are usually followed by a symbol, but it can
109 ;; actually be any destructuring-bind pattern, which
110 ;; would erroneously match `form'.
111 [[&or "for" "as" "with" "and"] sexp]
112 ;; These are followed by expressions which could
113 ;; erroneously match `symbolp'.
114 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
115 "above" "below" "by" "in" "on" "=" "across"
116 "repeat" "while" "until" "always" "never"
117 "thereis" "collect" "append" "nconc" "sum"
118 "count" "maximize" "minimize" "if" "unless"
120 ;; Simple default, which covers 99% of the cases.
124 ;;; ---------------------------------------------------------------
126 (defconst names-version "20151201.0" "Version of the names.el package.")
128 (defvar names--name nil
129 "Name of the current namespace inside the `define-namespace' macro.")
130 (defvar names--regexp nil "Regexp matching `names--name'.")
132 (defvar names--load-file (and load-file-name (expand-file-name load-file-name))
133 "The file where the current version of Names was loaded.
134 This is used by `names--check-for-update' to check if a new
135 version has been installed.")
137 (defvar names--bound nil
138 "List of variables defined in this namespace.")
139 (defvar names--fbound nil
140 "List of functions defined in this namespace.")
141 (defvar names--macro nil
142 "List of macros defined in this namespace.")
144 (defvar names--keywords nil
145 "Keywords that were passed to the current namespace.
146 See `names--keyword-list' for a list and description of possible
149 (defvar names--local-vars nil
150 "Non-global vars that are let/lambda bound at the moment.
151 These won't be namespaced, as local takes priority over namespace.")
153 (defvar names--protection nil
154 "Leading chars used to identify protected symbols.
155 Don't customise this.
156 Instead use the :protection keyword when defining the
159 (defvar names--current-run nil
160 "Either 1 or 2, depending on which runthrough we're in.")
162 (defvar names--var-list
163 '(names--name names--regexp names--bound
165 names--package names--group-parent
166 names--macro names--current-run
167 names--fbound names--keywords
168 names--local-vars names--protection)
169 "List of variables the user shouldn't touch.")
172 (defvar names--inside-make-autoload nil
173 "Used in `make-autoload' to indicate we're making autoloads.")
175 (defvar names--package nil
176 "Package, name to be used by the :group and :version keywords.
177 Is derived from `load-file-name', unless the :package keyword is
178 passed to `define-namespace'.")
180 (defvar names--group-parent nil
181 "The name of the parent to be given to `defgroup'.
182 Is only non-nil if the :group keyword is passed to `define-namespace'.")
184 (defvar names--version nil
185 "The version number given by :version.
186 Used to define a constant and a command.")
188 (defvar names--functionlike-macros nil
189 "Function-like macros, even if their debug-spec says otherwise.
190 When expanding the namespace, these macros will be treated
191 exactly like functions. This means that their contents will be
192 namespaced like regular function arguments.
194 To add macros to this list, pass the :functionlike-macros keyword
195 to your namespace along with a list of macro names (as unquoted
199 (define-namespace foo-
200 :functionlike-macros (-> ->> thread-first thread-last)
204 (defconst names--keyword-list
207 (if (or (symbolp x) (listp x))
208 (setq names--group-parent x)
210 "Argument given to :group is not a symbol: %s" x)))
211 "Indicate `define-namespace' should make a `defgroup' for you.
212 The name of the group is the package name (see :package keyword).
213 This keyword should be given one argument, the name of the PARENT
214 group as an unquoted symbol.
216 Alternatively, the argument can be a list, in which case it is a
217 list of arguments to be passed to `defgroup' (essentially, a full
218 group definition without the leading `defgroup').
220 If this keyword is provided, besides including a defgroup, Names
221 will also include a :group keyword in every `defcustom' (and
222 similar forms) that don't already contain one.")
228 (setq names--version x)
230 "Argument given to :version is not a string: %s" x)))
231 "Indicate `define-namespace' should define the version number.
232 This keyword should be given one argument, a string describing
233 the package's version number.
235 With this, Names will generate a `defconst' and an interactive
236 `defun', each named `PACKAGE-NAME-version'. The function messages
237 and returns the version number. See the :package keyword.")
243 (setq names--package x)
245 "Argument given to :package is not a symbol: %s" x)))
246 "Set the name of this package to the given symbol.
247 This keyword should be given one argument, a symbol corresponding
248 to the name of this package.
250 If this keyword isn't used, the package name is taken as the the
251 file's basename, but only if its actually needed. This name is
252 needed by the :version and :group keywords.")
257 (let ((val (symbol-name x)))
258 (setq names--protection
259 (format "\\`%s" (regexp-quote val)))))
260 "Change the value of the `names--protection' variable.")
262 (:functionlike-macros
264 ,(lambda (x) (setq names--functionlike-macros
265 (append x names--functionlike-macros)))
266 "A list of values to be appended to `names--functionlike-macros'.")
270 "Indicates variables assigned in let-bind are NOT candidates for namespacing.")
274 "Cause a message to be called on each special form.")
278 "Accept namespaced names from outside current namespace definition.")
282 "Indicate symbols quoted with `quote' should be considered variable names.")
284 (:dont-assume-function-quote
286 "Indicate symbols quoted with `function' should NOT be considered function names.")
290 "Indicate only forms actually inside the namespace should be present in the output.
291 This is for internal use. It is used by `names-eval-defun' to
292 prevent `define-namespace' from adding things like `defgroup' or
293 `defconst's to the output."))
294 "List of keywords used by `define-namespace'.
295 Each element is a list containing
296 (KEYWORD N DEFINITION DOCUMENTATION)
299 - KEYWORD is the keyword's name, a symbol satifying `keywordp'.
300 - N is the number of arguments it takes, an integer.
301 - DEFINITION is a function (symbol or lambda) that takes N
302 arguments and does whatever you need for implementing the
304 - DOCUMENTATION is a string explaining the keyword's
307 (defmacro names--prepend (sbl)
308 "Return namespace+SBL."
309 (declare (debug (symbolp)))
310 `(intern (format "%s%s" names--name ,sbl)))
313 (defmacro names--filter-if-bound (var &optional pred)
314 "If VAR is bound and is a list, take the car of its elements which satify PRED."
315 (declare (debug (symbolp &optional function-form)))
316 `(when (boundp ',var)
319 (mapcar (lambda (x) (when (funcall (or ,pred #'identity) (or (car-safe x) x))
320 (or (car-safe x) x)))
323 (defmacro names--next-keyword (body)
324 "If car of BODY is a known keyword, `pop' it (and its arguments) from body.
325 Returns a list (KEYWORD . ARGUMENTLIST)."
326 (declare (debug sexp))
327 `(let ((kar (car-safe ,body))
331 (setq n (assoc kar names--keyword-list))
333 (dotimes (_ (1+ n) out)
334 (push (pop ,body) out))
337 (defvar names--has-reloaded nil
338 "Whether `names--reload-if-upgraded' has already been called in this run.")
341 ;;; ---------------------------------------------------------------
342 ;;; The Main Macro and Main Function.
344 (defmacro define-namespace (name &rest body)
345 "Inside the namespace NAME, execute BODY.
346 NAME can be any symbol (not quoted), but it's highly recommended
347 to use some form of separator (such as :, /, or -). For a
348 complete description of this macro, please visit the frontpage
349 with \\[names-view-manual].
351 In summary, this macro has two main effects:
353 1. Any definitions inside BODY will have NAME prepended to the
356 (define-namespace foo-
357 (defvar bar 1 \"docs\")
362 (defvar foo-bar 1 \"docs\")
365 2. Any function calls and variable names get NAME prepended to
366 them if such a variable or function exists. Ex:
368 (define-namespace foo:
369 (defun message (x y) nil)
370 (message \"%s\" my-var)
375 (defun foo:message (x y) nil)
376 (foo:message \"%s\" my-var)
378 Note how `message' is expanded to `foo:message' in the second
379 form, because that function exists. Meanwhile, `bar' is left
380 untouched because `foo:bar' is not a known variable name.
382 ===============================
386 In order for `define-namespace' to work with \";;;###autoload\"
387 comments must replace all instances of \";;;###autoload\" inside
388 your `define-namespace' with `:autoload'.
389 Afterwards, add an \";;;###autoload\" comment just above your
392 ===============================
396 Immediately after NAME you may add keywords which customize the
397 behaviour of `define-namespace'. For a list of possible keywords
398 and a description of their effects, see the variable
399 `names--keyword-list'.
401 \(fn NAME [KEYWORD ...] BODY)"
402 (declare (indent (lambda (&rest x) 0))
403 (debug (&define name [&rest keywordp &optional [&or symbolp (symbolp . symbolp)]] body)))
404 (let ((names--has-reloaded names--has-reloaded))
405 ;; This was to avoid an infinite recursion, but the bug turned out
406 ;; to be somewhere else. Still, I see no reason to erase this.
407 (unless names--has-reloaded
408 (setq names--has-reloaded t)
409 (names--reload-if-upgraded))
410 (names--error-if-using-vars)
411 (names--define-namespace-implementation name body)))
413 (defun names--define-namespace-implementation (name body)
414 "Namespace BODY using NAME.
415 See `define-namespace' for more information."
417 (let* ((names--name name)
419 (concat "\\`" (regexp-quote (symbol-name name))))
420 (names--current-run 0)
421 ;; Use the :protection keyword to change this.
422 (names--protection "\\`::")
424 (names--remove-namespace-from-list
425 (names--filter-if-bound byte-compile-bound-variables)
426 (names--filter-if-bound byte-compile-variables)))
428 (names--remove-namespace-from-list
429 (names--filter-if-bound byte-compile-macro-environment 'names--compat-macrop)
430 (names--filter-if-bound byte-compile-function-environment 'names--compat-macrop)))
432 (names--remove-namespace-from-list
433 (names--filter-if-bound byte-compile-macro-environment (lambda (x) (not (names--compat-macrop x))))
434 (names--filter-if-bound byte-compile-function-environment (lambda (x) (not (names--compat-macrop x))))))
435 (names--functionlike-macros names--functionlike-macros)
436 names--keywords names--local-vars key-and-args
437 names--version names--package names--group-parent)
439 (while (setq key-and-args (names--next-keyword body))
440 (names--handle-keyword key-and-args)
441 (push key-and-args names--keywords))
443 ;; First have to populate the bound and fbound lists. So we read
444 ;; the entire form (without return it).
445 (if names--inside-make-autoload
446 ;; Dependencies haven't been loaded during autoload
447 ;; generation, so we better ignore errors here. Ideally we
448 ;; would only go through the forms marked for autoloading,
449 ;; but then we wouldn't know what symbols are var/function
451 (mapc (lambda (form) (ignore-errors (names-convert-form form))) body)
452 (mapc #'names-convert-form body))
453 (setq names--current-run (1+ names--current-run))
455 ;; Then we go back and actually namespace the entire form, which
456 ;; we'll later return so that it can be evaluated.
461 (when (and names--group-parent
462 (null (names--keyword :clean-output)))
463 (list (names--generate-defgroup)))
464 (when (and names--version
465 (null (names--keyword :clean-output)))
466 ;; `names--generate-version' returns a list.
467 (names--generate-version))
468 (mapcar 'names-convert-form
469 ;; Unless we're in `make-autoload', then just return autoloads.
470 (if names--inside-make-autoload
471 (names--extract-autoloads body)
474 ;; On emacs-version < 24.4, the byte-compiler cannot expand a
475 ;; macro if it is being called in the same top-level form as
476 ;; it was defined. That's a problem for us, since the entire
477 ;; namespace is a single top-level form (we return a `progn').
478 ;; The solution is for us to add the macros to
479 ;; `byte-compile-macro-environment' ourselves.
480 (if (and (boundp 'byte-compile-current-buffer)
481 byte-compile-current-buffer
482 (null names--inside-make-autoload)
483 (version< emacs-version "24.4"))
484 (let ((byte-compile-macro-environment
485 (when (boundp 'byte-compile-macro-environment)
486 byte-compile-macro-environment)))
487 (mapc #'names--add-macro-to-environment (cdr body))
488 (macroexpand-all body byte-compile-macro-environment))
491 ;; Exiting the `unwind-protect'.
492 (mapc (lambda (x) (set x nil)) names--var-list)))
494 (defun names--reload-if-upgraded ()
495 "Verify if there's a more recent version of Names in the `load-path'.
499 (let ((lp (expand-file-name (find-library-name "names")))
502 (not (string= lp names--load-file))
503 (file-readable-p lp))
505 (insert-file-contents-literally lp)
506 (goto-char (point-min))
509 (when (search-forward-regexp
510 "(defconst\\s-+names-version\\s-+\"\\([^\"]+\\)\"" nil t)
511 (match-string-no-properties 1))))
512 (when (and new-version (version< names-version new-version))
513 (eval-buffer nil lp)))))))
515 (defun names-convert-form (form)
516 "Do namespace conversion on FORM.
517 FORM is any legal elisp form.
518 Namespace name is defined by the global variable `names--name'.
520 See macro `namespace' for more information."
525 (let ((kar (car form))
528 ;; If symbol is protected, clean it.
530 (setq func (names--remove-protection kar)))
531 (names--message "Protected: %s" kar)
532 ;; And decide what to do with it.
533 (names--handle-args func (cdr form)))
535 ;; If kar is a list, either 1) it's a lambda form, 2) it's a
536 ;; macro we don't know about yet, 3) we have a bug.
538 (when (and (null (functionp kar))
539 (> names--current-run 1))
540 (names--warn "Ran into the following strange form.
541 Either it's an undefined macro, a macro with a bad debug declaration, or we have a bug.\n%s" form))
542 (mapcar 'names-convert-form form))
544 ;; Namespaced Functions/Macros
545 ((names--fboundp kar)
546 (names--message "Namespaced: %s" kar)
547 (names--args-of-function-or-macro
548 (names--prepend kar) (cdr form) (names--macrop kar)))
550 ;; General functions/macros/special-forms
551 (t (names--handle-args kar (cdr form))))))
554 (names--message "Symbol handling: %s" form)
555 ;; If symbol is protected, clean it and don't namespace it.
556 (or (names--remove-protection form)
557 ;; Otherwise, namespace if possible.
558 (if (names--boundp form)
559 (names--prepend form)
565 ;;; ---------------------------------------------------------------
566 ;;; Some auxiliary functions
567 (defun names-view-manual ()
568 "Call `browse-url' to view the manual of the Names package."
570 (browse-url "http://github.com/Malabarba/names"))
572 (defun names--package-name ()
573 "Return the package name as a symbol.
574 Decide package name based on several factors. In order:
575 1. The :package keyword,
576 2. The namespace NAME, removing the final char."
578 (let ((package (symbol-name names--name)))
579 (prog1 (setq names--package
580 (intern (substring package 0 -1)))
581 (names--warn "No :package given. Guessing `%s'"
584 (defun names--generate-defgroup ()
585 "Return a `defgroup' form for the current namespace."
586 (if (listp names--group-parent)
587 (cons 'defgroup names--group-parent)
588 (list 'defgroup (names--package-name) nil
589 (format "Customization group for %s." (names--package-name))
590 :prefix (symbol-name names--name)
591 :group `',names--group-parent)))
593 (defun names--generate-version ()
594 "Return a `defun' and a `defconst' forms declaring the package version.
595 Also adds `version' to `names--fbound' and `names--bound'."
596 (add-to-list 'names--fbound 'version)
597 (add-to-list 'names--bound 'version)
599 (list 'defconst (names--prepend 'version)
601 (format "Version of the %s package." (names--package-name)))
602 (list 'defun (names--prepend 'version) nil
603 (format "Version of the %s package." (names--package-name))
606 ,(format "%s version: %s" (names--package-name) names--version))
609 (defun names--add-macro-to-environment (form)
610 "If FORM declares a macro, add it to `byte-compile-macro-environment'."
611 (let ((expansion form))
612 (while (names--compat-macrop (car-safe expansion))
614 (ignore-errors (macroexpand
615 expansion byte-compile-macro-environment))))
618 (or (and (memq (car-safe expansion) '(progn prog1 prog2))
619 (mapc #'names--add-macro-to-environment (cdr expansion)))
620 (and (eq 'defalias (car-safe expansion))
621 (let ((def (ignore-errors (eval (nth 2 expansion)))))
622 (and (names--compat-macrop def)
623 (push (cons (ignore-errors
624 (eval (nth 1 expansion)))
626 byte-compile-macro-environment))))))))
629 (eval-after-load 'find-func
630 '(defadvice find-function-search-for-symbol
631 (around names-around-find-function-search-for-symbol-advice
632 (symbol type library) activate)
633 "Make sure `find-function-search-for-symbol' understands namespaces."
636 (unless (cdr ad-return-value)
637 (with-current-buffer (car ad-return-value)
638 (search-forward-regexp "^(define-namespace\\_>")
639 (skip-chars-forward "\r\n[:blank:]")
640 (let* ((names--regexp
641 (concat "\\`" (regexp-quote
642 (symbol-name (read (current-buffer))))))
644 ;; We manually implement `names--remove-namespace'
645 ;; because it might not be loaded.
646 (let ((name (symbol-name symbol)))
647 (when (string-match names--regexp name)
648 (intern (replace-match "" nil nil name))))))
650 (ad-set-arg 0 short-symbol)
653 (defun names--extract-autoloads (body)
654 "Return a list of the forms in BODY preceded by :autoload."
656 (when (setq acons (memq :autoload body))
659 (names--extract-autoloads (cdr (cdr acons)))))))
662 (defadvice make-autoload (around names-before-make-autoload-advice
663 (form file &optional expansion) activate)
664 "Make sure `make-autoload' understands `define-namespace'.
665 Use the `names--inside-make-autoload' variable to indicate to
666 `define-namespace' that we're generating autoloads."
667 ;; We used to have a letbind here, but this was causing a void
668 ;; variable bug on Emacs 24.3.
670 (if (null (eq (car-safe form) 'define-namespace))
672 (setq names--inside-make-autoload t)
673 (setq form (macroexpand form))
674 (setq names--inside-make-autoload nil)
675 ;; Up to 24.2 `make-autoload' couldn't handle `progn's.
676 (if (version< emacs-version "24.3")
677 (setq ad-return-value
679 (mapcar (lambda (x) (names--make-autoload-compat x file))
681 (ad-set-arg 2 'expansion)
685 (defun names--make-autoload-compat (form file)
686 (if (eq (car-safe form) 'defalias)
688 (make-autoload form file)))
690 (defvar names--ignored-forms '(declare)
691 "The name of functions/macros/special-forms which we return without reading.")
693 (defun names--handle-args (func args)
694 "Generic handling for the form (FUNC . ARGS), without namespacing FUNC."
695 (if (memq func names--ignored-forms)
697 ;; TODO: Speed this up. Just change it to an alist or a hash-table.
698 (let ((handler (intern-soft (format "names--convert-%s" func))))
699 ;; Some function-like forms get special handling.
700 ;; That's anything with a names--convert-%s function defined.
701 (if (fboundp handler)
702 (progn (names--message "Special handling: %s" handler)
703 (funcall handler (cons func args)))
704 ;; If it isn't special, it's either a function or a macro.
705 (names--args-of-function-or-macro func args (names--compat-macrop func))))))
707 (defun names--message (f &rest rest)
708 "If :verbose is on, pass F and REST to `message'."
709 (when (names--keyword :verbose)
710 (apply #'message (concat "[names] " f) rest)))
712 (defun names--warn (f &rest rest)
713 "Pass F and REST to `message', unless byte-compiling or non-interactive."
714 (unless (and (null (names--keyword :verbose))
715 (and (boundp 'byte-compile-function-environment)
716 byte-compile-function-environment))
717 (apply #'message (concat "[names] " f) rest)))
719 (defun names--error-if-using-vars ()
720 "Remind the developer that variables are not customizable."
724 (error "[names] Global value of variable %s should be nil! %s"
725 x "Set it using keywords instead")))
728 (defun names--remove-namespace-from-list (&rest lists)
729 "Return a concatenated un-namespaced version of LISTS.
730 Symbols in LISTS that aren't namespaced are removed, symbols that
731 are namespaced become un-namespaced."
732 (delq nil (mapcar 'names--remove-namespace (apply #'append lists))))
734 (defun names--remove-namespace (symbol)
735 "Return SYMBOL with namespace removed, or nil if it wasn't namespaced."
736 (names--remove-regexp symbol names--regexp))
738 (defun names--remove-protection (symbol)
739 "Remove the leading :: from SYMBOL if possible, otherwise return nil."
740 (names--remove-regexp symbol names--protection))
742 (defun names--remove-regexp (s r)
743 "Return S with regexp R removed, or nil if S didn't match."
744 (let ((name (symbol-name s)))
745 (when (string-match r name)
746 (intern (replace-match "" nil nil name)))))
748 (defun names--quote-p (sbl)
749 "Is SBL a function which quotes its argument?"
750 (memq sbl '(quote function)))
752 (defun names--fboundp (sbl)
753 "Is namespace+SBL a fboundp symbol?"
754 (or (memq sbl names--fbound)
755 (memq sbl names--macro)
756 (and (names--keyword :global)
757 (fboundp (names--prepend sbl)))))
759 (defun names--macrop (sbl)
760 "Is namespace+SBL a fboundp symbol?"
761 (or (memq sbl names--macro)
762 (and (names--keyword :global)
763 (names--compat-macrop (names--prepend sbl)))))
765 (defun names--keyword (keyword)
766 "Was KEYWORD one of the keywords passed to the `namespace' macro?"
767 (assoc keyword names--keywords))
769 (defun names--boundp (sbl)
770 "Is namespace+SBL a boundp symbol?
771 If SBL has a let binding, that takes precendence so this also
773 (and (null (memq sbl names--local-vars))
774 (or (memq sbl names--bound)
775 (and (names--keyword :global)
776 (boundp (names--prepend sbl))))))
778 (defvar names--verbose nil
779 "If non-nil, verbose message are printed regardless of the :verbose keyword.
780 Use this to easily turn on verbosity during tests.")
782 (defun names--args-of-function-or-macro (function args macro)
783 "Namespace FUNCTION's arguments ARGS, with special treatment if MACRO is non-nil."
785 (let ((it (names--get-edebug-spec function))
786 (names--verbose (eq function 'push)))
787 (names--message "Edebug-spec of `%s' is %s" function it)
788 ;; Macros where we evaluate all arguments are like functions.
790 (memq function names--functionlike-macros))
791 (names--args-of-function-or-macro function args nil)
792 ;; Macros where nothing is evaluated we can just return.
795 ;; Other macros are complicated. Ask edebug for help.
796 (names--macro-args-using-edebug (cons function args)))))
797 ;; We just convert the arguments of functions.
798 (cons function (mapcar 'names-convert-form args))))
800 (defun names--get-edebug-spec (name)
801 "Get 'edebug-form-spec property of symbol NAME."
802 ;; Get the spec of symbol resolving all indirection.
806 (and (symbolp indirect)
809 indirect 'edebug-form-spec 'macro))))
810 ;; (edebug-trace "indirection: %s" edebug-form-spec)
811 (setq spec indirect))
814 (defvar names--is-inside-macro nil
815 "Auxiliary var used in `names--macro-args-using-edebug'.")
817 (defvar names--gensym-counter 0
818 "Counter used to uniquify symbols generated `names--gensym'.")
820 (defun names--macro-args-using-edebug (form)
821 "Namespace the arguments of macro FORM by hacking into edebug.
822 This takes advantage of the fact that macros (should) declare a
823 `debug' specification which tells us which arguments are actually
826 Ideally, we would read this specification ourselves and see how
827 it matches (cdr FORM), but that would take a lot of work and
828 we'd be reimplementing something that edebug already does
829 phenomenally. So we hack into edebug instead."
833 ((max-lisp-eval-depth 3000)
836 (names--is-inside-macro form)
837 ;; Prevent excessive messaging.
838 ;; TODO: Don't do this if `message' is advised.
839 ((symbol-function 'message) #'names--edebug-message)
840 ;; Older edebugs have poor `get-edebug-spec'.
841 ((symbol-function 'get-edebug-spec) #'names--get-edebug-spec)
842 ;; Give symbols our own name.
843 ((symbol-function 'cl-gensym) #'names--gensym)
844 ;; Stop at one level deep.
845 ((symbol-function 'edebug-form) #'names--edebug-form)
846 ;; Don't actually wrap anything.
847 ((symbol-function 'edebug-make-enter-wrapper)
848 #'names--edebug-make-enter-wrapper))
852 (goto-char (point-min))
854 (edebug-read-top-level-form))
857 "Couldn't namespace this macro using its (debug ...) declaration: %s"
861 (when (equal (car-safe (cdr-safe er))
862 "Lisp nesting exceeds `max-lisp-eval-depth'")
864 "Lisp nesting exceeded `max-lisp-eval-depth' at the following form: %s"
868 (defvar names--message-backup
869 (if (ad-is-advised 'message)
870 (ad-get-orig-definition 'message)
871 (symbol-function 'message))
872 "Where names stores `message's definition while overriding it.")
874 (defun names--edebug-message (&rest args)
875 (if (or (names--keyword :verbose) names--verbose)
876 (apply names--message-backup args)
877 (when args (apply #'format args))))
879 (defun names--edebug-make-enter-wrapper (forms)
880 (setq edebug-def-name
883 (names--gensym "edebug-anon")))
886 (defun names--gensym (prefix)
887 "Generate a new uninterned symbol.
888 The name is made by appending a number to PREFIX and preppending \"names\", default \"G\"."
889 (let ((num (prog1 names--gensym-counter
890 (setq names--gensym-counter
891 (1+ names--gensym-counter)))))
892 (make-symbol (format "names-%s%d" (if (stringp prefix) prefix "G") num))))
894 (defun names--edebug-form (cursor)
895 "Parse form given by CURSOR using edebug, and namespace it if necessary."
897 ;; Return the instrumented form for the following form.
898 ;; Add the point offsets to the edebug-offset-list for the form.
899 (let* ((form (edebug-top-element-required cursor "Expected form"))
900 (offset (edebug-top-offset cursor))
901 ;; We don't want to convert the entire form that was passed
902 ;; to `names--macro-args-using-edebug', since the head of
903 ;; that was already converted and it would lead to an
905 ;; So we check for (equal names--is-inside-macro form)
906 ;; Simply incrementing a depth counter didn't work, for a
907 ;; reason I can no longer remember.
909 ;; We DO want to convert the arguments that edebug identifies
910 ;; as forms (level-1). And we do that ourselves, don't pass
912 (func (if (or (eq names--is-inside-macro t)
913 (equal names--is-inside-macro form))
914 'identity 'names-convert-form))
915 (names--is-inside-macro
916 (if (eq func 'names-convert-form)
917 t names--is-inside-macro)))
918 (names--message " [Edebug] Ran into this: %S" form)
919 (names--message " Cursor: %S" cursor)
922 ((consp form) ;; The first offset for a list form is for the list form itself.
923 (if (eq func 'names-convert-form)
924 (names-convert-form form)
925 (let* ((head (car form))
926 (spec (and (symbolp head) (get-edebug-spec head)))
927 (new-cursor (edebug-new-cursor form offset)))
928 ;; Find out if this is a defining form from first symbol.
929 ;; An indirect spec would not work here, yet.
930 (if (and (consp spec) (eq '&define (car spec)))
931 (edebug-defining-form
933 (car offset) ;; before the form
934 (edebug-after-offset cursor)
935 (cons (symbol-name head) (cdr spec)))
936 ;; Wrap a regular form.
937 (edebug-list-form new-cursor)))))
942 ;; Anything else is self-evaluating.
944 (edebug-move-cursor cursor))))
946 (defun names--maybe-append-group (form)
947 "Append (:group `names--package') to FORM.
948 Only if the :group keyword was passed to `define-namespace' and
949 if the form doesn't already have a :group."
950 (if (or (null names--group-parent) (memq :group form))
952 (append form `(:group ',(names--package-name)))))
955 ;;; ---------------------------------------------------------------
956 ;;; Interpreting keywords passed to the main macro.
957 (defun names--handle-keyword (body)
958 "Call the function that handles the keyword at the car of BODY.
959 Such function must be listed in `names--keyword-list'. If it is
960 nil, this function just returns.
962 Regardless of whether a function was called, the keyword is added
963 to the variable `names--keywords'.
965 The car of BODY is the keyword itself and the other elements are
966 the keyword arguments, if any."
967 (let ((func (nth 2 (assoc (car body) names--keyword-list))))
969 (apply func (cdr body))
973 ;;; ---------------------------------------------------------------
974 ;;; Interpreting the actual forms found in BODY of the main macro.
976 ;; This is where the heavy work is done.
978 ;; If you'd like to implement support for some special form, simply
979 ;; define a function called `names--convert-FORM-NAME' along the
980 ;; lines of the functions defined below. It will be automatically used
981 ;; whenever that form is found.
983 ;; Defun, defmacro, and defsubst macros are pretty predictable.
984 (defun names--convert-defmacro (form)
985 "Special treatment for `defmacro' FORM."
986 (let* ((name (cadr form))
987 (spaced-name (names--prepend name))
989 (add-to-list 'names--macro name)
990 (add-to-list 'names--fbound name)
991 ;; Set the macros debug spec if possible. It will be relevant on
993 (when (setq decl (ignore-errors (cond
994 ((eq (car-safe (nth 3 form)) 'declare)
996 ((and (stringp (nth 3 form))
997 (eq (car-safe (nth 4 form)) 'declare))
1000 (setq decl (car (cdr-safe (assoc 'debug (cdr decl)))))
1001 (when decl (put spaced-name 'edebug-form-spec decl)))
1002 ;; Then convert the macro as a defalias.
1005 (names--convert-lambda
1006 (cons spaced-name (cddr form))))))
1007 (defalias 'names--convert-defmacro* 'names--convert-defmacro)
1009 (defun names--convert-defvaralias (form)
1010 "Special treatment for `defvaralias' FORM."
1011 (let ((form (cons (car form)
1012 (mapcar #'names-convert-form (cdr form))))
1014 (setq name (names--remove-namespace
1015 (ignore-errors (eval (cadr form)))))
1017 (add-to-list 'names--bound name))
1020 (defun names--convert-defalias (form)
1021 "Special treatment for `defalias' FORM."
1022 (let ((form (cons (car form)
1023 (mapcar #'names-convert-form (cdr form))))
1025 (setq name (names--remove-namespace
1026 (ignore-errors (eval (cadr form)))))
1028 (add-to-list 'names--fbound name))
1031 (defun names--convert-defvar (form &optional dont-add)
1032 "Special treatment for `defvar' FORM.
1033 If DONT-ADD is nil, the FORM's `cadr' is added to `names--bound'."
1034 (let ((name (cadr form)))
1036 (add-to-list 'names--bound name))
1040 (names--prepend name))
1041 (mapcar 'names-convert-form (cdr (cdr form))))))
1043 (defalias 'names--convert-defconst 'names--convert-defvar
1044 "Special treatment for `defconst' FORM.")
1046 (defun names--convert-defcustom (form)
1047 "Special treatment for `defcustom' FORM."
1048 (names--maybe-append-group
1049 (names--convert-defvar form)))
1051 (defun names--convert-custom-declare-variable (form)
1052 "Special treatment for `custom-declare-variable' FORM."
1053 (let ((name (eval (cadr form))) ;;ignore-errors
1054 (val (car (cddr form))))
1055 (add-to-list 'names--bound name)
1059 (list 'quote (names--prepend name)) ;cadr
1060 ;; The DEFAULT argument is explicitly evaluated by
1061 ;; `custom-declare-variable', so it should be safe to namespace
1062 ;; even when quoted. Plus, we need to do this because
1063 ;; defcustom quotes this part.
1064 (if (names--quote-p (car-safe val))
1065 (list (car val) (names-convert-form (cadr val)))
1066 (names-convert-form val))
1067 (names-convert-form (car (cdr (cdr (cdr form))))))
1068 (mapcar 'names-convert-form (cdr (cdr (cdr (cdr form))))))))
1070 (defun names--convert-defface (form)
1071 "Special treatment for `defface' FORM.
1072 Identical to defvar, just doesn't add the symbol to the boundp
1073 list. And maybe use a :group."
1074 (names--maybe-append-group
1075 (names--convert-defvar form :dont-add)))
1077 (defun names--convert-define-derived-mode (form)
1078 "Special treatment for `define-derived-mode' FORM."
1079 (let ((name (cadr form)))
1080 (add-to-list 'names--fbound name)
1081 (add-to-list 'names--bound name)
1082 (add-to-list 'names--bound
1083 (intern (format "%s-map" name)))
1084 (add-to-list 'names--bound
1085 (intern (format "%s-hook" name)))
1087 (names--maybe-append-group
1088 ;; And here we namespace it.
1091 (names--prepend name)
1093 (names-convert-form (nth 3 form))
1094 (names-convert-form (nth 4 form))))
1095 (mapcar #'names-convert-form (cddr (cl-cdddr form))))))
1097 (defun names--convert-define-minor-mode (form)
1098 "Special treatment for `define-minor-mode' FORM."
1099 (let ((name (cadr form))
1100 (keymap (nth 5 form)))
1101 ;; Register the mode name
1102 (add-to-list 'names--fbound name)
1103 (add-to-list 'names--bound name)
1104 (add-to-list 'names--bound (intern (format "%s-hook" name)))
1105 ;; Register the keymap
1106 (if (or (null keymap) (null (symbolp keymap)))
1107 (add-to-list 'names--bound (intern (format "%s-map" name)))
1108 (when (setq keymap (names--remove-namespace keymap))
1109 (add-to-list 'names--bound keymap)))
1111 (names--maybe-append-group
1112 ;; And here we namespace it.
1115 (names--prepend name)
1117 (names-convert-form (nth 3 form))
1118 (names-convert-form (nth 4 form))
1119 (names-convert-form (nth 5 form))
1120 (names-convert-form (nth 6 form))))
1121 (mapcar #'names-convert-form (cddr form)))))
1123 (defun names--convert-define-globalized-minor-mode (form)
1124 "Special treatment for `define-globalized-minor-mode' FORM.
1125 The NAME of the global mode will NOT be namespaced, despite being
1126 a definition. It is kept verbatim.
1127 This is because people tend to name their global modes as
1128 `global-foo-mode', and namespacing would make this impossible.
1130 The MODE and TURN-ON arguments are converted as function names.
1131 Everything else is converted as regular forms (which usually
1132 means no conversion will happen since it's usually keywords and
1134 (let ((name (names--remove-namespace (cadr form)))
1135 (copy (cl-copy-list form)))
1136 ;; Register the mode name
1138 (add-to-list 'names--fbound name)
1139 (add-to-list 'names--bound name)
1140 (add-to-list 'names--bound (intern (format "%s-hook" name))))
1141 (names--maybe-append-group
1142 ;; And here we namespace it.
1147 (names--handle-symbol-as-function (pop copy))
1148 (names--handle-symbol-as-function (pop copy)))
1149 (mapcar #'names-convert-form copy)))))
1150 (defalias 'names--convert-define-global-minor-mode
1151 #'names--convert-define-globalized-minor-mode)
1152 (defalias 'names--convert-easy-mmode-define-global-mode
1153 #'names--convert-define-globalized-minor-mode)
1155 (defun names--convert-quote (form)
1156 "Special treatment for `quote' FORM.
1157 When FORM is (quote argument), argument too arbitrary to be
1158 logically namespaced and is never parsed for namespacing
1159 (but see :assume-var-quote in `names--keyword-list').
1161 When FORM is (function form), a symbol is namespaced as a
1162 function name, a list is namespaced as a lambda form."
1163 (let ((kadr (cadr form))
1164 (this-name (car form)))
1165 (if (and (eq this-name 'function)
1167 (list this-name (names-convert-form kadr))
1170 ;; A symbol inside a function quote should be a function,
1171 ;; unless the user disabled that.
1172 ((and (eq this-name 'function)
1173 (null (names--keyword :dont-assume-function-quote)))
1175 (names--handle-symbol-as-function kadr)))
1177 ;; A symbol inside a regular quote should be a function, if
1178 ;; the user asked for that.
1179 ((and (eq this-name 'quote)
1180 (names--keyword :assume-var-quote))
1182 (or (names--remove-protection kadr)
1183 (if (names--boundp kadr)
1184 (names--prepend kadr)
1190 (defun names--handle-symbol-as-function (s)
1191 "Namespace symbol S as a function name."
1192 (or (names--remove-protection s)
1193 (if (names--fboundp s) (names--prepend s) s)))
1195 (defalias 'names--convert-function 'names--convert-quote)
1197 (defun names--convert-macro (form)
1198 "Special treatment for `macro' form.
1199 Return (macro . (names-convert-form (cdr FORM)))."
1200 (cons 'macro (names-convert-form (cdr form))))
1202 (defun names--convert-lambda (form)
1203 "Special treatment for `lambda' FORM."
1204 (let ((names--local-vars
1205 (append (names--vars-from-arglist (cadr form))
1207 (forms (cdr (cdr form))))
1211 (when (stringp (car forms))
1214 (setq forms (cdr forms))))
1215 (when (eq 'interactive (car-safe (car forms)))
1217 (list (list (car (car forms))
1218 (names-convert-form (cadr (car forms)))))
1219 (setq forms (cdr forms))))
1221 ;; (message "%S" forms)
1222 (mapcar 'names-convert-form forms)))))
1224 (defun names--convert-clojure (form)
1225 "Special treatment for `clojure' FORM."
1226 (names--warn "Found a `closure'! You should use `lambda's instead")
1227 (let ((names--local-vars
1228 (append (names--vars-from-arglist (cadr form))
1229 names--local-vars)))
1232 (names--convert-lambda (cdr form)))))
1234 (defun names--vars-from-arglist (args)
1235 "Get a list of local variables from a generalized arglist ARGS."
1240 (let ((symb (or (cdr-safe (car-safe x)) (car-safe x) x)))
1241 (when (and (symbolp symb)
1242 (null (string-match "^&" (symbol-name symb)))
1247 (defun names--convert-defun (form)
1248 "Special treatment for `defun' FORM."
1249 (let* ((name (cadr form)))
1250 (add-to-list 'names--fbound name)
1252 (names--convert-lambda
1253 (cons (names--prepend name) (cddr form))))))
1254 (defalias 'names--convert-defun* 'names--convert-defun)
1255 (defalias 'names--convert-defsubst 'names--convert-defun)
1256 (defalias 'names--convert-defsubst* 'names--convert-defun)
1258 (defun names--let-var-convert-then-add (sym add)
1259 "Try to convert SYM unless :no-let-vars is in use.
1260 If ADD is non-nil, add resulting symbol to `names--local-vars'."
1261 (let ((name (if (null (names--keyword :no-let-vars))
1262 (names-convert-form sym)
1264 (when add (add-to-list 'names--local-vars name))
1267 (defun names--convert-let (form &optional star)
1268 "Special treatment for `let' FORM.
1269 If STAR is non-nil, parse as a `let*'."
1270 (let* ((names--local-vars names--local-vars)
1275 (list (names--let-var-convert-then-add (car x) star)
1276 (names-convert-form (cadr x)))
1277 (names--let-var-convert-then-add x star)))
1279 ;; Each var defined in a regular `let' only becomes protected after
1280 ;; all others have been defined.
1282 (setq names--local-vars
1284 (mapcar (lambda (x) (or (car-safe x) x)) vars)
1285 names--local-vars)))
1287 (list (car form) vars)
1288 (mapcar 'names-convert-form (cddr form)))))
1290 (defun names--convert-let* (form)
1291 "Special treatment for `let' FORM."
1292 (names--convert-let form t))
1294 (defun names--convert-cond (form)
1295 "Special treatment for `cond' FORM."
1299 (lambda (x) (mapcar #'names-convert-form x))
1302 (defun names--convert-condition-case (form)
1303 "Special treatment for `condition-case' FORM."
1308 (names-convert-form (cadr (cdr form))))
1312 (mapcar 'names-convert-form (cdr x))))
1313 (cddr (cdr form)))))
1316 ;;; names.el ends here