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 (or (ignore-errors (indirect-function object t))
86 (ignore-errors (indirect-function object)))))
88 (or (eq 'macro (car def))
89 (and (names--autoloadp def) (memq (nth 4 def) '(macro t))))))))
91 (if (fboundp 'autoloadp)
92 (defalias 'names--autoloadp #'autoloadp)
93 (defsubst names--autoloadp (object)
94 "Non-nil if OBJECT is an autoload."
95 (eq 'autoload (car-safe object))))
97 (unless (get-edebug-spec 'cl-defun)
98 (def-edebug-spec cl-defun defun*))
99 (unless (get-edebug-spec 'cl-defmacro)
100 (def-edebug-spec cl-defmacro defmacro*))
101 (unless (get-edebug-spec 'setq-local)
102 (def-edebug-spec setq-local setq))
103 (unless (get-edebug-spec 'loop)
104 (def-edebug-spec loop
106 ;; These are usually followed by a symbol, but it can
107 ;; actually be any destructuring-bind pattern, which
108 ;; would erroneously match `form'.
109 [[&or "for" "as" "with" "and"] sexp]
110 ;; These are followed by expressions which could
111 ;; erroneously match `symbolp'.
112 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
113 "above" "below" "by" "in" "on" "=" "across"
114 "repeat" "while" "until" "always" "never"
115 "thereis" "collect" "append" "nconc" "sum"
116 "count" "maximize" "minimize" "if" "unless"
118 ;; Simple default, which covers 99% of the cases.
122 ;;; ---------------------------------------------------------------
124 (defconst names-version "20150617.0" "Version of the names.el package.")
126 (defvar names--name nil
127 "Name of the current namespace inside the `define-namespace' macro.")
128 (defvar names--regexp nil "Regexp matching `names--name'.")
130 (defvar names--load-file (and load-file-name (expand-file-name load-file-name))
131 "The file where the current version of Names was loaded.
132 This is used by `names--check-for-update' to check if a new
133 version has been installed.")
135 (defvar names--bound nil
136 "List of variables defined in this namespace.")
137 (defvar names--fbound nil
138 "List of functions defined in this namespace.")
139 (defvar names--macro nil
140 "List of macros defined in this namespace.")
142 (defvar names--keywords nil
143 "Keywords that were passed to the current namespace.
144 See `names--keyword-list' for a list and description of possible
147 (defvar names--local-vars nil
148 "Non-global vars that are let/lambda bound at the moment.
149 These won't be namespaced, as local takes priority over namespace.")
151 (defvar names--protection nil
152 "Leading chars used to identify protected symbols.
153 Don't customise this.
154 Instead use the :protection keyword when defining the
157 (defvar names--current-run nil
158 "Either 1 or 2, depending on which runthrough we're in.")
160 (defvar names--var-list
161 '(names--name names--regexp names--bound
163 names--package names--group-parent
164 names--macro names--current-run
165 names--fbound names--keywords
166 names--local-vars names--protection)
167 "List of variables the user shouldn't touch.")
170 (defvar names--inside-make-autoload nil
171 "Used in `make-autoload' to indicate we're making autoloads.")
173 (defvar names--package nil
174 "Package, name to be used by the :group and :version keywords.
175 Is derived from `load-file-name', unless the :package keyword is
176 passed to `define-namespace'.")
178 (defvar names--group-parent nil
179 "The name of the parent to be given to `defgroup'.
180 Is only non-nil if the :group keyword is passed to `define-namespace'.")
182 (defvar names--version nil
183 "The version number given by :version.
184 Used to define a constant and a command.")
186 (defvar names--functionlike-macros nil
187 "Function-like macros, even if their debug-spec says otherwise.
188 When expanding the namespace, these macros will be treated
189 exactly like functions. This means that their contents will be
190 namespaced like regular function arguments.
192 To add macros to this list, pass the :functionlike-macros keyword
193 to your namespace along with a list of macro names (as unquoted
197 (define-namespace foo-
198 :functionlike-macros (-> ->> thread-first thread-last)
202 (defconst names--keyword-list
205 (if (or (symbolp x) (listp x))
206 (setq names--group-parent x)
208 "Argument given to :group is not a symbol: %s" x)))
209 "Indicate `define-namespace' should make a `defgroup' for you.
210 The name of the group is the package name (see :package keyword).
211 This keyword should be given one argument, the name of the PARENT
212 group as an unquoted symbol.
214 Alternatively, the argument can be a list, in which case it is a
215 list of arguments to be passed to `defgroup' (essentially, a full
216 group definition without the leading `defgroup').
218 If this keyword is provided, besides including a defgroup, Names
219 will also include a :group keyword in every `defcustom' (and
220 similar forms) that don't already contain one.")
226 (setq names--version x)
228 "Argument given to :version is not a string: %s" x)))
229 "Indicate `define-namespace' should define the version number.
230 This keyword should be given one argument, a string describing
231 the package's version number.
233 With this, Names will generate a `defconst' and an interactive
234 `defun', each named `PACKAGE-NAME-version'. The function messages
235 and returns the version number. See the :package keyword.")
241 (setq names--package x)
243 "Argument given to :package is not a symbol: %s" x)))
244 "Set the name of this package to the given symbol.
245 This keyword should be given one argument, a symbol corresponding
246 to the name of this package.
248 If this keyword isn't used, the package name is taken as the the
249 file's basename, but only if its actually needed. This name is
250 needed by the :version and :group keywords.")
255 (let ((val (symbol-name x)))
256 (setq names--protection
257 (format "\\`%s" (regexp-quote val)))))
258 "Change the value of the `names--protection' variable.")
260 (:functionlike-macros
262 ,(lambda (x) (setq names--functionlike-macros
263 (append x names--functionlike-macros)))
264 "A list of values to be appended to `names--functionlike-macros'.")
268 "Indicates variables assigned in let-bind are NOT candidates for namespacing.")
272 "Cause a message to be called on each special form.")
276 "Accept namespaced names from outside current namespace definition.")
280 "Indicate symbols quoted with `quote' should be considered variable names.")
282 (:dont-assume-function-quote
284 "Indicate symbols quoted with `function' should NOT be considered function names.")
288 "Indicate only forms actually inside the namespace should be present in the output.
289 This is for internal use. It is used by `names-eval-defun' to
290 prevent `define-namespace' from adding things like `defgroup' or
291 `defconst's to the output."))
292 "List of keywords used by `define-namespace'.
293 Each element is a list containing
294 (KEYWORD N DEFINITION DOCUMENTATION)
297 - KEYWORD is the keyword's name, a symbol satifying `keywordp'.
298 - N is the number of arguments it takes, an integer.
299 - DEFINITION is a function (symbol or lambda) that takes N
300 arguments and does whatever you need for implementing the
302 - DOCUMENTATION is a string explaining the keyword's
305 (defmacro names--prepend (sbl)
306 "Return namespace+SBL."
307 (declare (debug (symbolp)))
308 `(intern (format "%s%s" names--name ,sbl)))
311 (defmacro names--filter-if-bound (var &optional pred)
312 "If VAR is bound and is a list, take the car of its elements which satify PRED."
313 (declare (debug (symbolp &optional function-form)))
314 `(when (boundp ',var)
317 (mapcar (lambda (x) (when (funcall (or ,pred 'identity) (or (car-safe x) x))
318 (or (car-safe x) x)))
321 (defmacro names--next-keyword (body)
322 "If car of BODY is a known keyword, `pop' it (and its arguments) from body.
323 Returns a list (KEYWORD . ARGUMENTLIST)."
324 (declare (debug sexp))
325 `(let ((kar (car-safe ,body))
329 (setq n (assoc kar names--keyword-list))
331 (dotimes (it (1+ n) out)
332 (push (pop ,body) out))
335 (defvar names--has-reloaded nil
336 "Whether `names--reload-if-upgraded' has already been called in this run.")
339 ;;; ---------------------------------------------------------------
340 ;;; The Main Macro and Main Function.
342 (defmacro define-namespace (name &rest body)
343 "Inside the namespace NAME, execute BODY.
344 NAME can be any symbol (not quoted), but it's highly recommended
345 to use some form of separator (such as :, /, or -). For a
346 complete description of this macro, please visit the frontpage
347 with \\[names-view-manual].
349 In summary, this macro has two main effects:
351 1. Any definitions inside BODY will have NAME prepended to the
354 (define-namespace foo-
355 (defvar bar 1 \"docs\")
360 (defvar foo-bar 1 \"docs\")
363 2. Any function calls and variable names get NAME prepended to
364 them if such a variable or function exists. Ex:
366 (define-namespace foo:
367 (defun message (x y) nil)
368 (message \"%s\" my-var)
373 (defun foo:message (x y) nil)
374 (foo:message \"%s\" my-var)
376 Note how `message' is expanded to `foo:message' in the second
377 form, because that function exists. Meanwhile, `bar' is left
378 untouched because `foo:bar' is not a known variable name.
380 ===============================
384 In order for `define-namespace' to work with \";;;###autoload\"
385 comments must replace all instances of \";;;###autoload\" inside
386 your `define-namespace' with `:autoload'.
387 Afterwards, add an \";;;###autoload\" comment just above your
390 ===============================
394 Immediately after NAME you may add keywords which customize the
395 behaviour of `define-namespace'. For a list of possible keywords
396 and a description of their effects, see the variable
397 `names--keyword-list'.
399 \(fn NAME [KEYWORD ...] BODY)"
400 (declare (indent (lambda (&rest x) 0))
401 (debug (&define name [&rest keywordp &optional [&or symbolp (symbolp . symbolp)]] body)))
402 (let ((names--has-reloaded names--has-reloaded))
403 ;; This was to avoid an infinite recursion, but the bug turned out
404 ;; to be somewhere else. Still, I see no reason to erase this.
405 (unless names--has-reloaded
406 (setq names--has-reloaded t)
407 (names--reload-if-upgraded))
408 (names--error-if-using-vars)
409 (names--define-namespace-implementation name body)))
411 (defun names--define-namespace-implementation (name body)
412 "Namespace BODY using NAME.
413 See `define-namespace' for more information."
415 (let* ((names--name name)
417 (concat "\\`" (regexp-quote (symbol-name name))))
418 (names--current-run 0)
419 ;; Use the :protection keyword to change this.
420 (names--protection "\\`::")
422 (names--remove-namespace-from-list
423 (names--filter-if-bound byte-compile-bound-variables)
424 (names--filter-if-bound byte-compile-variables)))
426 (names--remove-namespace-from-list
427 (names--filter-if-bound byte-compile-macro-environment 'names--compat-macrop)
428 (names--filter-if-bound byte-compile-function-environment 'names--compat-macrop)))
430 (names--remove-namespace-from-list
431 (names--filter-if-bound byte-compile-macro-environment (lambda (x) (not (names--compat-macrop x))))
432 (names--filter-if-bound byte-compile-function-environment (lambda (x) (not (names--compat-macrop x))))))
433 (names--functionlike-macros names--functionlike-macros)
434 names--keywords names--local-vars key-and-args
435 names--version names--package names--group-parent)
437 (while (setq key-and-args (names--next-keyword body))
438 (names--handle-keyword key-and-args)
439 (push key-and-args names--keywords))
441 ;; First have to populate the bound and fbound lists. So we read
442 ;; the entire form (without evaluating it).
443 (mapc 'names-convert-form body)
444 (setq names--current-run (1+ names--current-run))
446 ;; Then we go back and actually namespace the entire form, which
447 ;; we'll later return so that it can be evaluated.
452 (when (and names--group-parent
453 (null (names--keyword :clean-output)))
454 (list (names--generate-defgroup)))
455 (when (and names--version
456 (null (names--keyword :clean-output)))
457 ;; `names--generate-version' returns a list.
458 (names--generate-version))
459 (mapcar 'names-convert-form
460 ;; Unless we're in `make-autoload', then just return autoloads.
461 (if names--inside-make-autoload
462 (names--extract-autoloads body)
465 ;; On emacs-version < 24.4, the byte-compiler cannot expand a
466 ;; macro if it is being called in the same top-level form as
467 ;; it was defined. That's a problem for us, since the entire
468 ;; namespace is a single top-level form (we return a `progn').
469 ;; The solution is for us to add the macros to
470 ;; `byte-compile-macro-environment' ourselves.
471 (if (and (boundp 'byte-compile-current-buffer)
472 byte-compile-current-buffer
473 (null names--inside-make-autoload)
474 (version< emacs-version "24.4"))
475 (let ((byte-compile-macro-environment
476 (when (boundp 'byte-compile-macro-environment)
477 byte-compile-macro-environment)))
478 (mapc #'names--add-macro-to-environment (cdr body))
479 (macroexpand-all body byte-compile-macro-environment))
482 ;; Exiting the `unwind-protect'.
483 (mapc (lambda (x) (set x nil)) names--var-list)))
485 (defun names--reload-if-upgraded ()
486 "Verify if there's a more recent version of Names in the `load-path'.
490 (let ((lp (expand-file-name (find-library-name "names")))
493 (not (string= lp names--load-file))
494 (file-readable-p lp))
496 (insert-file-contents-literally lp)
497 (goto-char (point-min))
500 (when (search-forward-regexp
501 "(defconst\\s-+names-version\\s-+\"\\([^\"]+\\)\"" nil t)
502 (match-string-no-properties 1))))
503 (when (and new-version (version< names-version new-version))
504 (eval-buffer nil lp)))))))
506 (defun names-convert-form (form)
507 "Do namespace conversion on FORM.
508 FORM is any legal elisp form.
509 Namespace name is defined by the global variable `names--name'.
511 See macro `namespace' for more information."
516 (let ((kar (car form))
519 ;; If symbol is protected, clean it.
521 (setq func (names--remove-protection kar)))
522 (names--message "Protected: %s" kar)
523 ;; And decide what to do with it.
524 (names--handle-args func (cdr form)))
526 ;; If kar is a list, either 1) it's a lambda form, 2) it's a
527 ;; macro we don't know about yet, 3) we have a bug.
529 (when (and (null (functionp kar))
530 (> names--current-run 1))
531 (names--warn "Ran into the following strange form.
532 Either it's an undefined macro, a macro with a bad debug declaration, or we have a bug.\n%s" form))
533 (mapcar 'names-convert-form form))
535 ;; Namespaced Functions/Macros
536 ((names--fboundp kar)
537 (names--message "Namespaced: %s" kar)
538 (names--args-of-function-or-macro
539 (names--prepend kar) (cdr form) (names--macrop kar)))
541 ;; General functions/macros/special-forms
542 (t (names--handle-args kar (cdr form))))))
545 (names--message "Symbol handling: %s" form)
546 ;; If symbol is protected, clean it and don't namespace it.
547 (or (names--remove-protection form)
548 ;; Otherwise, namespace if possible.
549 (if (names--boundp form)
550 (names--prepend form)
556 ;;; ---------------------------------------------------------------
557 ;;; Some auxiliary functions
558 (defun names-view-manual ()
559 "Call `browse-url' to view the manual of the Names package."
561 (browse-url "http://github.com/Bruce-Connor/names"))
563 (defun names--package-name ()
564 "Return the package name as a symbol.
565 Decide package name based on several factors. In order:
566 1. The :package keyword,
567 2. The namespace NAME, removing the final char."
569 (let ((package (symbol-name names--name)))
570 (prog1 (setq names--package
571 (intern (substring package 0 -1)))
572 (names--warn "No :package given. Guessing `%s'"
575 (defun names--generate-defgroup ()
576 "Return a `defgroup' form for the current namespace."
577 (if (listp names--group-parent)
578 (cons 'defgroup names--group-parent)
579 (list 'defgroup (names--package-name) nil
580 (format "Customization group for %s." (names--package-name))
581 :prefix (symbol-name names--name)
582 :group `',names--group-parent)))
584 (defun names--generate-version ()
585 "Return a `defun' and a `defconst' forms declaring the package version.
586 Also adds `version' to `names--fbound' and `names--bound'."
587 (add-to-list 'names--fbound 'version)
588 (add-to-list 'names--bound 'version)
590 (list 'defconst (names--prepend 'version)
592 (format "Version of the %s package." (names--package-name)))
593 (list 'defun (names--prepend 'version) nil
594 (format "Version of the %s package." (names--package-name))
597 ,(format "%s version: %s" (names--package-name) names--version))
600 (defun names--add-macro-to-environment (form)
601 "If FORM declares a macro, add it to `byte-compile-macro-environment'."
602 (let ((expansion form))
603 (while (names--compat-macrop (car-safe expansion))
605 (ignore-errors (macroexpand
606 expansion byte-compile-macro-environment))))
609 (or (and (memq (car-safe expansion) '(progn prog1 prog2))
610 (mapc #'names--add-macro-to-environment (cdr expansion)))
611 (and (eq 'defalias (car-safe expansion))
612 (let ((def (ignore-errors (eval (nth 2 expansion)))))
613 (and (names--compat-macrop def)
614 (push (cons (ignore-errors
615 (eval (nth 1 expansion)))
617 byte-compile-macro-environment))))))))
620 (eval-after-load 'find-func
621 '(defadvice find-function-search-for-symbol
622 (around names-around-find-function-search-for-symbol-advice
623 (symbol type library) activate)
624 "Make sure `find-function-search-for-symbol' understands namespaces."
627 (unless (cdr ad-return-value)
628 (with-current-buffer (car ad-return-value)
629 (search-forward-regexp "^(define-namespace\\_>")
630 (skip-chars-forward "\r\n[:blank:]")
631 (let* ((names--regexp
632 (concat "\\`" (regexp-quote
633 (symbol-name (read (current-buffer))))))
635 ;; We manually implement `names--remove-namespace'
636 ;; because it might not be loaded.
637 (let ((name (symbol-name symbol)))
638 (when (string-match names--regexp name)
639 (intern (replace-match "" nil nil name))))))
641 (ad-set-arg 0 short-symbol)
644 (defun names--extract-autoloads (body)
645 "Return a list of the forms in BODY preceded by :autoload."
647 (when (setq acons (memq :autoload body))
650 (names--extract-autoloads (cdr (cdr acons)))))))
653 (defadvice make-autoload (around names-before-make-autoload-advice
654 (form file &optional expansion) activate)
655 "Make sure `make-autoload' understands `define-namespace'.
656 Use the `names--inside-make-autoload' variable to indicate to
657 `define-namespace' that we're generating autoloads."
658 ;; We used to have a letbind here, but this was causing a void
659 ;; variable bug on Emacs 24.3.
661 (if (null (eq (car-safe form) 'define-namespace))
663 (setq names--inside-make-autoload t)
664 (setq form (macroexpand form))
665 (setq names--inside-make-autoload nil)
666 ;; Up to 24.2 `make-autoload' couldn't handle `progn's.
667 (if (version< emacs-version "24.3")
668 (setq ad-return-value
670 (mapcar (lambda (x) (names--make-autoload-compat x file))
672 (ad-set-arg 2 'expansion)
676 (defun names--make-autoload-compat (form file)
677 (if (eq (car-safe form) 'defalias)
679 (make-autoload form file)))
681 (defvar names--ignored-forms '(declare)
682 "The name of functions/macros/special-forms which we return without reading.")
684 (defun names--handle-args (func args)
685 "Generic handling for the form (FUNC . ARGS), without namespacing FUNC."
686 (if (memq func names--ignored-forms)
688 ;; TODO: Speed this up. Just change it to an alist or a hash-table.
689 (let ((handler (intern-soft (format "names--convert-%s" func))))
690 ;; Some function-like forms get special handling.
691 ;; That's anything with a names--convert-%s function defined.
692 (if (fboundp handler)
693 (progn (names--message "Special handling: %s" handler)
694 (funcall handler (cons func args)))
695 ;; If it isn't special, it's either a function or a macro.
696 (names--args-of-function-or-macro func args (names--compat-macrop func))))))
698 (defun names--message (f &rest rest)
699 "If :verbose is on, pass F and REST to `message'."
700 (when (names--keyword :verbose)
701 (apply 'message (concat "[names] " f) rest)))
703 (defun names--warn (f &rest rest)
704 "Pass F and REST to `message', unless byte-compiling or non-interactive."
705 (unless (and (null (names--keyword :verbose))
706 (and (boundp 'byte-compile-function-environment)
707 byte-compile-function-environment))
708 (apply 'message (concat "[names] " f) rest)))
710 (defun names--error-if-using-vars ()
711 "Remind the developer that variables are not customizable."
715 (error "[names] Global value of variable %s should be nil! %s"
716 x "Set it using keywords instead")))
719 (defun names--remove-namespace-from-list (&rest lists)
720 "Return a concatenated un-namespaced version of LISTS.
721 Symbols in LISTS that aren't namespaced are removed, symbols that
722 are namespaced become un-namespaced."
723 (delq nil (mapcar 'names--remove-namespace (apply 'append lists))))
725 (defun names--remove-namespace (symbol)
726 "Return SYMBOL with namespace removed, or nil if it wasn't namespaced."
727 (names--remove-regexp symbol names--regexp))
729 (defun names--remove-protection (symbol)
730 "Remove the leading :: from SYMBOL if possible, otherwise return nil."
731 (names--remove-regexp symbol names--protection))
733 (defun names--remove-regexp (s r)
734 "Return S with regexp R removed, or nil if S didn't match."
735 (let ((name (symbol-name s)))
736 (when (string-match r name)
737 (intern (replace-match "" nil nil name)))))
739 (defun names--quote-p (sbl)
740 "Is SBL a function which quotes its argument?"
741 (memq sbl '(quote function)))
743 (defun names--fboundp (sbl)
744 "Is namespace+SBL a fboundp symbol?"
745 (or (memq sbl names--fbound)
746 (memq sbl names--macro)
747 (and (names--keyword :global)
748 (fboundp (names--prepend sbl)))))
750 (defun names--macrop (sbl)
751 "Is namespace+SBL a fboundp symbol?"
752 (or (memq sbl names--macro)
753 (and (names--keyword :global)
754 (names--compat-macrop (names--prepend sbl)))))
756 (defun names--keyword (keyword)
757 "Was KEYWORD one of the keywords passed to the `namespace' macro?"
758 (assoc keyword names--keywords))
760 (defun names--boundp (sbl)
761 "Is namespace+SBL a boundp symbol?
762 If SBL has a let binding, that takes precendence so this also
764 (and (null (memq sbl names--local-vars))
765 (or (memq sbl names--bound)
766 (and (names--keyword :global)
767 (boundp (names--prepend sbl))))))
769 (defvar names--verbose nil
770 "If non-nil, verbose message are printed regardless of the :verbose keyword.
771 Use this to easily turn on verbosity during tests.")
773 (defun names--args-of-function-or-macro (function args macro)
774 "Namespace FUNCTION's arguments ARGS, with special treatment if MACRO is non-nil."
776 (let ((it (names--get-edebug-spec function))
777 (names--verbose (eq function 'push)))
778 (names--message "Edebug-spec of `%s' is %s" function it)
779 ;; Macros where we evaluate all arguments are like functions.
781 (memq function names--functionlike-macros))
782 (names--args-of-function-or-macro function args nil)
783 ;; Macros where nothing is evaluated we can just return.
786 ;; Other macros are complicated. Ask edebug for help.
787 (names--macro-args-using-edebug (cons function args)))))
788 ;; We just convert the arguments of functions.
789 (cons function (mapcar 'names-convert-form args))))
791 (defun names--get-edebug-spec (name)
792 "Get 'edebug-form-spec property of symbol NAME."
793 ;; Get the spec of symbol resolving all indirection.
797 (and (symbolp indirect)
800 indirect 'edebug-form-spec 'macro))))
801 ;; (edebug-trace "indirection: %s" edebug-form-spec)
802 (setq spec indirect))
805 (defvar names--is-inside-macro nil
806 "Auxiliary var used in `names--macro-args-using-edebug'.")
808 (defvar names--gensym-counter 0
809 "Counter used to uniquify symbols generated `names--gensym'.")
811 (defun names--macro-args-using-edebug (form)
812 "Namespace the arguments of macro FORM by hacking into edebug.
813 This takes advantage of the fact that macros (should) declare a
814 `debug' specification which tells us which arguments are actually
817 Ideally, we would read this specification ourselves and see how
818 it matches (cdr FORM), but that would take a lot of work and
819 we'd be reimplementing something that edebug already does
820 phenomenally. So we hack into edebug instead."
824 ((max-lisp-eval-depth 3000)
827 (names--is-inside-macro form)
828 ;; Prevent excessive messaging.
829 ;; TODO: Don't do this if `message' is advised.
830 ((symbol-function 'message) #'names--edebug-message)
831 ;; Older edebugs have poor `get-edebug-spec'.
832 ((symbol-function 'get-edebug-spec) #'names--get-edebug-spec)
833 ;; Give symbols our own name.
834 ((symbol-function 'cl-gensym) #'names--gensym)
835 ;; Stop at one level deep.
836 ((symbol-function 'edebug-form) #'names--edebug-form)
837 ;; Don't actually wrap anything.
838 ((symbol-function 'edebug-make-enter-wrapper)
839 #'names--edebug-make-enter-wrapper))
843 (goto-char (point-min))
845 (edebug-read-top-level-form))
848 "Couldn't namespace this macro using its (debug ...) declaration: %s"
852 (when (equal (car-safe (cdr-safe er))
853 "Lisp nesting exceeds `max-lisp-eval-depth'")
855 "Lisp nesting exceeded `max-lisp-eval-depth' at the following form: %s"
859 (defvar names--message-backup
860 (if (ad-is-advised 'message)
861 (ad-get-orig-definition 'message)
862 (symbol-function 'message))
863 "Where names stores `message's definition while overriding it.")
865 (defun names--edebug-message (&rest args)
866 (if (or (names--keyword :verbose) names--verbose)
867 (apply names--message-backup args)
868 (when args (apply #'format args))))
870 (defun names--edebug-make-enter-wrapper (forms)
871 (setq edebug-def-name
874 (names--gensym "edebug-anon")))
877 (defun names--gensym (prefix)
878 "Generate a new uninterned symbol.
879 The name is made by appending a number to PREFIX and preppending \"names\", default \"G\"."
880 (let ((num (prog1 names--gensym-counter
881 (setq names--gensym-counter
882 (1+ names--gensym-counter)))))
883 (make-symbol (format "names-%s%d" (if (stringp prefix) prefix "G") num))))
885 (defun names--edebug-form (cursor)
886 "Parse form given by CURSOR using edebug, and namespace it if necessary."
888 ;; Return the instrumented form for the following form.
889 ;; Add the point offsets to the edebug-offset-list for the form.
890 (let* ((form (edebug-top-element-required cursor "Expected form"))
891 (offset (edebug-top-offset cursor))
892 ;; We don't want to convert the entire form that was passed
893 ;; to `names--macro-args-using-edebug', since the head of
894 ;; that was already converted and it would lead to an
896 ;; So we check for (equal names--is-inside-macro form)
897 ;; Simply incrementing a depth counter didn't work, for a
898 ;; reason I can no longer remember.
900 ;; We DO want to convert the arguments that edebug identifies
901 ;; as forms (level-1). And we do that ourselves, don't pass
903 (func (if (or (eq names--is-inside-macro t)
904 (equal names--is-inside-macro form))
905 'identity 'names-convert-form))
906 (names--is-inside-macro
907 (if (eq func 'names-convert-form)
908 t names--is-inside-macro)))
909 (names--message " [Edebug] Ran into this: %S" form)
910 (names--message " Cursor: %S" cursor)
913 ((consp form) ;; The first offset for a list form is for the list form itself.
914 (if (eq func 'names-convert-form)
915 (names-convert-form form)
916 (let* ((head (car form))
917 (spec (and (symbolp head) (get-edebug-spec head)))
918 (new-cursor (edebug-new-cursor form offset)))
919 ;; Find out if this is a defining form from first symbol.
920 ;; An indirect spec would not work here, yet.
921 (if (and (consp spec) (eq '&define (car spec)))
922 (edebug-defining-form
924 (car offset) ;; before the form
925 (edebug-after-offset cursor)
926 (cons (symbol-name head) (cdr spec)))
927 ;; Wrap a regular form.
928 (edebug-list-form new-cursor)))))
933 ;; Anything else is self-evaluating.
935 (edebug-move-cursor cursor))))
937 (defun names--maybe-append-group (form)
938 "Append (:group `names--package') to FORM.
939 Only if the :group keyword was passed to `define-namespace' and
940 if the form doesn't already have a :group."
941 (if (or (null names--group-parent) (memq :group form))
943 (append form `(:group ',(names--package-name)))))
946 ;;; ---------------------------------------------------------------
947 ;;; Interpreting keywords passed to the main macro.
948 (defun names--handle-keyword (body)
949 "Call the function that handles the keyword at the car of BODY.
950 Such function must be listed in `names--keyword-list'. If it is
951 nil, this function just returns.
953 Regardless of whether a function was called, the keyword is added
954 to the variable `names--keywords'.
956 The car of BODY is the keyword itself and the other elements are
957 the keyword arguments, if any."
958 (let ((func (nth 2 (assoc (car body) names--keyword-list))))
960 (apply func (cdr body))
964 ;;; ---------------------------------------------------------------
965 ;;; Interpreting the actual forms found in BODY of the main macro.
967 ;; This is where the heavy work is done.
969 ;; If you'd like to implement support for some special form, simply
970 ;; define a function called `names--convert-FORM-NAME' along the
971 ;; lines of the functions defined below. It will be automatically used
972 ;; whenever that form is found.
974 ;;; Defun, defmacro, and defsubst macros are pretty predictable.
975 (defun names--convert-defmacro (form)
976 "Special treatment for `defmacro' FORM."
977 (let* ((names--name-already-prefixed t)
979 (spaced-name (names--prepend name))
981 (add-to-list 'names--macro name)
982 (add-to-list 'names--fbound name)
983 ;; Set the macros debug spec if possible. It will be relevant on
985 (when (setq decl (ignore-errors (cond
986 ((eq (car-safe (nth 3 form)) 'declare)
988 ((and (stringp (nth 3 form))
989 (eq (car-safe (nth 4 form)) 'declare))
992 (setq decl (car (cdr-safe (assoc 'debug (cdr decl)))))
993 (when decl (put spaced-name 'edebug-form-spec decl)))
994 ;; Then convert the macro as a defalias.
997 (names--convert-lambda
998 (cons spaced-name (cddr form))))))
999 (defalias 'names--convert-defmacro* 'names--convert-defmacro)
1001 (defun names--convert-defvaralias (form)
1002 "Special treatment for `defvaralias' FORM."
1003 (let ((form (cons (car form)
1004 (mapcar #'names-convert-form (cdr form))))
1006 (setq name (names--remove-namespace
1007 (ignore-errors (eval (cadr form)))))
1009 (add-to-list 'names--bound name))
1012 (defun names--convert-defalias (form)
1013 "Special treatment for `defalias' FORM."
1014 (let ((form (cons (car form)
1015 (mapcar #'names-convert-form (cdr form))))
1017 (setq name (names--remove-namespace
1018 (ignore-errors (eval (cadr form)))))
1020 (add-to-list 'names--fbound name))
1023 (defun names--convert-defvar (form &optional dont-add)
1024 "Special treatment for `defvar' FORM.
1025 If DONT-ADD is nil, the FORM's `cadr' is added to `names--bound'."
1026 (let ((name (cadr form)))
1028 (add-to-list 'names--bound name))
1032 (names--prepend name))
1033 (mapcar 'names-convert-form (cdr (cdr form))))))
1035 (defalias 'names--convert-defconst 'names--convert-defvar
1036 "Special treatment for `defconst' FORM.")
1038 (defun names--convert-defcustom (form)
1039 "Special treatment for `defcustom' FORM."
1040 (names--maybe-append-group
1041 (names--convert-defvar form)))
1043 (defun names--convert-custom-declare-variable (form)
1044 "Special treatment for `custom-declare-variable' FORM."
1045 (let ((name (eval (cadr form))) ;;ignore-errors
1046 (val (car (cddr form))))
1047 (add-to-list 'names--bound name)
1051 (list 'quote (names--prepend name)) ;cadr
1052 ;; The DEFAULT argument is explicitly evaluated by
1053 ;; `custom-declare-variable', so it should be safe to namespace
1054 ;; even when quoted. Plus, we need to do this because
1055 ;; defcustom quotes this part.
1056 (if (names--quote-p (car-safe val))
1057 (list (car val) (names-convert-form (cadr val)))
1058 (names-convert-form val))
1059 (names-convert-form (car (cdr (cdr (cdr form))))))
1060 (mapcar 'names-convert-form (cdr (cdr (cdr (cdr form))))))))
1062 (defun names--convert-defface (form)
1063 "Special treatment for `defface' FORM.
1064 Identical to defvar, just doesn't add the symbol to the boundp
1065 list. And maybe use a :group."
1066 (names--maybe-append-group
1067 (names--convert-defvar form :dont-add)))
1069 (defun names--convert-define-derived-mode (form)
1070 "Special treatment for `define-derived-mode' FORM."
1071 (let ((name (cadr form)))
1072 (add-to-list 'names--fbound name)
1073 (add-to-list 'names--bound name)
1074 (add-to-list 'names--bound
1075 (intern (format "%s-map" name)))
1076 (add-to-list 'names--bound
1077 (intern (format "%s-hook" name)))
1079 (names--maybe-append-group
1080 ;; And here we namespace it.
1083 (names--prepend name)
1085 (names-convert-form (nth 3 form))
1086 (names-convert-form (nth 4 form))))
1087 (mapcar #'names-convert-form (cddr (cl-cdddr form))))))
1089 (defun names--convert-define-minor-mode (form)
1090 "Special treatment for `define-minor-mode' FORM."
1091 (let ((name (cadr form))
1092 (keymap (nth 5 form)))
1093 ;; Register the mode name
1094 (add-to-list 'names--fbound name)
1095 (add-to-list 'names--bound name)
1096 (add-to-list 'names--bound (intern (format "%s-hook" name)))
1097 ;; Register the keymap
1098 (if (or (null keymap) (null (symbolp keymap)))
1099 (add-to-list 'names--bound (intern (format "%s-map" name)))
1100 (when (setq keymap (names--remove-namespace keymap))
1101 (add-to-list 'names--bound keymap)))
1103 (names--maybe-append-group
1104 ;; And here we namespace it.
1107 (names--prepend name)
1109 (names-convert-form (nth 3 form))
1110 (names-convert-form (nth 4 form))
1111 (names-convert-form (nth 5 form))
1112 (names-convert-form (nth 6 form))))
1113 (mapcar #'names-convert-form (cddr form)))))
1115 (defun names--convert-define-globalized-minor-mode (form)
1116 "Special treatment for `define-globalized-minor-mode' FORM.
1117 The NAME of the global mode will NOT be namespaced, despite being
1118 a definition. It is kept verbatim.
1119 This is because people tend to name their global modes as
1120 `global-foo-mode', and namespacing would make this impossible.
1122 The MODE and TURN-ON arguments are converted as function names.
1123 Everything else is converted as regular forms (which usually
1124 means no conversion will happen since it's usually keywords and
1126 (let ((name (names--remove-namespace (cadr form)))
1127 (copy (cl-copy-list form)))
1128 ;; Register the mode name
1130 (add-to-list 'names--fbound name)
1131 (add-to-list 'names--bound name)
1132 (add-to-list 'names--bound (intern (format "%s-hook" name))))
1133 (names--maybe-append-group
1134 ;; And here we namespace it.
1139 (names--handle-symbol-as-function (pop copy))
1140 (names--handle-symbol-as-function (pop copy)))
1141 (mapcar #'names-convert-form copy)))))
1142 (defalias #'names--convert-define-global-minor-mode
1143 #'names--convert-define-globalized-minor-mode)
1144 (defalias #'names--convert-easy-mmode-define-global-mode
1145 #'names--convert-define-globalized-minor-mode)
1147 (defun names--convert-quote (form)
1148 "Special treatment for `quote' FORM.
1149 When FORM is (quote argument), argument too arbitrary to be
1150 logically namespaced and is never parsed for namespacing
1151 (but see :assume-var-quote in `names--keyword-list').
1153 When FORM is (function form), a symbol is namespaced as a
1154 function name, a list is namespaced as a lambda form."
1155 (let ((kadr (cadr form))
1156 (this-name (car form))
1158 (if (and (eq this-name 'function)
1160 (list this-name (names-convert-form kadr))
1163 ;; A symbol inside a function quote should be a function,
1164 ;; unless the user disabled that.
1165 ((and (eq this-name 'function)
1166 (null (names--keyword :dont-assume-function-quote)))
1168 (names--handle-symbol-as-function kadr)))
1170 ;; A symbol inside a regular quote should be a function, if
1171 ;; the user asked for that.
1172 ((and (eq this-name 'quote)
1173 (names--keyword :assume-var-quote))
1175 (or (names--remove-protection kadr)
1176 (if (names--boundp kadr)
1177 (names--prepend kadr)
1183 (defun names--handle-symbol-as-function (s)
1184 "Namespace symbol S as a function name."
1185 (or (names--remove-protection s)
1186 (if (names--fboundp s) (names--prepend s) s)))
1188 (defalias 'names--convert-function 'names--convert-quote)
1190 (defun names--convert-macro (form)
1191 "Special treatment for `macro' form.
1192 Return (macro . (names-convert-form (cdr FORM)))."
1193 (cons 'macro (names-convert-form (cdr form))))
1195 (defun names--convert-lambda (form)
1196 "Special treatment for `lambda' FORM."
1197 (let ((names--local-vars
1198 (append (names--vars-from-arglist (cadr form))
1200 (forms (cdr (cdr form))))
1204 (when (stringp (car forms))
1207 (setq forms (cdr forms))))
1208 (when (eq 'interactive (car-safe (car forms)))
1210 (list (list (car (car forms))
1211 (names-convert-form (cadr (car forms)))))
1212 (setq forms (cdr forms))))
1214 ;; (message "%S" forms)
1215 (mapcar 'names-convert-form forms)))))
1217 (defun names--convert-clojure (form)
1218 "Special treatment for `clojure' FORM."
1219 (names--warn "Found a `closure'! You should use `lambda's instead")
1220 (let ((names--local-vars
1221 (append (names--vars-from-arglist (cadr form))
1223 (forms (cdr (cdr form))))
1226 (names--convert-lambda (cdr form)))))
1228 (defun names--vars-from-arglist (args)
1229 "Get a list of local variables from a generalized arglist ARGS."
1234 (let ((symb (or (cdr-safe (car-safe x)) (car-safe x) x)))
1235 (when (and (symbolp symb)
1236 (null (string-match "^&" (symbol-name symb)))
1241 (defun names--convert-defun (form)
1242 "Special treatment for `defun' FORM."
1243 (let* ((name (cadr form)))
1244 (add-to-list 'names--fbound name)
1246 (names--convert-lambda
1247 (cons (names--prepend name) (cddr form))))))
1248 (defalias 'names--convert-defun* 'names--convert-defun)
1249 (defalias 'names--convert-defsubst 'names--convert-defun)
1250 (defalias 'names--convert-defsubst* 'names--convert-defun)
1252 (defun names--let-var-convert-then-add (sym add)
1253 "Try to convert SYM unless :no-let-vars is in use.
1254 If ADD is non-nil, add resulting symbol to `names--local-vars'."
1255 (let ((name (if (null (names--keyword :no-let-vars))
1256 (names-convert-form sym)
1258 (when add (add-to-list 'names--local-vars name))
1261 (defun names--convert-let (form &optional star)
1262 "Special treatment for `let' FORM.
1263 If STAR is non-nil, parse as a `let*'."
1264 (let* ((names--local-vars names--local-vars)
1269 (list (names--let-var-convert-then-add (car x) star)
1270 (names-convert-form (cadr x)))
1271 (names--let-var-convert-then-add x star)))
1273 ;; Each var defined in a regular `let' only becomes protected after
1274 ;; all others have been defined.
1276 (setq names--local-vars
1278 (mapcar (lambda (x) (or (car-safe x) x)) vars)
1279 names--local-vars)))
1281 (list (car form) vars)
1282 (mapcar 'names-convert-form (cddr form)))))
1284 (defun names--convert-let* (form)
1285 "Special treatment for `let' FORM."
1286 (names--convert-let form t))
1288 (defun names--convert-cond (form)
1289 "Special treatment for `cond' FORM."
1293 (lambda (x) (mapcar #'names-convert-form x))
1296 (defun names--convert-condition-case (form)
1297 "Special treatment for `condition-case' FORM."
1302 (names-convert-form (cadr (cdr form))))
1306 (mapcar 'names-convert-form (cdr x))))
1307 (cddr (cdr form)))))
1310 ;;; names.el ends here