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 <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 (defvar edebug-inhibit-emacs-lisp-mode-bindings)
48 (setq edebug-inhibit-emacs-lisp-mode-bindings t)
49 ;; And the `C-xX' binds.
50 (defvar global-edebug-prefix)
51 (when (or (null (boundp 'global-edebug-prefix))
52 (eq ?\C-x (elt global-edebug-prefix 0)))
53 (setq global-edebug-prefix "")))
59 (declare-function names--autoload-do-load "names" 2)
60 (defalias 'names--function-get
61 (if (fboundp 'function-get) #'function-get
63 (defun names--autoload-do-load (def name)
64 "Load autoloaded definition DEF from function named NAME."
65 (unless (load (cadr def) 'noerror)
66 (error "Macro `%s' is autoloaded, but its file (%s) couldn't be loaded"
68 (symbol-function name))
70 (lambda (f prop &rest _)
71 "Return the value of property PROP of function F.
72 If F is an autoloaded macro, try to autoload it in the hope that
75 (while (and (symbolp f)
76 (null (setq val (get f prop)))
78 (let ((fundef (symbol-function f)))
79 (if (and (names--autoloadp fundef)
80 (not (equal fundef (names--autoload-do-load fundef f))))
81 nil ;Re-try `get' on the same `f'.
85 (defalias 'names--compat-macrop
86 (if (fboundp 'macrop) #'macrop
88 "Non-nil if and only if OBJECT is a macro."
89 (let ((def (or (ignore-errors (indirect-function object t))
90 (ignore-errors (indirect-function object)))))
92 (or (eq 'macro (car def))
93 (and (names--autoloadp def) (memq (nth 4 def) '(macro t)))))))))
95 (defalias 'names--autoloadp
96 (if (fboundp 'autoloadp) #'autoloadp
98 "Non-nil if OBJECT is an autoload."
99 (eq 'autoload (car-safe object)))))
101 (unless (get-edebug-spec 'cl-defun)
102 (def-edebug-spec cl-defun defun*))
103 (unless (get-edebug-spec 'cl-defmacro)
104 (def-edebug-spec cl-defmacro defmacro*))
105 (unless (get-edebug-spec 'setq-local)
106 (def-edebug-spec setq-local setq))
107 (unless (get-edebug-spec 'loop)
108 (def-edebug-spec loop
110 ;; These are usually followed by a symbol, but it can
111 ;; actually be any destructuring-bind pattern, which
112 ;; would erroneously match `form'.
113 [[&or "for" "as" "with" "and"] sexp]
114 ;; These are followed by expressions which could
115 ;; erroneously match `symbolp'.
116 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
117 "above" "below" "by" "in" "on" "=" "across"
118 "repeat" "while" "until" "always" "never"
119 "thereis" "collect" "append" "nconc" "sum"
120 "count" "maximize" "minimize" "if" "unless"
122 ;; Simple default, which covers 99% of the cases.
126 ;;; ---------------------------------------------------------------
128 (defconst names-version "20150618.0" "Version of the names.el package.")
130 (defvar names--name nil
131 "Name of the current namespace inside the `define-namespace' macro.")
132 (defvar names--regexp nil "Regexp matching `names--name'.")
134 (defvar names--load-file (and load-file-name (expand-file-name load-file-name))
135 "The file where the current version of Names was loaded.
136 This is used by `names--check-for-update' to check if a new
137 version has been installed.")
139 (defvar names--bound nil
140 "List of variables defined in this namespace.")
141 (defvar names--fbound nil
142 "List of functions defined in this namespace.")
143 (defvar names--macro nil
144 "List of macros defined in this namespace.")
146 (defvar names--keywords nil
147 "Keywords that were passed to the current namespace.
148 See `names--keyword-list' for a list and description of possible
151 (defvar names--local-vars nil
152 "Non-global vars that are let/lambda bound at the moment.
153 These won't be namespaced, as local takes priority over namespace.")
155 (defvar names--protection nil
156 "Leading chars used to identify protected symbols.
157 Don't customise this.
158 Instead use the :protection keyword when defining the
161 (defvar names--current-run nil
162 "Either 1 or 2, depending on which runthrough we're in.")
164 (defvar names--var-list
165 '(names--name names--regexp names--bound
167 names--package names--group-parent
168 names--macro names--current-run
169 names--fbound names--keywords
170 names--local-vars names--protection)
171 "List of variables the user shouldn't touch.")
174 (defvar names--inside-make-autoload nil
175 "Used in `make-autoload' to indicate we're making autoloads.")
177 (defvar names--package nil
178 "Package, name to be used by the :group and :version keywords.
179 Is derived from `load-file-name', unless the :package keyword is
180 passed to `define-namespace'.")
182 (defvar names--group-parent nil
183 "The name of the parent to be given to `defgroup'.
184 Is only non-nil if the :group keyword is passed to `define-namespace'.")
186 (defvar names--version nil
187 "The version number given by :version.
188 Used to define a constant and a command.")
190 (defvar names--functionlike-macros nil
191 "Function-like macros, even if their debug-spec says otherwise.
192 When expanding the namespace, these macros will be treated
193 exactly like functions. This means that their contents will be
194 namespaced like regular function arguments.
196 To add macros to this list, pass the :functionlike-macros keyword
197 to your namespace along with a list of macro names (as unquoted
201 (define-namespace foo-
202 :functionlike-macros (-> ->> thread-first thread-last)
206 (defconst names--keyword-list
209 (if (or (symbolp x) (listp x))
210 (setq names--group-parent x)
212 "Argument given to :group is not a symbol: %s" x)))
213 "Indicate `define-namespace' should make a `defgroup' for you.
214 The name of the group is the package name (see :package keyword).
215 This keyword should be given one argument, the name of the PARENT
216 group as an unquoted symbol.
218 Alternatively, the argument can be a list, in which case it is a
219 list of arguments to be passed to `defgroup' (essentially, a full
220 group definition without the leading `defgroup').
222 If this keyword is provided, besides including a defgroup, Names
223 will also include a :group keyword in every `defcustom' (and
224 similar forms) that don't already contain one.")
230 (setq names--version x)
232 "Argument given to :version is not a string: %s" x)))
233 "Indicate `define-namespace' should define the version number.
234 This keyword should be given one argument, a string describing
235 the package's version number.
237 With this, Names will generate a `defconst' and an interactive
238 `defun', each named `PACKAGE-NAME-version'. The function messages
239 and returns the version number. See the :package keyword.")
245 (setq names--package x)
247 "Argument given to :package is not a symbol: %s" x)))
248 "Set the name of this package to the given symbol.
249 This keyword should be given one argument, a symbol corresponding
250 to the name of this package.
252 If this keyword isn't used, the package name is taken as the the
253 file's basename, but only if its actually needed. This name is
254 needed by the :version and :group keywords.")
259 (let ((val (symbol-name x)))
260 (setq names--protection
261 (format "\\`%s" (regexp-quote val)))))
262 "Change the value of the `names--protection' variable.")
264 (:functionlike-macros
266 ,(lambda (x) (setq names--functionlike-macros
267 (append x names--functionlike-macros)))
268 "A list of values to be appended to `names--functionlike-macros'.")
272 "Indicates variables assigned in let-bind are NOT candidates for namespacing.")
276 "Cause a message to be called on each special form.")
280 "Accept namespaced names from outside current namespace definition.")
284 "Indicate symbols quoted with `quote' should be considered variable names.")
286 (:dont-assume-function-quote
288 "Indicate symbols quoted with `function' should NOT be considered function names.")
292 "Indicate only forms actually inside the namespace should be present in the output.
293 This is for internal use. It is used by `names-eval-defun' to
294 prevent `define-namespace' from adding things like `defgroup' or
295 `defconst's to the output."))
296 "List of keywords used by `define-namespace'.
297 Each element is a list containing
298 (KEYWORD N DEFINITION DOCUMENTATION)
301 - KEYWORD is the keyword's name, a symbol satifying `keywordp'.
302 - N is the number of arguments it takes, an integer.
303 - DEFINITION is a function (symbol or lambda) that takes N
304 arguments and does whatever you need for implementing the
306 - DOCUMENTATION is a string explaining the keyword's
309 (defmacro names--prepend (sbl)
310 "Return namespace+SBL."
311 (declare (debug (symbolp)))
312 `(intern (format "%s%s" names--name ,sbl)))
315 (defmacro names--filter-if-bound (var &optional pred)
316 "If VAR is bound and is a list, take the car of its elements which satify PRED."
317 (declare (debug (symbolp &optional function-form)))
318 `(when (boundp ',var)
321 (mapcar (lambda (x) (when (funcall (or ,pred #'identity) (or (car-safe x) x))
322 (or (car-safe x) x)))
325 (defmacro names--next-keyword (body)
326 "If car of BODY is a known keyword, `pop' it (and its arguments) from body.
327 Returns a list (KEYWORD . ARGUMENTLIST)."
328 (declare (debug sexp))
329 `(let ((kar (car-safe ,body))
333 (setq n (assoc kar names--keyword-list))
335 (dotimes (_ (1+ n) out)
336 (push (pop ,body) out))
339 (defvar names--has-reloaded nil
340 "Whether `names--reload-if-upgraded' has already been called in this run.")
343 ;;; ---------------------------------------------------------------
344 ;;; The Main Macro and Main Function.
346 (defmacro define-namespace (name &rest body)
347 "Inside the namespace NAME, execute BODY.
348 NAME can be any symbol (not quoted), but it's highly recommended
349 to use some form of separator (such as :, /, or -). For a
350 complete description of this macro, please visit the frontpage
351 with \\[names-view-manual].
353 In summary, this macro has two main effects:
355 1. Any definitions inside BODY will have NAME prepended to the
358 (define-namespace foo-
359 (defvar bar 1 \"docs\")
364 (defvar foo-bar 1 \"docs\")
367 2. Any function calls and variable names get NAME prepended to
368 them if such a variable or function exists. Ex:
370 (define-namespace foo:
371 (defun message (x y) nil)
372 (message \"%s\" my-var)
377 (defun foo:message (x y) nil)
378 (foo:message \"%s\" my-var)
380 Note how `message' is expanded to `foo:message' in the second
381 form, because that function exists. Meanwhile, `bar' is left
382 untouched because `foo:bar' is not a known variable name.
384 ===============================
388 In order for `define-namespace' to work with \";;;###autoload\"
389 comments must replace all instances of \";;;###autoload\" inside
390 your `define-namespace' with `:autoload'.
391 Afterwards, add an \";;;###autoload\" comment just above your
394 ===============================
398 Immediately after NAME you may add keywords which customize the
399 behaviour of `define-namespace'. For a list of possible keywords
400 and a description of their effects, see the variable
401 `names--keyword-list'.
403 \(fn NAME [KEYWORD ...] BODY)"
404 (declare (indent (lambda (&rest x) 0))
405 (debug (&define name [&rest keywordp &optional [&or symbolp (symbolp . symbolp)]] body)))
406 (let ((names--has-reloaded names--has-reloaded))
407 ;; This was to avoid an infinite recursion, but the bug turned out
408 ;; to be somewhere else. Still, I see no reason to erase this.
409 (unless names--has-reloaded
410 (setq names--has-reloaded t)
411 (names--reload-if-upgraded))
412 (names--error-if-using-vars)
413 (names--define-namespace-implementation name body)))
415 (defun names--define-namespace-implementation (name body)
416 "Namespace BODY using NAME.
417 See `define-namespace' for more information."
419 (let* ((names--name name)
421 (concat "\\`" (regexp-quote (symbol-name name))))
422 (names--current-run 0)
423 ;; Use the :protection keyword to change this.
424 (names--protection "\\`::")
426 (names--remove-namespace-from-list
427 (names--filter-if-bound byte-compile-bound-variables)
428 (names--filter-if-bound byte-compile-variables)))
430 (names--remove-namespace-from-list
431 (names--filter-if-bound byte-compile-macro-environment 'names--compat-macrop)
432 (names--filter-if-bound byte-compile-function-environment 'names--compat-macrop)))
434 (names--remove-namespace-from-list
435 (names--filter-if-bound byte-compile-macro-environment (lambda (x) (not (names--compat-macrop x))))
436 (names--filter-if-bound byte-compile-function-environment (lambda (x) (not (names--compat-macrop x))))))
437 (names--functionlike-macros names--functionlike-macros)
438 names--keywords names--local-vars key-and-args
439 names--version names--package names--group-parent)
441 (while (setq key-and-args (names--next-keyword body))
442 (names--handle-keyword key-and-args)
443 (push key-and-args names--keywords))
445 ;; First have to populate the bound and fbound lists. So we read
446 ;; the entire form (without evaluating it).
447 (mapc 'names-convert-form body)
448 (setq names--current-run (1+ names--current-run))
450 ;; Then we go back and actually namespace the entire form, which
451 ;; we'll later return so that it can be evaluated.
456 (when (and names--group-parent
457 (null (names--keyword :clean-output)))
458 (list (names--generate-defgroup)))
459 (when (and names--version
460 (null (names--keyword :clean-output)))
461 ;; `names--generate-version' returns a list.
462 (names--generate-version))
463 (mapcar 'names-convert-form
464 ;; Unless we're in `make-autoload', then just return autoloads.
465 (if names--inside-make-autoload
466 (names--extract-autoloads body)
469 ;; On emacs-version < 24.4, the byte-compiler cannot expand a
470 ;; macro if it is being called in the same top-level form as
471 ;; it was defined. That's a problem for us, since the entire
472 ;; namespace is a single top-level form (we return a `progn').
473 ;; The solution is for us to add the macros to
474 ;; `byte-compile-macro-environment' ourselves.
475 (if (and (boundp 'byte-compile-current-buffer)
476 byte-compile-current-buffer
477 (null names--inside-make-autoload)
478 (version< emacs-version "24.4"))
479 (let ((byte-compile-macro-environment
480 (when (boundp 'byte-compile-macro-environment)
481 byte-compile-macro-environment)))
482 (mapc #'names--add-macro-to-environment (cdr body))
483 (macroexpand-all body byte-compile-macro-environment))
486 ;; Exiting the `unwind-protect'.
487 (mapc (lambda (x) (set x nil)) names--var-list)))
489 (defun names--reload-if-upgraded ()
490 "Verify if there's a more recent version of Names in the `load-path'.
494 (let ((lp (expand-file-name (find-library-name "names")))
497 (not (string= lp names--load-file))
498 (file-readable-p lp))
500 (insert-file-contents-literally lp)
501 (goto-char (point-min))
504 (when (search-forward-regexp
505 "(defconst\\s-+names-version\\s-+\"\\([^\"]+\\)\"" nil t)
506 (match-string-no-properties 1))))
507 (when (and new-version (version< names-version new-version))
508 (eval-buffer nil lp)))))))
510 (defun names-convert-form (form)
511 "Do namespace conversion on FORM.
512 FORM is any legal elisp form.
513 Namespace name is defined by the global variable `names--name'.
515 See macro `namespace' for more information."
520 (let ((kar (car form))
523 ;; If symbol is protected, clean it.
525 (setq func (names--remove-protection kar)))
526 (names--message "Protected: %s" kar)
527 ;; And decide what to do with it.
528 (names--handle-args func (cdr form)))
530 ;; If kar is a list, either 1) it's a lambda form, 2) it's a
531 ;; macro we don't know about yet, 3) we have a bug.
533 (when (and (null (functionp kar))
534 (> names--current-run 1))
535 (names--warn "Ran into the following strange form.
536 Either it's an undefined macro, a macro with a bad debug declaration, or we have a bug.\n%s" form))
537 (mapcar 'names-convert-form form))
539 ;; Namespaced Functions/Macros
540 ((names--fboundp kar)
541 (names--message "Namespaced: %s" kar)
542 (names--args-of-function-or-macro
543 (names--prepend kar) (cdr form) (names--macrop kar)))
545 ;; General functions/macros/special-forms
546 (t (names--handle-args kar (cdr form))))))
549 (names--message "Symbol handling: %s" form)
550 ;; If symbol is protected, clean it and don't namespace it.
551 (or (names--remove-protection form)
552 ;; Otherwise, namespace if possible.
553 (if (names--boundp form)
554 (names--prepend form)
560 ;;; ---------------------------------------------------------------
561 ;;; Some auxiliary functions
562 (defun names-view-manual ()
563 "Call `browse-url' to view the manual of the Names package."
565 (browse-url "http://github.com/Bruce-Connor/names"))
567 (defun names--package-name ()
568 "Return the package name as a symbol.
569 Decide package name based on several factors. In order:
570 1. The :package keyword,
571 2. The namespace NAME, removing the final char."
573 (let ((package (symbol-name names--name)))
574 (prog1 (setq names--package
575 (intern (substring package 0 -1)))
576 (names--warn "No :package given. Guessing `%s'"
579 (defun names--generate-defgroup ()
580 "Return a `defgroup' form for the current namespace."
581 (if (listp names--group-parent)
582 (cons 'defgroup names--group-parent)
583 (list 'defgroup (names--package-name) nil
584 (format "Customization group for %s." (names--package-name))
585 :prefix (symbol-name names--name)
586 :group `',names--group-parent)))
588 (defun names--generate-version ()
589 "Return a `defun' and a `defconst' forms declaring the package version.
590 Also adds `version' to `names--fbound' and `names--bound'."
591 (add-to-list 'names--fbound 'version)
592 (add-to-list 'names--bound 'version)
594 (list 'defconst (names--prepend 'version)
596 (format "Version of the %s package." (names--package-name)))
597 (list 'defun (names--prepend 'version) nil
598 (format "Version of the %s package." (names--package-name))
601 ,(format "%s version: %s" (names--package-name) names--version))
604 (defun names--add-macro-to-environment (form)
605 "If FORM declares a macro, add it to `byte-compile-macro-environment'."
606 (let ((expansion form))
607 (while (names--compat-macrop (car-safe expansion))
609 (ignore-errors (macroexpand
610 expansion byte-compile-macro-environment))))
613 (or (and (memq (car-safe expansion) '(progn prog1 prog2))
614 (mapc #'names--add-macro-to-environment (cdr expansion)))
615 (and (eq 'defalias (car-safe expansion))
616 (let ((def (ignore-errors (eval (nth 2 expansion)))))
617 (and (names--compat-macrop def)
618 (push (cons (ignore-errors
619 (eval (nth 1 expansion)))
621 byte-compile-macro-environment))))))))
624 (eval-after-load 'find-func
625 '(defadvice find-function-search-for-symbol
626 (around names-around-find-function-search-for-symbol-advice
627 (symbol type library) activate)
628 "Make sure `find-function-search-for-symbol' understands namespaces."
631 (unless (cdr ad-return-value)
632 (with-current-buffer (car ad-return-value)
633 (search-forward-regexp "^(define-namespace\\_>")
634 (skip-chars-forward "\r\n[:blank:]")
635 (let* ((names--regexp
636 (concat "\\`" (regexp-quote
637 (symbol-name (read (current-buffer))))))
639 ;; We manually implement `names--remove-namespace'
640 ;; because it might not be loaded.
641 (let ((name (symbol-name symbol)))
642 (when (string-match names--regexp name)
643 (intern (replace-match "" nil nil name))))))
645 (ad-set-arg 0 short-symbol)
648 (defun names--extract-autoloads (body)
649 "Return a list of the forms in BODY preceded by :autoload."
651 (when (setq acons (memq :autoload body))
654 (names--extract-autoloads (cdr (cdr acons)))))))
657 (defadvice make-autoload (around names-before-make-autoload-advice
658 (form file &optional expansion) activate)
659 "Make sure `make-autoload' understands `define-namespace'.
660 Use the `names--inside-make-autoload' variable to indicate to
661 `define-namespace' that we're generating autoloads."
662 ;; We used to have a letbind here, but this was causing a void
663 ;; variable bug on Emacs 24.3.
665 (if (null (eq (car-safe form) 'define-namespace))
667 (setq names--inside-make-autoload t)
668 (setq form (macroexpand form))
669 (setq names--inside-make-autoload nil)
670 ;; Up to 24.2 `make-autoload' couldn't handle `progn's.
671 (if (version< emacs-version "24.3")
672 (setq ad-return-value
674 (mapcar (lambda (x) (names--make-autoload-compat x file))
676 (ad-set-arg 2 'expansion)
680 (defun names--make-autoload-compat (form file)
681 (if (eq (car-safe form) 'defalias)
683 (make-autoload form file)))
685 (defvar names--ignored-forms '(declare)
686 "The name of functions/macros/special-forms which we return without reading.")
688 (defun names--handle-args (func args)
689 "Generic handling for the form (FUNC . ARGS), without namespacing FUNC."
690 (if (memq func names--ignored-forms)
692 ;; TODO: Speed this up. Just change it to an alist or a hash-table.
693 (let ((handler (intern-soft (format "names--convert-%s" func))))
694 ;; Some function-like forms get special handling.
695 ;; That's anything with a names--convert-%s function defined.
696 (if (fboundp handler)
697 (progn (names--message "Special handling: %s" handler)
698 (funcall handler (cons func args)))
699 ;; If it isn't special, it's either a function or a macro.
700 (names--args-of-function-or-macro func args (names--compat-macrop func))))))
702 (defun names--message (f &rest rest)
703 "If :verbose is on, pass F and REST to `message'."
704 (when (names--keyword :verbose)
705 (apply #'message (concat "[names] " f) rest)))
707 (defun names--warn (f &rest rest)
708 "Pass F and REST to `message', unless byte-compiling or non-interactive."
709 (unless (and (null (names--keyword :verbose))
710 (and (boundp 'byte-compile-function-environment)
711 byte-compile-function-environment))
712 (apply #'message (concat "[names] " f) rest)))
714 (defun names--error-if-using-vars ()
715 "Remind the developer that variables are not customizable."
719 (error "[names] Global value of variable %s should be nil! %s"
720 x "Set it using keywords instead")))
723 (defun names--remove-namespace-from-list (&rest lists)
724 "Return a concatenated un-namespaced version of LISTS.
725 Symbols in LISTS that aren't namespaced are removed, symbols that
726 are namespaced become un-namespaced."
727 (delq nil (mapcar 'names--remove-namespace (apply #'append lists))))
729 (defun names--remove-namespace (symbol)
730 "Return SYMBOL with namespace removed, or nil if it wasn't namespaced."
731 (names--remove-regexp symbol names--regexp))
733 (defun names--remove-protection (symbol)
734 "Remove the leading :: from SYMBOL if possible, otherwise return nil."
735 (names--remove-regexp symbol names--protection))
737 (defun names--remove-regexp (s r)
738 "Return S with regexp R removed, or nil if S didn't match."
739 (let ((name (symbol-name s)))
740 (when (string-match r name)
741 (intern (replace-match "" nil nil name)))))
743 (defun names--quote-p (sbl)
744 "Is SBL a function which quotes its argument?"
745 (memq sbl '(quote function)))
747 (defun names--fboundp (sbl)
748 "Is namespace+SBL a fboundp symbol?"
749 (or (memq sbl names--fbound)
750 (memq sbl names--macro)
751 (and (names--keyword :global)
752 (fboundp (names--prepend sbl)))))
754 (defun names--macrop (sbl)
755 "Is namespace+SBL a fboundp symbol?"
756 (or (memq sbl names--macro)
757 (and (names--keyword :global)
758 (names--compat-macrop (names--prepend sbl)))))
760 (defun names--keyword (keyword)
761 "Was KEYWORD one of the keywords passed to the `namespace' macro?"
762 (assoc keyword names--keywords))
764 (defun names--boundp (sbl)
765 "Is namespace+SBL a boundp symbol?
766 If SBL has a let binding, that takes precendence so this also
768 (and (null (memq sbl names--local-vars))
769 (or (memq sbl names--bound)
770 (and (names--keyword :global)
771 (boundp (names--prepend sbl))))))
773 (defvar names--verbose nil
774 "If non-nil, verbose message are printed regardless of the :verbose keyword.
775 Use this to easily turn on verbosity during tests.")
777 (defun names--args-of-function-or-macro (function args macro)
778 "Namespace FUNCTION's arguments ARGS, with special treatment if MACRO is non-nil."
780 (let ((it (names--get-edebug-spec function))
781 (names--verbose (eq function 'push)))
782 (names--message "Edebug-spec of `%s' is %s" function it)
783 ;; Macros where we evaluate all arguments are like functions.
785 (memq function names--functionlike-macros))
786 (names--args-of-function-or-macro function args nil)
787 ;; Macros where nothing is evaluated we can just return.
790 ;; Other macros are complicated. Ask edebug for help.
791 (names--macro-args-using-edebug (cons function args)))))
792 ;; We just convert the arguments of functions.
793 (cons function (mapcar 'names-convert-form args))))
795 (defun names--get-edebug-spec (name)
796 "Get 'edebug-form-spec property of symbol NAME."
797 ;; Get the spec of symbol resolving all indirection.
801 (and (symbolp indirect)
804 indirect 'edebug-form-spec 'macro))))
805 ;; (edebug-trace "indirection: %s" edebug-form-spec)
806 (setq spec indirect))
809 (defvar names--is-inside-macro nil
810 "Auxiliary var used in `names--macro-args-using-edebug'.")
812 (defvar names--gensym-counter 0
813 "Counter used to uniquify symbols generated `names--gensym'.")
815 (defun names--macro-args-using-edebug (form)
816 "Namespace the arguments of macro FORM by hacking into edebug.
817 This takes advantage of the fact that macros (should) declare a
818 `debug' specification which tells us which arguments are actually
821 Ideally, we would read this specification ourselves and see how
822 it matches (cdr FORM), but that would take a lot of work and
823 we'd be reimplementing something that edebug already does
824 phenomenally. So we hack into edebug instead."
828 ((max-lisp-eval-depth 3000)
831 (names--is-inside-macro form)
832 ;; Prevent excessive messaging.
833 ;; TODO: Don't do this if `message' is advised.
834 ((symbol-function 'message) #'names--edebug-message)
835 ;; Older edebugs have poor `get-edebug-spec'.
836 ((symbol-function 'get-edebug-spec) #'names--get-edebug-spec)
837 ;; Give symbols our own name.
838 ((symbol-function 'cl-gensym) #'names--gensym)
839 ;; Stop at one level deep.
840 ((symbol-function 'edebug-form) #'names--edebug-form)
841 ;; Don't actually wrap anything.
842 ((symbol-function 'edebug-make-enter-wrapper)
843 #'names--edebug-make-enter-wrapper))
847 (goto-char (point-min))
849 (edebug-read-top-level-form))
852 "Couldn't namespace this macro using its (debug ...) declaration: %s"
856 (when (equal (car-safe (cdr-safe er))
857 "Lisp nesting exceeds `max-lisp-eval-depth'")
859 "Lisp nesting exceeded `max-lisp-eval-depth' at the following form: %s"
863 (defvar names--message-backup
864 (if (ad-is-advised 'message)
865 (ad-get-orig-definition 'message)
866 (symbol-function 'message))
867 "Where names stores `message's definition while overriding it.")
869 (defun names--edebug-message (&rest args)
870 (if (or (names--keyword :verbose) names--verbose)
871 (apply names--message-backup args)
872 (when args (apply #'format args))))
874 (defun names--edebug-make-enter-wrapper (forms)
875 (setq edebug-def-name
878 (names--gensym "edebug-anon")))
881 (defun names--gensym (prefix)
882 "Generate a new uninterned symbol.
883 The name is made by appending a number to PREFIX and preppending \"names\", default \"G\"."
884 (let ((num (prog1 names--gensym-counter
885 (setq names--gensym-counter
886 (1+ names--gensym-counter)))))
887 (make-symbol (format "names-%s%d" (if (stringp prefix) prefix "G") num))))
889 (defun names--edebug-form (cursor)
890 "Parse form given by CURSOR using edebug, and namespace it if necessary."
892 ;; Return the instrumented form for the following form.
893 ;; Add the point offsets to the edebug-offset-list for the form.
894 (let* ((form (edebug-top-element-required cursor "Expected form"))
895 (offset (edebug-top-offset cursor))
896 ;; We don't want to convert the entire form that was passed
897 ;; to `names--macro-args-using-edebug', since the head of
898 ;; that was already converted and it would lead to an
900 ;; So we check for (equal names--is-inside-macro form)
901 ;; Simply incrementing a depth counter didn't work, for a
902 ;; reason I can no longer remember.
904 ;; We DO want to convert the arguments that edebug identifies
905 ;; as forms (level-1). And we do that ourselves, don't pass
907 (func (if (or (eq names--is-inside-macro t)
908 (equal names--is-inside-macro form))
909 'identity 'names-convert-form))
910 (names--is-inside-macro
911 (if (eq func 'names-convert-form)
912 t names--is-inside-macro)))
913 (names--message " [Edebug] Ran into this: %S" form)
914 (names--message " Cursor: %S" cursor)
917 ((consp form) ;; The first offset for a list form is for the list form itself.
918 (if (eq func 'names-convert-form)
919 (names-convert-form form)
920 (let* ((head (car form))
921 (spec (and (symbolp head) (get-edebug-spec head)))
922 (new-cursor (edebug-new-cursor form offset)))
923 ;; Find out if this is a defining form from first symbol.
924 ;; An indirect spec would not work here, yet.
925 (if (and (consp spec) (eq '&define (car spec)))
926 (edebug-defining-form
928 (car offset) ;; before the form
929 (edebug-after-offset cursor)
930 (cons (symbol-name head) (cdr spec)))
931 ;; Wrap a regular form.
932 (edebug-list-form new-cursor)))))
937 ;; Anything else is self-evaluating.
939 (edebug-move-cursor cursor))))
941 (defun names--maybe-append-group (form)
942 "Append (:group `names--package') to FORM.
943 Only if the :group keyword was passed to `define-namespace' and
944 if the form doesn't already have a :group."
945 (if (or (null names--group-parent) (memq :group form))
947 (append form `(:group ',(names--package-name)))))
950 ;;; ---------------------------------------------------------------
951 ;;; Interpreting keywords passed to the main macro.
952 (defun names--handle-keyword (body)
953 "Call the function that handles the keyword at the car of BODY.
954 Such function must be listed in `names--keyword-list'. If it is
955 nil, this function just returns.
957 Regardless of whether a function was called, the keyword is added
958 to the variable `names--keywords'.
960 The car of BODY is the keyword itself and the other elements are
961 the keyword arguments, if any."
962 (let ((func (nth 2 (assoc (car body) names--keyword-list))))
964 (apply func (cdr body))
968 ;;; ---------------------------------------------------------------
969 ;;; Interpreting the actual forms found in BODY of the main macro.
971 ;; This is where the heavy work is done.
973 ;; If you'd like to implement support for some special form, simply
974 ;; define a function called `names--convert-FORM-NAME' along the
975 ;; lines of the functions defined below. It will be automatically used
976 ;; whenever that form is found.
978 ;; Defun, defmacro, and defsubst macros are pretty predictable.
979 (defun names--convert-defmacro (form)
980 "Special treatment for `defmacro' FORM."
981 (let* ((name (cadr form))
982 (spaced-name (names--prepend name))
984 (add-to-list 'names--macro name)
985 (add-to-list 'names--fbound name)
986 ;; Set the macros debug spec if possible. It will be relevant on
988 (when (setq decl (ignore-errors (cond
989 ((eq (car-safe (nth 3 form)) 'declare)
991 ((and (stringp (nth 3 form))
992 (eq (car-safe (nth 4 form)) 'declare))
995 (setq decl (car (cdr-safe (assoc 'debug (cdr decl)))))
996 (when decl (put spaced-name 'edebug-form-spec decl)))
997 ;; Then convert the macro as a defalias.
1000 (names--convert-lambda
1001 (cons spaced-name (cddr form))))))
1002 (defalias 'names--convert-defmacro* 'names--convert-defmacro)
1004 (defun names--convert-defvaralias (form)
1005 "Special treatment for `defvaralias' FORM."
1006 (let ((form (cons (car form)
1007 (mapcar #'names-convert-form (cdr form))))
1009 (setq name (names--remove-namespace
1010 (ignore-errors (eval (cadr form)))))
1012 (add-to-list 'names--bound name))
1015 (defun names--convert-defalias (form)
1016 "Special treatment for `defalias' FORM."
1017 (let ((form (cons (car form)
1018 (mapcar #'names-convert-form (cdr form))))
1020 (setq name (names--remove-namespace
1021 (ignore-errors (eval (cadr form)))))
1023 (add-to-list 'names--fbound name))
1026 (defun names--convert-defvar (form &optional dont-add)
1027 "Special treatment for `defvar' FORM.
1028 If DONT-ADD is nil, the FORM's `cadr' is added to `names--bound'."
1029 (let ((name (cadr form)))
1031 (add-to-list 'names--bound name))
1035 (names--prepend name))
1036 (mapcar 'names-convert-form (cdr (cdr form))))))
1038 (defalias 'names--convert-defconst 'names--convert-defvar
1039 "Special treatment for `defconst' FORM.")
1041 (defun names--convert-defcustom (form)
1042 "Special treatment for `defcustom' FORM."
1043 (names--maybe-append-group
1044 (names--convert-defvar form)))
1046 (defun names--convert-custom-declare-variable (form)
1047 "Special treatment for `custom-declare-variable' FORM."
1048 (let ((name (eval (cadr form))) ;;ignore-errors
1049 (val (car (cddr form))))
1050 (add-to-list 'names--bound name)
1054 (list 'quote (names--prepend name)) ;cadr
1055 ;; The DEFAULT argument is explicitly evaluated by
1056 ;; `custom-declare-variable', so it should be safe to namespace
1057 ;; even when quoted. Plus, we need to do this because
1058 ;; defcustom quotes this part.
1059 (if (names--quote-p (car-safe val))
1060 (list (car val) (names-convert-form (cadr val)))
1061 (names-convert-form val))
1062 (names-convert-form (car (cdr (cdr (cdr form))))))
1063 (mapcar 'names-convert-form (cdr (cdr (cdr (cdr form))))))))
1065 (defun names--convert-defface (form)
1066 "Special treatment for `defface' FORM.
1067 Identical to defvar, just doesn't add the symbol to the boundp
1068 list. And maybe use a :group."
1069 (names--maybe-append-group
1070 (names--convert-defvar form :dont-add)))
1072 (defun names--convert-define-derived-mode (form)
1073 "Special treatment for `define-derived-mode' FORM."
1074 (let ((name (cadr form)))
1075 (add-to-list 'names--fbound name)
1076 (add-to-list 'names--bound name)
1077 (add-to-list 'names--bound
1078 (intern (format "%s-map" name)))
1079 (add-to-list 'names--bound
1080 (intern (format "%s-hook" name)))
1082 (names--maybe-append-group
1083 ;; And here we namespace it.
1086 (names--prepend name)
1088 (names-convert-form (nth 3 form))
1089 (names-convert-form (nth 4 form))))
1090 (mapcar #'names-convert-form (cddr (cl-cdddr form))))))
1092 (defun names--convert-define-minor-mode (form)
1093 "Special treatment for `define-minor-mode' FORM."
1094 (let ((name (cadr form))
1095 (keymap (nth 5 form)))
1096 ;; 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 ;; Register the keymap
1101 (if (or (null keymap) (null (symbolp keymap)))
1102 (add-to-list 'names--bound (intern (format "%s-map" name)))
1103 (when (setq keymap (names--remove-namespace keymap))
1104 (add-to-list 'names--bound keymap)))
1106 (names--maybe-append-group
1107 ;; And here we namespace it.
1110 (names--prepend name)
1112 (names-convert-form (nth 3 form))
1113 (names-convert-form (nth 4 form))
1114 (names-convert-form (nth 5 form))
1115 (names-convert-form (nth 6 form))))
1116 (mapcar #'names-convert-form (cddr form)))))
1118 (defun names--convert-define-globalized-minor-mode (form)
1119 "Special treatment for `define-globalized-minor-mode' FORM.
1120 The NAME of the global mode will NOT be namespaced, despite being
1121 a definition. It is kept verbatim.
1122 This is because people tend to name their global modes as
1123 `global-foo-mode', and namespacing would make this impossible.
1125 The MODE and TURN-ON arguments are converted as function names.
1126 Everything else is converted as regular forms (which usually
1127 means no conversion will happen since it's usually keywords and
1129 (let ((name (names--remove-namespace (cadr form)))
1130 (copy (cl-copy-list form)))
1131 ;; Register the mode name
1133 (add-to-list 'names--fbound name)
1134 (add-to-list 'names--bound name)
1135 (add-to-list 'names--bound (intern (format "%s-hook" name))))
1136 (names--maybe-append-group
1137 ;; And here we namespace it.
1142 (names--handle-symbol-as-function (pop copy))
1143 (names--handle-symbol-as-function (pop copy)))
1144 (mapcar #'names-convert-form copy)))))
1145 (defalias 'names--convert-define-global-minor-mode
1146 #'names--convert-define-globalized-minor-mode)
1147 (defalias 'names--convert-easy-mmode-define-global-mode
1148 #'names--convert-define-globalized-minor-mode)
1150 (defun names--convert-quote (form)
1151 "Special treatment for `quote' FORM.
1152 When FORM is (quote argument), argument too arbitrary to be
1153 logically namespaced and is never parsed for namespacing
1154 (but see :assume-var-quote in `names--keyword-list').
1156 When FORM is (function form), a symbol is namespaced as a
1157 function name, a list is namespaced as a lambda form."
1158 (let ((kadr (cadr form))
1159 (this-name (car form)))
1160 (if (and (eq this-name 'function)
1162 (list this-name (names-convert-form kadr))
1165 ;; A symbol inside a function quote should be a function,
1166 ;; unless the user disabled that.
1167 ((and (eq this-name 'function)
1168 (null (names--keyword :dont-assume-function-quote)))
1170 (names--handle-symbol-as-function kadr)))
1172 ;; A symbol inside a regular quote should be a function, if
1173 ;; the user asked for that.
1174 ((and (eq this-name 'quote)
1175 (names--keyword :assume-var-quote))
1177 (or (names--remove-protection kadr)
1178 (if (names--boundp kadr)
1179 (names--prepend kadr)
1185 (defun names--handle-symbol-as-function (s)
1186 "Namespace symbol S as a function name."
1187 (or (names--remove-protection s)
1188 (if (names--fboundp s) (names--prepend s) s)))
1190 (defalias 'names--convert-function 'names--convert-quote)
1192 (defun names--convert-macro (form)
1193 "Special treatment for `macro' form.
1194 Return (macro . (names-convert-form (cdr FORM)))."
1195 (cons 'macro (names-convert-form (cdr form))))
1197 (defun names--convert-lambda (form)
1198 "Special treatment for `lambda' FORM."
1199 (let ((names--local-vars
1200 (append (names--vars-from-arglist (cadr form))
1202 (forms (cdr (cdr form))))
1206 (when (stringp (car forms))
1209 (setq forms (cdr forms))))
1210 (when (eq 'interactive (car-safe (car forms)))
1212 (list (list (car (car forms))
1213 (names-convert-form (cadr (car forms)))))
1214 (setq forms (cdr forms))))
1216 ;; (message "%S" forms)
1217 (mapcar 'names-convert-form forms)))))
1219 (defun names--convert-clojure (form)
1220 "Special treatment for `clojure' FORM."
1221 (names--warn "Found a `closure'! You should use `lambda's instead")
1222 (let ((names--local-vars
1223 (append (names--vars-from-arglist (cadr form))
1224 names--local-vars)))
1227 (names--convert-lambda (cdr form)))))
1229 (defun names--vars-from-arglist (args)
1230 "Get a list of local variables from a generalized arglist ARGS."
1235 (let ((symb (or (cdr-safe (car-safe x)) (car-safe x) x)))
1236 (when (and (symbolp symb)
1237 (null (string-match "^&" (symbol-name symb)))
1242 (defun names--convert-defun (form)
1243 "Special treatment for `defun' FORM."
1244 (let* ((name (cadr form)))
1245 (add-to-list 'names--fbound name)
1247 (names--convert-lambda
1248 (cons (names--prepend name) (cddr form))))))
1249 (defalias 'names--convert-defun* 'names--convert-defun)
1250 (defalias 'names--convert-defsubst 'names--convert-defun)
1251 (defalias 'names--convert-defsubst* 'names--convert-defun)
1253 (defun names--let-var-convert-then-add (sym add)
1254 "Try to convert SYM unless :no-let-vars is in use.
1255 If ADD is non-nil, add resulting symbol to `names--local-vars'."
1256 (let ((name (if (null (names--keyword :no-let-vars))
1257 (names-convert-form sym)
1259 (when add (add-to-list 'names--local-vars name))
1262 (defun names--convert-let (form &optional star)
1263 "Special treatment for `let' FORM.
1264 If STAR is non-nil, parse as a `let*'."
1265 (let* ((names--local-vars names--local-vars)
1270 (list (names--let-var-convert-then-add (car x) star)
1271 (names-convert-form (cadr x)))
1272 (names--let-var-convert-then-add x star)))
1274 ;; Each var defined in a regular `let' only becomes protected after
1275 ;; all others have been defined.
1277 (setq names--local-vars
1279 (mapcar (lambda (x) (or (car-safe x) x)) vars)
1280 names--local-vars)))
1282 (list (car form) vars)
1283 (mapcar 'names-convert-form (cddr form)))))
1285 (defun names--convert-let* (form)
1286 "Special treatment for `let' FORM."
1287 (names--convert-let form t))
1289 (defun names--convert-cond (form)
1290 "Special treatment for `cond' FORM."
1294 (lambda (x) (mapcar #'names-convert-form x))
1297 (defun names--convert-condition-case (form)
1298 "Special treatment for `condition-case' FORM."
1303 (names-convert-form (cadr (cdr form))))
1307 (mapcar 'names-convert-form (cdr x))))
1308 (cddr (cdr form)))))
1311 ;;; names.el ends here