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 (indirect-function object t)))
91 (or (eq 'macro (car def))
92 (and (names--autoloadp def) (memq (nth 4 def) '(macro t)))))))))
94 (defalias 'names--autoloadp
95 (if (fboundp 'autoloadp) #'autoloadp
97 "Non-nil if OBJECT is an autoload."
98 (eq 'autoload (car-safe object)))))
100 (unless (get-edebug-spec 'cl-defun)
101 (def-edebug-spec cl-defun defun*))
102 (unless (get-edebug-spec 'cl-defmacro)
103 (def-edebug-spec cl-defmacro defmacro*))
104 (unless (get-edebug-spec 'setq-local)
105 (def-edebug-spec setq-local setq))
106 (unless (get-edebug-spec 'loop)
107 (def-edebug-spec loop
109 ;; These are usually followed by a symbol, but it can
110 ;; actually be any destructuring-bind pattern, which
111 ;; would erroneously match `form'.
112 [[&or "for" "as" "with" "and"] sexp]
113 ;; These are followed by expressions which could
114 ;; erroneously match `symbolp'.
115 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
116 "above" "below" "by" "in" "on" "=" "across"
117 "repeat" "while" "until" "always" "never"
118 "thereis" "collect" "append" "nconc" "sum"
119 "count" "maximize" "minimize" "if" "unless"
121 ;; Simple default, which covers 99% of the cases.
125 ;;; ---------------------------------------------------------------
127 (defconst names-version "20150115.1" "Version of the names.el package.")
129 (defvar names--name nil
130 "Name of the current namespace inside the `define-namespace' macro.")
131 (defvar names--regexp nil "Regexp matching `names--name'.")
133 (defvar names--load-file (and load-file-name (expand-file-name load-file-name))
134 "The file where the current version of Names was loaded.
135 This is used by `names--check-for-update' to check if a new
136 version has been installed.")
138 (defvar names--bound nil
139 "List of variables defined in this namespace.")
140 (defvar names--fbound nil
141 "List of functions defined in this namespace.")
142 (defvar names--macro nil
143 "List of macros defined in this namespace.")
145 (defvar names--keywords nil
146 "Keywords that were passed to the current namespace.
147 See `names--keyword-list' for a list and description of possible
150 (defvar names--local-vars nil
151 "Non-global vars that are let/lambda bound at the moment.
152 These won't be namespaced, as local takes priority over namespace.")
154 (defvar names--protection nil
155 "Leading chars used to identify protected symbols.
156 Don't customise this.
157 Instead use the :protection keyword when defining the
160 (defvar names--current-run nil
161 "Either 1 or 2, depending on which runthrough we're in.")
163 (defvar names--var-list
164 '(names--name names--regexp names--bound
166 names--package names--group-parent
167 names--macro names--current-run
168 names--fbound names--keywords
169 names--local-vars names--protection)
170 "List of variables the user shouldn't touch.")
173 (defvar names--inside-make-autoload nil
174 "Used in `make-autoload' to indicate we're making autoloads.")
176 (defvar names--package nil
177 "Package, name to be used by the :group and :version keywords.
178 Is derived from `load-file-name', unless the :package keyword is
179 passed to `define-namespace'.")
181 (defvar names--group-parent nil
182 "The name of the parent to be given to `defgroup'.
183 Is only non-nil if the :group keyword is passed to `define-namespace'.")
185 (defvar names--version nil
186 "The version number given by :version.
187 Used to define a constant and a command.")
189 (defconst names--keyword-list
192 (if (or (symbolp x) (listp x))
193 (setq names--group-parent x)
195 "Argument given to :group is not a symbol: %s" x)))
196 "Indicate `define-namespace' should make a `defgroup' for you.
197 The name of the group is the package name (see :package keyword).
198 This keyword should be given one argument, the name of the PARENT
199 group as an unquoted symbol.
201 Alternatively, the argument can be a list, in which case it is a
202 list of arguments to be passed to `defgroup' (essentially, a full
203 group definition without the leading `defgroup').
205 If this keyword is provided, besides including a defgroup, Names
206 will also include a :group keyword in every `defcustom' (and
207 similar forms) that don't already contain one.")
213 (setq names--version x)
215 "Argument given to :version is not a string: %s" x)))
216 "Indicate `define-namespace' should define the version number.
217 This keyword should be given one argument, a string describing
218 the package's version number.
220 With this, Names will generate a `defconst' and an interactive
221 `defun', each named `PACKAGE-NAME-version'. The function messages
222 and returns the version number. See the :package keyword.")
228 (setq names--package x)
230 "Argument given to :package is not a symbol: %s" x)))
231 "Set the name of this package to the given symbol.
232 This keyword should be given one argument, a symbol corresponding
233 to the name of this package.
235 If this keyword isn't used, the package name is taken as the the
236 file's basename, but only if its actually needed. This name is
237 needed by the :version and :group keywords.")
242 (let ((val (symbol-name x)))
243 (setq names--protection
244 (format "\\`%s" (regexp-quote val)))))
245 "Change the value of the `names--protection' variable.")
249 "Indicates variables assigned in let-bind are NOT candidates for namespacing.")
253 "Cause a message to be called on each special form.")
257 "Accept namespaced names from outside current namespace definition.")
261 "Indicate symbols quoted with `quote' should be considered variable names.")
263 (:dont-assume-function-quote
265 "Indicate symbols quoted with `function' should NOT be considered function names.")
269 "Indicate only forms actually inside the namespace should be present in the output.
270 This is for internal use. It is used by `names-eval-defun' to
271 prevent `define-namespace' from adding things like `defgroup' or
272 `defconst's to the output."))
273 "List of keywords used by `define-namespace'.
274 Each element is a list containing
275 (KEYWORD N DEFINITION DOCUMENTATION)
278 - KEYWORD is the keyword's name, a symbol satifying `keywordp'.
279 - N is the number of arguments it takes, an integer.
280 - DEFINITION is a function (symbol or lambda) that takes N
281 arguments and does whatever you need for implementing the
283 - DOCUMENTATION is a string explaining the keyword's
286 (defmacro names--prepend (sbl)
287 "Return namespace+SBL."
288 (declare (debug (symbolp)))
289 `(intern (format "%s%s" names--name ,sbl)))
292 (defmacro names--filter-if-bound (var &optional pred)
293 "If VAR is bound and is a list, take the car of its elements which satify PRED."
294 (declare (debug (symbolp &optional function-form)))
295 `(when (boundp ',var)
298 (mapcar (lambda (x) (when (funcall (or ,pred #'identity) (or (car-safe x) x))
299 (or (car-safe x) x)))
302 (defmacro names--next-keyword (body)
303 "If car of BODY is a known keyword, `pop' it (and its arguments) from body.
304 Returns a list (KEYWORD . ARGUMENTLIST)."
305 (declare (debug sexp))
306 `(let ((kar (car-safe ,body))
310 (setq n (assoc kar names--keyword-list))
312 (dotimes (_ (1+ n) out)
313 (push (pop ,body) out))
316 (defvar names--has-reloaded nil
317 "Whether `names--reload-if-upgraded' has already been called in this run.")
320 ;;; ---------------------------------------------------------------
321 ;;; The Main Macro and Main Function.
323 (defmacro define-namespace (name &rest body)
324 "Inside the namespace NAME, execute BODY.
325 NAME can be any symbol (not quoted), but it's highly recommended
326 to use some form of separator (such as :, /, or -). For a
327 complete description of this macro, please visit the frontpage
328 with \\[names-view-manual].
330 In summary, this macro has two main effects:
332 1. Any definitions inside BODY will have NAME prepended to the
335 (define-namespace foo-
336 (defvar bar 1 \"docs\")
341 (defvar foo-bar 1 \"docs\")
344 2. Any function calls and variable names get NAME prepended to
345 them if such a variable or function exists. Ex:
347 (define-namespace foo:
348 (defun message (x y) nil)
349 (message \"%s\" my-var)
354 (defun foo:message (x y) nil)
355 (foo:message \"%s\" my-var)
357 Note how `message' is expanded to `foo:message' in the second
358 form, because that function exists. Meanwhile, `bar' is left
359 untouched because `foo:bar' is not a known variable name.
361 ===============================
365 In order for `define-namespace' to work with \";;;###autoload\"
366 comments must replace all instances of \";;;###autoload\" inside
367 your `define-namespace' with `:autoload'.
368 Afterwards, add an \";;;###autoload\" comment just above your
371 ===============================
375 Immediately after NAME you may add keywords which customize the
376 behaviour of `define-namespace'. For a list of possible keywords
377 and a description of their effects, see the variable
378 `names--keyword-list'.
380 \(fn NAME [KEYWORD ...] BODY)"
381 (declare (indent (lambda (&rest x) 0))
382 (debug (&define name [&rest keywordp &optional [&or symbolp (symbolp . symbolp)]] body)))
383 (let ((names--has-reloaded names--has-reloaded))
384 ;; This was to avoid an infinite recursion, but the bug turned out
385 ;; to be somewhere else. Still, I see no reason to erase this.
386 (unless names--has-reloaded
387 (setq names--has-reloaded t)
388 (names--reload-if-upgraded))
389 (names--error-if-using-vars)
390 (names--define-namespace-implementation name body)))
392 (defun names--define-namespace-implementation (name body)
393 "Namespace BODY using NAME.
394 See `define-namespace' for more information."
396 (let* ((names--name name)
398 (concat "\\`" (regexp-quote (symbol-name name))))
399 (names--current-run 0)
400 ;; Use the :protection keyword to change this.
401 (names--protection "\\`::")
403 (names--remove-namespace-from-list
404 (names--filter-if-bound byte-compile-bound-variables)
405 (names--filter-if-bound byte-compile-variables)))
407 (names--remove-namespace-from-list
408 (names--filter-if-bound byte-compile-macro-environment 'names--compat-macrop)
409 (names--filter-if-bound byte-compile-function-environment 'names--compat-macrop)))
411 (names--remove-namespace-from-list
412 (names--filter-if-bound byte-compile-macro-environment (lambda (x) (not (names--compat-macrop x))))
413 (names--filter-if-bound byte-compile-function-environment (lambda (x) (not (names--compat-macrop x))))))
414 names--keywords names--local-vars key-and-args
415 names--version names--package names--group-parent)
417 (while (setq key-and-args (names--next-keyword body))
418 (names--handle-keyword key-and-args)
419 (push key-and-args names--keywords))
421 ;; First have to populate the bound and fbound lists. So we read
422 ;; the entire form (without evaluating it).
423 (mapc 'names-convert-form body)
424 (setq names--current-run (1+ names--current-run))
426 ;; Then we go back and actually namespace the entire form, which
427 ;; we'll later return so that it can be evaluated.
432 (when (and names--group-parent
433 (null (names--keyword :clean-output)))
434 (list (names--generate-defgroup)))
435 (when (and names--version
436 (null (names--keyword :clean-output)))
437 ;; `names--generate-version' returns a list.
438 (names--generate-version))
439 (mapcar 'names-convert-form
440 ;; Unless we're in `make-autoload', then just return autoloads.
441 (if names--inside-make-autoload
442 (names--extract-autoloads body)
445 ;; On emacs-version < 24.4, the byte-compiler cannot expand a
446 ;; macro if it is being called in the same top-level form as
447 ;; it was defined. That's a problem for us, since the entire
448 ;; namespace is a single top-level form (we return a `progn').
449 ;; The solution is for us to add the macros to
450 ;; `byte-compile-macro-environment' ourselves.
451 (if (and (boundp 'byte-compile-current-buffer)
452 byte-compile-current-buffer
453 (null names--inside-make-autoload)
454 (version< emacs-version "24.4"))
455 (let ((byte-compile-macro-environment
456 (when (boundp 'byte-compile-macro-environment)
457 byte-compile-macro-environment)))
458 (mapc #'names--add-macro-to-environment (cdr body))
459 (macroexpand-all body byte-compile-macro-environment))
462 ;; Exiting the `unwind-protect'.
463 (mapc (lambda (x) (set x nil)) names--var-list)))
465 (defun names--reload-if-upgraded ()
466 "Verify if there's a more recent version of Names in the `load-path'.
470 (let ((lp (expand-file-name (find-library-name "names")))
473 (not (string= lp names--load-file))
474 (file-readable-p lp))
476 (insert-file-contents-literally lp)
477 (goto-char (point-min))
480 (when (search-forward-regexp
481 "(defconst\\s-+names-version\\s-+\"\\([^\"]+\\)\"" nil t)
482 (match-string-no-properties 1))))
483 (when (and new-version (version< names-version new-version))
484 (eval-buffer nil lp)))))))
486 (defun names-convert-form (form)
487 "Do namespace conversion on FORM.
488 FORM is any legal elisp form.
489 Namespace name is defined by the global variable `names--name'.
491 See macro `namespace' for more information."
496 (let ((kar (car form))
499 ;; If symbol is protected, clean it.
501 (setq func (names--remove-protection kar)))
502 (names--message "Protected: %s" kar)
503 ;; And decide what to do with it.
504 (names--handle-args func (cdr form)))
506 ;; If kar is a list, either 1) it's a lambda form, 2) it's a
507 ;; macro we don't know about yet, 3) we have a bug.
509 (when (and (null (functionp kar))
510 (> names--current-run 1))
511 (names--warn "Ran into the following strange form.
512 Either it's an undefined macro, a macro with a bad debug declaration, or we have a bug.\n%s" form))
513 (mapcar 'names-convert-form form))
515 ;; Namespaced Functions/Macros
516 ((names--fboundp kar)
517 (names--message "Namespaced: %s" kar)
518 (names--args-of-function-or-macro
519 (names--prepend kar) (cdr form) (names--macrop kar)))
521 ;; General functions/macros/special-forms
522 (t (names--handle-args kar (cdr form))))))
525 (names--message "Symbol handling: %s" form)
526 ;; If symbol is protected, clean it and don't namespace it.
527 (or (names--remove-protection form)
528 ;; Otherwise, namespace if possible.
529 (if (names--boundp form)
530 (names--prepend form)
536 ;;; ---------------------------------------------------------------
537 ;;; Some auxiliary functions
538 (defun names-view-manual ()
539 "Call `browse-url' to view the manual of the Names package."
541 (browse-url "http://github.com/Bruce-Connor/names"))
543 (defun names--package-name ()
544 "Return the package name as a symbol.
545 Decide package name based on several factors. In order:
546 1. The :package keyword,
547 2. The namespace NAME, removing the final char."
549 (let ((package (symbol-name names--name)))
550 (prog1 (setq names--package
551 (intern (substring package 0 -1)))
552 (names--warn "No :package given. Guessing `%s'"
555 (defun names--generate-defgroup ()
556 "Return a `defgroup' form for the current namespace."
557 (if (listp names--group-parent)
558 (cons 'defgroup names--group-parent)
559 (list 'defgroup (names--package-name) nil
560 (format "Customization group for %s." (names--package-name))
561 :prefix (symbol-name names--name)
562 :group `',names--group-parent)))
564 (defun names--generate-version ()
565 "Return a `defun' and a `defconst' forms declaring the package version.
566 Also adds `version' to `names--fbound' and `names--bound'."
567 (add-to-list 'names--fbound 'version)
568 (add-to-list 'names--bound 'version)
570 (list 'defconst (names--prepend 'version)
572 (format "Version of the %s package." (names--package-name)))
573 (list 'defun (names--prepend 'version) nil
574 (format "Version of the %s package." (names--package-name))
577 ,(format "%s version: %s" (names--package-name) names--version))
580 (defun names--add-macro-to-environment (form)
581 "If FORM declares a macro, add it to `byte-compile-macro-environment'."
582 (let ((expansion form))
583 (while (names--compat-macrop (car-safe expansion))
585 (ignore-errors (macroexpand
586 expansion byte-compile-macro-environment))))
589 (or (and (memq (car-safe expansion) '(progn prog1 prog2))
590 (mapc #'names--add-macro-to-environment (cdr expansion)))
591 (and (eq 'defalias (car-safe expansion))
592 (let ((def (ignore-errors (eval (nth 2 expansion)))))
593 (and (names--compat-macrop def)
594 (push (cons (ignore-errors
595 (eval (nth 1 expansion)))
597 byte-compile-macro-environment))))))))
600 (defadvice find-function-search-for-symbol
601 (around names-around-find-function-search-for-symbol-advice
602 (symbol type library) activate)
603 "Make sure `find-function-search-for-symbol' understands namespaces."
606 (unless (cdr ad-return-value)
607 (with-current-buffer (car ad-return-value)
608 (search-forward-regexp "^(define-namespace\\_>")
609 (skip-chars-forward "\r\n[:blank:]")
610 (let* ((names--regexp
611 (concat "\\`" (regexp-quote
612 (symbol-name (read (current-buffer))))))
614 ;; We manually implement `names--remove-namespace'
615 ;; because it might not be loaded.
616 (let ((name (symbol-name symbol)))
617 (when (string-match names--regexp name)
618 (intern (replace-match "" nil nil name))))))
620 (ad-set-arg 0 short-symbol)
623 (defun names--extract-autoloads (body)
624 "Return a list of the forms in BODY preceded by :autoload."
626 (when (setq acons (memq :autoload body))
629 (names--extract-autoloads (cdr (cdr acons)))))))
632 (defadvice make-autoload (around names-before-make-autoload-advice
633 (form file &optional expansion) activate)
634 "Make sure `make-autoload' understands `define-namespace'.
635 Use the `names--inside-make-autoload' variable to indicate to
636 `define-namespace' that we're generating autoloads."
637 ;; We used to have a letbind here, but this was causing a void
638 ;; variable bug on Emacs 24.3.
640 (if (null (eq (car-safe form) 'define-namespace))
642 (setq names--inside-make-autoload t)
643 (setq form (macroexpand form))
644 (setq names--inside-make-autoload nil)
645 ;; Up to 24.2 `make-autoload' couldn't handle `progn's.
646 (if (version< emacs-version "24.3")
647 (setq ad-return-value
649 (mapcar (lambda (x) (names--make-autoload-compat x file))
651 (ad-set-arg 2 'expansion)
655 (defun names--make-autoload-compat (form file)
656 (if (eq (car-safe form) 'defalias)
658 (make-autoload form file)))
660 (defvar names--ignored-forms '(declare)
661 "The name of functions/macros/special-forms which we return without reading.")
663 (defun names--handle-args (func args)
664 "Generic handling for the form (FUNC . ARGS), without namespacing FUNC."
665 (if (memq func names--ignored-forms)
667 ;; TODO: Speed this up. Just change it to an alist or a hash-table.
668 (let ((handler (intern-soft (format "names--convert-%s" func))))
669 ;; Some function-like forms get special handling.
670 ;; That's anything with a names--convert-%s function defined.
671 (if (fboundp handler)
672 (progn (names--message "Special handling: %s" handler)
673 (funcall handler (cons func args)))
674 ;; If it isn't special, it's either a function or a macro.
675 (names--args-of-function-or-macro func args (names--compat-macrop func))))))
677 (defun names--message (f &rest rest)
678 "If :verbose is on, pass F and REST to `message'."
679 (when (names--keyword :verbose)
680 (apply #'message (concat "[names] " f) rest)))
682 (defun names--warn (f &rest rest)
683 "Pass F and REST to `message', unless byte-compiling or non-interactive."
684 (unless (and (null (names--keyword :verbose))
685 (and (boundp 'byte-compile-function-environment)
686 byte-compile-function-environment))
687 (apply #'message (concat "[names] " f) rest)))
689 (defun names--error-if-using-vars ()
690 "Remind the developer that variables are not customizable."
694 (error "[names] Global value of variable %s should be nil! %s"
695 x "Set it using keywords instead")))
698 (defun names--remove-namespace-from-list (&rest lists)
699 "Return a concatenated un-namespaced version of LISTS.
700 Symbols in LISTS that aren't namespaced are removed, symbols that
701 are namespaced become un-namespaced."
702 (delq nil (mapcar 'names--remove-namespace (apply #'append lists))))
704 (defun names--remove-namespace (symbol)
705 "Return SYMBOL with namespace removed, or nil if it wasn't namespaced."
706 (names--remove-regexp symbol names--regexp))
708 (defun names--remove-protection (symbol)
709 "Remove the leading :: from SYMBOL if possible, otherwise return nil."
710 (names--remove-regexp symbol names--protection))
712 (defun names--remove-regexp (s r)
713 "Return S with regexp R removed, or nil if S didn't match."
714 (let ((name (symbol-name s)))
715 (when (string-match r name)
716 (intern (replace-match "" nil nil name)))))
718 (defun names--quote-p (sbl)
719 "Is SBL a function which quotes its argument?"
720 (memq sbl '(quote function)))
722 (defun names--fboundp (sbl)
723 "Is namespace+SBL a fboundp symbol?"
724 (or (memq sbl names--fbound)
725 (memq sbl names--macro)
726 (and (names--keyword :global)
727 (fboundp (names--prepend sbl)))))
729 (defun names--macrop (sbl)
730 "Is namespace+SBL a fboundp symbol?"
731 (or (memq sbl names--macro)
732 (and (names--keyword :global)
733 (names--compat-macrop (names--prepend sbl)))))
735 (defun names--keyword (keyword)
736 "Was KEYWORD one of the keywords passed to the `namespace' macro?"
737 (assoc keyword names--keywords))
739 (defun names--boundp (sbl)
740 "Is namespace+SBL a boundp symbol?
741 If SBL has a let binding, that takes precendence so this also
743 (and (null (memq sbl names--local-vars))
744 (or (memq sbl names--bound)
745 (and (names--keyword :global)
746 (boundp (names--prepend sbl))))))
748 (defvar names--verbose nil
749 "If non-nil, verbose message are printed regardless of the :verbose keyword.
750 Use this to easily turn on verbosity during tests.")
752 ;; This is calling edebug even on `when' and `unless'
753 (defun names--args-of-function-or-macro (function args macro)
754 "Namespace FUNCTION's arguments ARGS, with special treatment if MACRO is non-nil."
756 (let ((it (names--get-edebug-spec function))
757 (names--verbose (eq function 'push)))
758 (names--message "Edebug-spec of `%s' is %s" function it)
759 ;; Macros where we evaluate all arguments are like functions.
761 (names--args-of-function-or-macro function args nil)
762 ;; Macros where nothing is evaluated we can just return.
765 ;; Other macros are complicated. Ask edebug for help.
766 (names--macro-args-using-edebug (cons function args)))))
767 ;; We just convert the arguments of functions.
768 (cons function (mapcar 'names-convert-form args))))
770 (defun names--get-edebug-spec (name)
771 "Get 'edebug-form-spec property of symbol NAME."
772 ;; Get the spec of symbol resolving all indirection.
776 (and (symbolp indirect)
779 indirect 'edebug-form-spec 'macro))))
780 ;; (edebug-trace "indirection: %s" edebug-form-spec)
781 (setq spec indirect))
784 (defvar names--is-inside-macro nil
785 "Auxiliary var used in `names--macro-args-using-edebug'.")
787 (defvar names--gensym-counter 0
788 "Counter used to uniquify symbols generated `names--gensym'.")
790 (defun names--macro-args-using-edebug (form)
791 "Namespace the arguments of macro FORM by hacking into edebug.
792 This takes advantage of the fact that macros (should) declare a
793 `debug' specification which tells us which arguments are actually
796 Ideally, we would read this specification ourselves and see how
797 it matches (cdr FORM), but that would take a lot of work and
798 we'd be reimplementing something that edebug already does
799 phenomenally. So we hack into edebug instead."
803 ((max-lisp-eval-depth 3000)
806 (names--is-inside-macro form)
807 ;; Prevent excessive messaging.
808 ;; TODO: Don't do this if `message' is advised.
809 ((symbol-function 'message) #'names--edebug-message)
810 ;; Older edebugs have poor `get-edebug-spec'.
811 ((symbol-function 'get-edebug-spec) #'names--get-edebug-spec)
812 ;; Give symbols our own name.
813 ((symbol-function 'cl-gensym) #'names--gensym)
814 ;; Stop at one level deep.
815 ((symbol-function 'edebug-form) #'names--edebug-form)
816 ;; Don't actually wrap anything.
817 ((symbol-function 'edebug-make-enter-wrapper)
818 #'names--edebug-make-enter-wrapper))
822 (goto-char (point-min))
824 (edebug-read-top-level-form))
827 "Couldn't namespace this macro using its (debug ...) declaration: %s"
831 (when (equal (car-safe (cdr-safe er))
832 "Lisp nesting exceeds `max-lisp-eval-depth'")
834 "Lisp nesting exceeded `max-lisp-eval-depth' at the following form: %s"
838 (defvar names--message-backup
839 (if (ad-is-advised 'message)
840 (ad-get-orig-definition 'message)
841 (symbol-function 'message))
842 "Where names stores `message's definition while overriding it.")
844 (defun names--edebug-message (&rest args)
845 (if (or (names--keyword :verbose) names--verbose)
846 (apply names--message-backup args)
847 (when args (apply #'format args))))
849 (defun names--edebug-make-enter-wrapper (forms)
850 (setq edebug-def-name
853 (names--gensym "edebug-anon")))
856 (defun names--gensym (prefix)
857 "Generate a new uninterned symbol.
858 The name is made by appending a number to PREFIX and preppending \"names\", default \"G\"."
859 (let ((num (prog1 names--gensym-counter
860 (setq names--gensym-counter
861 (1+ names--gensym-counter)))))
862 (make-symbol (format "names-%s%d" (if (stringp prefix) prefix "G") num))))
864 (defun names--edebug-form (cursor)
865 "Parse form given by CURSOR using edebug, and namespace it if necessary."
867 ;; Return the instrumented form for the following form.
868 ;; Add the point offsets to the edebug-offset-list for the form.
869 (let* ((form (edebug-top-element-required cursor "Expected form"))
870 (offset (edebug-top-offset cursor))
871 ;; We don't want to convert the entire form that was passed
872 ;; to `names--macro-args-using-edebug', since the head of
873 ;; that was already converted and it would lead to an
875 ;; So we check for (equal names--is-inside-macro form)
876 ;; Simply incrementing a depth counter didn't work, for a
877 ;; reason I can no longer remember.
879 ;; We DO want to convert the arguments that edebug identifies
880 ;; as forms (level-1). And we do that ourselves, don't pass
882 (func (if (or (eq names--is-inside-macro t)
883 (equal names--is-inside-macro form))
884 'identity 'names-convert-form))
885 (names--is-inside-macro
886 (if (eq func 'names-convert-form)
887 t names--is-inside-macro)))
888 (names--message " [Edebug] Ran into this: %S" form)
889 (names--message " Cursor: %S" cursor)
892 ((consp form) ;; The first offset for a list form is for the list form itself.
893 (if (eq func 'names-convert-form)
894 (names-convert-form form)
895 (let* ((head (car form))
896 (spec (and (symbolp head) (get-edebug-spec head)))
897 (new-cursor (edebug-new-cursor form offset)))
898 ;; Find out if this is a defining form from first symbol.
899 ;; An indirect spec would not work here, yet.
900 (if (and (consp spec) (eq '&define (car spec)))
901 (edebug-defining-form
903 (car offset) ;; before the form
904 (edebug-after-offset cursor)
905 (cons (symbol-name head) (cdr spec)))
906 ;; Wrap a regular form.
907 (edebug-list-form new-cursor)))))
912 ;; Anything else is self-evaluating.
914 (edebug-move-cursor cursor))))
916 (defun names--maybe-append-group (form)
917 "Append (:group `names--package') to FORM.
918 Only if the :group keyword was passed to `define-namespace' and
919 if the form doesn't already have a :group."
920 (if (or (null names--group-parent) (memq :group form))
922 (append form `(:group ',(names--package-name)))))
925 ;;; ---------------------------------------------------------------
926 ;;; Interpreting keywords passed to the main macro.
927 (defun names--handle-keyword (body)
928 "Call the function that handles the keyword at the car of BODY.
929 Such function must be listed in `names--keyword-list'. If it is
930 nil, this function just returns.
932 Regardless of whether a function was called, the keyword is added
933 to the variable `names--keywords'.
935 The car of BODY is the keyword itself and the other elements are
936 the keyword arguments, if any."
937 (let ((func (nth 2 (assoc (car body) names--keyword-list))))
939 (apply func (cdr body))
943 ;;; ---------------------------------------------------------------
944 ;;; Interpreting the actual forms found in BODY of the main macro.
946 ;; This is where the heavy work is done.
948 ;; If you'd like to implement support for some special form, simply
949 ;; define a function called `names--convert-FORM-NAME' along the
950 ;; lines of the functions defined below. It will be automatically used
951 ;; whenever that form is found.
953 ;; Defun, defmacro, and defsubst macros are pretty predictable.
954 (defun names--convert-defmacro (form)
955 "Special treatment for `defmacro' FORM."
956 (let* (;; (names--name-already-prefixed t) ;FIXME: Unused?!
958 (spaced-name (names--prepend name))
960 (add-to-list 'names--macro name)
961 (add-to-list 'names--fbound name)
962 ;; Set the macros debug spec if possible. It will be relevant on
964 (when (setq decl (ignore-errors (cond
965 ((eq (car-safe (nth 3 form)) 'declare)
967 ((and (stringp (nth 3 form))
968 (eq (car-safe (nth 4 form)) 'declare))
971 (setq decl (car (cdr-safe (assoc 'debug (cdr decl)))))
972 (when decl (put spaced-name 'edebug-form-spec decl)))
973 ;; Then convert the macro as a defalias.
976 (names--convert-lambda
977 (cons spaced-name (cddr form))))))
978 (defalias 'names--convert-defmacro* 'names--convert-defmacro)
980 (defun names--convert-defvaralias (form)
981 "Special treatment for `defvaralias' FORM."
982 (let ((form (cons (car form)
983 (mapcar #'names-convert-form (cdr form))))
985 (setq name (names--remove-namespace
986 (ignore-errors (eval (cadr form)))))
988 (add-to-list 'names--bound name))
991 (defun names--convert-defalias (form)
992 "Special treatment for `defalias' FORM."
993 (let ((form (cons (car form)
994 (mapcar #'names-convert-form (cdr form))))
996 (setq name (names--remove-namespace
997 (ignore-errors (eval (cadr form)))))
999 (add-to-list 'names--fbound name))
1002 (defun names--convert-defvar (form &optional dont-add)
1003 "Special treatment for `defvar' FORM.
1004 If DONT-ADD is nil, the FORM's `cadr' is added to `names--bound'."
1005 (let ((name (cadr form)))
1007 (add-to-list 'names--bound name))
1011 (names--prepend name))
1012 (mapcar 'names-convert-form (cdr (cdr form))))))
1014 (defalias 'names--convert-defconst 'names--convert-defvar
1015 "Special treatment for `defconst' FORM.")
1017 (defun names--convert-defcustom (form)
1018 "Special treatment for `defcustom' FORM."
1019 (names--maybe-append-group
1020 (names--convert-defvar form)))
1022 (defun names--convert-custom-declare-variable (form)
1023 "Special treatment for `custom-declare-variable' FORM."
1024 (let ((name (eval (cadr form))) ;;ignore-errors
1025 (val (car (cddr form))))
1026 (add-to-list 'names--bound name)
1030 (list 'quote (names--prepend name)) ;cadr
1031 ;; The DEFAULT argument is explicitly evaluated by
1032 ;; `custom-declare-variable', so it should be safe to namespace
1033 ;; even when quoted. Plus, we need to do this because
1034 ;; defcustom quotes this part.
1035 (if (names--quote-p (car-safe val))
1036 (list (car val) (names-convert-form (cadr val)))
1037 (names-convert-form val))
1038 (names-convert-form (car (cdr (cdr (cdr form))))))
1039 (mapcar 'names-convert-form (cdr (cdr (cdr (cdr form))))))))
1041 (defun names--convert-defface (form)
1042 "Special treatment for `defface' FORM.
1043 Identical to defvar, just doesn't add the symbol to the boundp
1044 list. And maybe use a :group."
1045 (names--maybe-append-group
1046 (names--convert-defvar form :dont-add)))
1048 (defun names--convert-define-derived-mode (form)
1049 "Special treatment for `define-derived-mode' FORM."
1050 (let ((name (cadr form)))
1051 (add-to-list 'names--fbound name)
1052 (add-to-list 'names--bound name)
1053 (add-to-list 'names--bound
1054 (intern (format "%s-map" name)))
1055 (add-to-list 'names--bound
1056 (intern (format "%s-hook" name)))
1058 (names--maybe-append-group
1059 ;; And here we namespace it.
1062 (names--prepend name)
1064 (names-convert-form (nth 3 form))
1065 (names-convert-form (nth 4 form))))
1066 (mapcar #'names-convert-form (cddr (cl-cdddr form))))))
1068 (defun names--convert-define-minor-mode (form)
1069 "Special treatment for `define-minor-mode' FORM."
1070 (let ((name (cadr form))
1071 (keymap (nth 5 form)))
1072 ;; Register the mode name
1073 (add-to-list 'names--fbound name)
1074 (add-to-list 'names--bound name)
1075 (add-to-list 'names--bound (intern (format "%s-hook" name)))
1076 ;; Register the keymap
1077 (if (or (null keymap) (null (symbolp keymap)))
1078 (add-to-list 'names--bound (intern (format "%s-map" name)))
1079 (when (setq keymap (names--remove-namespace keymap))
1080 (add-to-list 'names--bound keymap)))
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 (names-convert-form (nth 5 form))
1091 (names-convert-form (nth 6 form))))
1092 (mapcar #'names-convert-form (cddr form)))))
1094 (defun names--convert-define-globalized-minor-mode (form)
1095 "Special treatment for `define-globalized-minor-mode' FORM.
1096 The NAME of the global mode will NOT be namespaced, despite being
1097 a definition. It is kept verbatim.
1098 This is because people tend to name their global modes as
1099 `global-foo-mode', and namespacing would make this impossible.
1101 The MODE and TURN-ON arguments are converted as function names.
1102 Everything else is converted as regular forms (which usually
1103 means no conversion will happen since it's usually keywords and
1105 (let ((name (names--remove-namespace (cadr form)))
1106 (copy (cl-copy-list form)))
1107 ;; Register the mode name
1109 (add-to-list 'names--fbound name)
1110 (add-to-list 'names--bound name)
1111 (add-to-list 'names--bound (intern (format "%s-hook" name))))
1112 (names--maybe-append-group
1113 ;; And here we namespace it.
1118 (names--handle-symbol-as-function (pop copy))
1119 (names--handle-symbol-as-function (pop copy)))
1120 (mapcar #'names-convert-form copy)))))
1121 (defalias 'names--convert-define-global-minor-mode
1122 #'names--convert-define-globalized-minor-mode)
1123 (defalias 'names--convert-easy-mmode-define-global-mode
1124 #'names--convert-define-globalized-minor-mode)
1126 (defun names--convert-quote (form)
1127 "Special treatment for `quote' FORM.
1128 When FORM is (quote argument), argument too arbitrary to be
1129 logically namespaced and is never parsed for namespacing
1130 (but see :assume-var-quote in `names--keyword-list').
1132 When FORM is (function form), a symbol is namespaced as a
1133 function name, a list is namespaced as a lambda form."
1134 (let ((kadr (cadr form))
1135 (this-name (car form)))
1136 (if (and (eq this-name 'function)
1138 (list this-name (names-convert-form kadr))
1141 ;; A symbol inside a function quote should be a function,
1142 ;; unless the user disabled that.
1143 ((and (eq this-name 'function)
1144 (null (names--keyword :dont-assume-function-quote)))
1146 (names--handle-symbol-as-function kadr)))
1148 ;; A symbol inside a regular quote should be a function, if
1149 ;; the user asked for that.
1150 ((and (eq this-name 'quote)
1151 (names--keyword :assume-var-quote))
1153 (or (names--remove-protection kadr)
1154 (if (names--boundp kadr)
1155 (names--prepend kadr)
1161 (defun names--handle-symbol-as-function (s)
1162 "Namespace symbol S as a function name."
1163 (or (names--remove-protection s)
1164 (if (names--fboundp s) (names--prepend s) s)))
1166 (defalias 'names--convert-function 'names--convert-quote)
1168 (defun names--convert-macro (form)
1169 "Special treatment for `macro' form.
1170 Return (macro . (names-convert-form (cdr FORM)))."
1171 (cons 'macro (names-convert-form (cdr form))))
1173 (defun names--convert-lambda (form)
1174 "Special treatment for `lambda' FORM."
1175 (let ((names--local-vars
1176 (append (names--vars-from-arglist (cadr form))
1178 (forms (cdr (cdr form))))
1182 (when (stringp (car forms))
1185 (setq forms (cdr forms))))
1186 (when (eq 'interactive (car-safe (car forms)))
1188 (list (list (car (car forms))
1189 (names-convert-form (cadr (car forms)))))
1190 (setq forms (cdr forms))))
1192 ;; (message "%S" forms)
1193 (mapcar 'names-convert-form forms)))))
1195 (defun names--convert-clojure (form)
1196 "Special treatment for `clojure' FORM."
1197 (names--warn "Found a `closure'! You should use `lambda's instead")
1198 (let ((names--local-vars
1199 (append (names--vars-from-arglist (cadr form))
1200 names--local-vars)))
1203 (names--convert-lambda (cdr form)))))
1205 (defun names--vars-from-arglist (args)
1206 "Get a list of local variables from a generalized arglist ARGS."
1211 (let ((symb (or (cdr-safe (car-safe x)) (car-safe x) x)))
1212 (when (and (symbolp symb)
1213 (null (string-match "^&" (symbol-name symb)))
1218 (defun names--convert-defun (form)
1219 "Special treatment for `defun' FORM."
1220 (let* ((name (cadr form)))
1221 (add-to-list 'names--fbound name)
1223 (names--convert-lambda
1224 (cons (names--prepend name) (cddr form))))))
1225 (defalias 'names--convert-defun* 'names--convert-defun)
1226 (defalias 'names--convert-defsubst 'names--convert-defun)
1227 (defalias 'names--convert-defsubst* 'names--convert-defun)
1229 (defun names--let-var-convert-then-add (sym add)
1230 "Try to convert SYM unless :no-let-vars is in use.
1231 If ADD is non-nil, add resulting symbol to `names--local-vars'."
1232 (let ((name (if (null (names--keyword :no-let-vars))
1233 (names-convert-form sym)
1235 (when add (add-to-list 'names--local-vars name))
1238 (defun names--convert-let (form &optional star)
1239 "Special treatment for `let' FORM.
1240 If STAR is non-nil, parse as a `let*'."
1241 (let* ((names--local-vars names--local-vars)
1246 (list (names--let-var-convert-then-add (car x) star)
1247 (names-convert-form (cadr x)))
1248 (names--let-var-convert-then-add x star)))
1250 ;; Each var defined in a regular `let' only becomes protected after
1251 ;; all others have been defined.
1253 (setq names--local-vars
1255 (mapcar (lambda (x) (or (car-safe x) x)) vars)
1256 names--local-vars)))
1258 (list (car form) vars)
1259 (mapcar 'names-convert-form (cddr form)))))
1261 (defun names--convert-let* (form)
1262 "Special treatment for `let' FORM."
1263 (names--convert-let form t))
1265 (defun names--convert-cond (form)
1266 "Special treatment for `cond' FORM."
1270 (lambda (x) (mapcar #'names-convert-form x))
1273 (defun names--convert-condition-case (form)
1274 "Special treatment for `condition-case' FORM."
1279 (names-convert-form (cadr (cdr form))))
1283 (mapcar 'names-convert-form (cdr x))))
1284 (cddr (cdr form)))))
1287 ;;; names.el ends here